1 Commits

Author SHA1 Message Date
erangel1 2a81bda00e did something 2026-05-19 22:55:26 +02:00
12 changed files with 5774 additions and 213 deletions
+9
View File
@@ -41,6 +41,15 @@ NATS_URL=nats://localhost:4222
# openssl ecparam -genkey -name prime256v1 -noout -out signing-key.pem # openssl ecparam -genkey -name prime256v1 -noout -out signing-key.pem
# ARTIFACT_SIGNING_KEY= # ARTIFACT_SIGNING_KEY=
# ─── SSH Server ────────────────────────────────────────────────────────────────
# Hostname shown in SSH clone URLs. Auto-detected from INSTANCE_URL or request
# Host header when empty.
# SSH_HOST=ssh.example.com
# SSH_PORT=2222
# Path to PEM-encoded SSH host key. If empty, an ephemeral RSA-4096 key is
# generated at startup (host key changes on restart — warns clients).
# SSH_HOST_KEY_PATH=
# ─── OCI Registry (Phase 4) ─────────────────────────────────────────────────── # ─── OCI Registry (Phase 4) ───────────────────────────────────────────────────
# Root directory for the OCI Distribution Spec blob and upload storage. # Root directory for the OCI Distribution Spec blob and upload storage.
OCI_ROOT=/var/lib/forgebucket/oci OCI_ROOT=/var/lib/forgebucket/oci
+5156
View File
File diff suppressed because it is too large Load Diff
+17
View File
@@ -10,8 +10,25 @@
"preview": "vite preview" "preview": "vite preview"
}, },
"dependencies": { "dependencies": {
"@codemirror/autocomplete": "^6.0.0",
"@codemirror/commands": "^6.0.0",
"@codemirror/lang-cpp": "^6.0.0",
"@codemirror/lang-css": "^6.0.0",
"@codemirror/lang-html": "^6.0.0",
"@codemirror/lang-java": "^6.0.0",
"@codemirror/lang-javascript": "^6.2.5", "@codemirror/lang-javascript": "^6.2.5",
"@codemirror/lang-json": "^6.0.0",
"@codemirror/lang-markdown": "^6.0.0",
"@codemirror/lang-python": "^6.0.0",
"@codemirror/lang-rust": "^6.0.0",
"@codemirror/lang-xml": "^6.0.0",
"@codemirror/lang-yaml": "^6.1.3",
"@codemirror/language": "^6.0.0",
"@codemirror/merge": "^6.12.1", "@codemirror/merge": "^6.12.1",
"@codemirror/search": "^6.0.0",
"@codemirror/state": "^6.0.0",
"@codemirror/theme-one-dark": "^6.0.0",
"@codemirror/view": "^6.0.0",
"@tanstack/react-query": "^5.100.9", "@tanstack/react-query": "^5.100.9",
"react": "^19.2.5", "react": "^19.2.5",
"react-dom": "^19.2.5", "react-dom": "^19.2.5",
+137 -16
View File
@@ -1,5 +1,8 @@
import { Link } from 'react-router-dom' import { useRef, useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { useQueryClient } from '@tanstack/react-query'
import { useRepoTree } from '../../api/queries/repos' import { useRepoTree } from '../../api/queries/repos'
import { getCSRFToken } from '../../api/client'
import { Skeleton } from '../../ui/Skeleton' import { Skeleton } from '../../ui/Skeleton'
interface TreeBrowserProps { interface TreeBrowserProps {
@@ -32,23 +35,141 @@ function formatSize(bytes: number): string {
} }
export function TreeBrowser({ owner, repo, ref, path = '' }: TreeBrowserProps) { export function TreeBrowser({ owner, repo, ref, path = '' }: TreeBrowserProps) {
const navigate = useNavigate()
const queryClient = useQueryClient()
const { data: entries, isLoading, isError } = useRepoTree(owner, repo, ref, path) const { data: entries, isLoading, isError } = useRepoTree(owner, repo, ref, path)
const fileInputRef = useRef<HTMLInputElement>(null)
const folderInputRef = useRef<HTMLInputElement>(null)
const zipInputRef = useRef<HTMLInputElement>(null)
const [uploadStatus, setUploadStatus] = useState<string | null>(null)
const [uploading, setUploading] = useState(false)
async function handleUpload(files: FileList | null, isZip = false) {
if (!files || files.length === 0) return
setUploading(true)
setUploadStatus(`Uploading ${isZip ? 'archive' : `${files.length} file${files.length > 1 ? 's' : ''}`}`)
try {
const csrfToken = await getCSRFToken()
const form = new FormData()
form.append('branch', ref || 'main')
form.append('message', isZip ? 'Upload archive' : `Upload ${files.length} file${files.length > 1 ? 's' : ''}`)
if (isZip) {
form.append('zip', files[0])
} else {
for (const file of Array.from(files)) {
const relativePath = (file as File & { webkitRelativePath?: string }).webkitRelativePath || file.name
const f = new File([file], relativePath, { type: file.type })
form.append('file[]', f, relativePath)
}
}
const res = await fetch(`/api/v1/repos/${owner}/${repo}/upload`, {
method: 'POST',
credentials: 'include',
headers: { 'X-CSRF-Token': csrfToken },
body: form,
})
if (!res.ok) {
const err = await res.json().catch(() => ({ error: res.statusText }))
throw new Error(err.error || 'Upload failed')
}
const result = await res.json()
setUploadStatus(`Committed ${result.committed} file${result.committed !== 1 ? 's' : ''}`)
queryClient.invalidateQueries({ queryKey: ['repos', owner, repo, 'tree'] })
queryClient.invalidateQueries({ queryKey: ['repos', owner, repo, 'files'] })
setTimeout(() => setUploadStatus(null), 3000)
} catch (err) {
setUploadStatus(`Error: ${(err as Error).message}`)
setTimeout(() => setUploadStatus(null), 5000)
} finally {
setUploading(false)
if (fileInputRef.current) fileInputRef.current.value = ''
if (folderInputRef.current) folderInputRef.current.value = ''
if (zipInputRef.current) zipInputRef.current.value = ''
}
}
if (isLoading) return <TreeSkeleton /> if (isLoading) return <TreeSkeleton />
if (isError) return <p className="text-xs text-[var(--c-danger)] p-4">Failed to load file tree.</p> if (isError) return <p className="text-xs text-[var(--c-danger)] p-4">Failed to load file tree.</p>
if (!entries?.length) return (
<div className="border border-dashed border-[var(--c-border)] rounded p-6 text-center text-xs text-[var(--c-muted)]">
No files yet push your first commit to see them here.
</div>
)
const dirs = entries.filter(e => e.type === 'tree').sort((a, b) => a.name.localeCompare(b.name)) const dirs = (entries ?? []).filter(e => e.type === 'tree').sort((a, b) => a.name.localeCompare(b.name))
const files = entries.filter(e => e.type === 'blob').sort((a, b) => a.name.localeCompare(b.name)) const files = (entries ?? []).filter(e => e.type === 'blob').sort((a, b) => a.name.localeCompare(b.name))
const sorted = [...dirs, ...files] const sorted = [...dirs, ...files]
return ( return (
<div className="border border-[var(--c-border)] rounded overflow-hidden bg-[var(--c-surface)]"> <div className="border border-[var(--c-border)] rounded overflow-hidden bg-[var(--c-surface)]">
{/* Path breadcrumb inside tree */}
{/* Upload toolbar */}
<div className="flex items-center gap-2 px-3 py-2 bg-[var(--c-surface-muted)] border-b border-[var(--c-border)] flex-wrap">
<button
onClick={() => navigate(`/repos/${owner}/${repo}/blob?ref=${encodeURIComponent(ref || 'main')}&new=true`)}
className="flex items-center gap-1.5 px-2.5 py-1 rounded text-xs font-medium border border-[var(--c-border)] text-[var(--c-text)] hover:bg-[var(--c-surface)] bg-[var(--c-surface)]"
>
<svg width="12" height="12" fill="none" stroke="currentColor" strokeWidth="2.5" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M12 4.5v15m7.5-7.5h-15" />
</svg>
New file
</button>
<button
onClick={() => fileInputRef.current?.click()}
disabled={uploading}
className="flex items-center gap-1.5 px-2.5 py-1 rounded text-xs font-medium border border-[var(--c-border)] text-[var(--c-text)] hover:bg-[var(--c-surface)] bg-[var(--c-surface)] disabled:opacity-50"
>
<svg width="12" height="12" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M3 16.5v2.25A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75V16.5m-13.5-9L12 3m0 0 4.5 4.5M12 3v13.5" />
</svg>
Upload files
</button>
<button
onClick={() => folderInputRef.current?.click()}
disabled={uploading}
className="flex items-center gap-1.5 px-2.5 py-1 rounded text-xs font-medium border border-[var(--c-border)] text-[var(--c-text)] hover:bg-[var(--c-surface)] bg-[var(--c-surface)] disabled:opacity-50"
>
<svg width="12" height="12" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M2.25 12.75V12A2.25 2.25 0 0 1 4.5 9.75h15A2.25 2.25 0 0 1 21.75 12v.75m-8.69-6.44-2.12-2.12a1.5 1.5 0 0 0-1.061-.44H4.5A2.25 2.25 0 0 0 2.25 6v8.25" />
</svg>
Upload folder
</button>
<button
onClick={() => zipInputRef.current?.click()}
disabled={uploading}
className="flex items-center gap-1.5 px-2.5 py-1 rounded text-xs font-medium border border-[var(--c-border)] text-[var(--c-text)] hover:bg-[var(--c-surface)] bg-[var(--c-surface)] disabled:opacity-50"
>
<svg width="12" height="12" fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M20.25 7.5l-.625 10.632a2.25 2.25 0 0 1-2.247 2.118H6.622a2.25 2.25 0 0 1-2.247-2.118L3.75 7.5M10 11.25h4M3.375 7.5h17.25c.621 0 1.125-.504 1.125-1.125v-1.5c0-.621-.504-1.125-1.125-1.125H3.375c-.621 0-1.125.504-1.125 1.125v1.5c0 .621.504 1.125 1.125 1.125Z" />
</svg>
Upload ZIP
</button>
{uploadStatus && (
<span className={`text-xs ml-1 ${uploadStatus.startsWith('Error') ? 'text-[var(--c-danger)]' : 'text-[var(--c-success)]'}`}>
{uploadStatus}
</span>
)}
{/* Hidden file inputs */}
<input ref={fileInputRef} type="file" multiple className="hidden" onChange={e => handleUpload(e.target.files)} />
<input
ref={folderInputRef}
type="file"
className="hidden"
// @ts-expect-error webkitdirectory is not in React types
webkitdirectory=""
multiple
onChange={e => handleUpload(e.target.files)}
/>
<input ref={zipInputRef} type="file" accept=".zip" className="hidden" onChange={e => handleUpload(e.target.files, true)} />
</div>
{/* Path breadcrumb */}
{path && ( {path && (
<div className="flex items-center gap-1 px-3 py-2 bg-[var(--c-surface-muted)] border-b border-[var(--c-border)] text-xs text-[var(--c-muted)]"> <div className="flex items-center gap-1 px-3 py-2 bg-[var(--c-surface-muted)] border-b border-[var(--c-border)] text-xs text-[var(--c-muted)]">
<Link to={`/repos/${owner}/${repo}`} className="hover:text-[var(--c-brand)]">{repo}</Link> <Link to={`/repos/${owner}/${repo}`} className="hover:text-[var(--c-brand)]">{repo}</Link>
@@ -67,6 +188,11 @@ export function TreeBrowser({ owner, repo, ref, path = '' }: TreeBrowserProps) {
</div> </div>
)} )}
{sorted.length === 0 ? (
<div className="p-6 text-center text-xs text-[var(--c-muted)]">
No files yet push your first commit or upload files above.
</div>
) : (
<table className="w-full text-sm border-collapse"> <table className="w-full text-sm border-collapse">
<colgroup> <colgroup>
<col className="w-auto" /> <col className="w-auto" />
@@ -83,7 +209,6 @@ export function TreeBrowser({ owner, repo, ref, path = '' }: TreeBrowserProps) {
return ( return (
<tr key={entry.hash} className="border-b border-[var(--c-border)] last:border-b-0 hover:bg-[var(--c-surface-raised)]"> <tr key={entry.hash} className="border-b border-[var(--c-border)] last:border-b-0 hover:bg-[var(--c-surface-raised)]">
{/* Name */}
<td className="px-3 py-2"> <td className="px-3 py-2">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
{isDir ? ( {isDir ? (
@@ -95,10 +220,7 @@ export function TreeBrowser({ owner, repo, ref, path = '' }: TreeBrowserProps) {
<path strokeLinecap="round" strokeLinejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 0 0-3.375-3.375h-1.5A1.125 1.125 0 0 1 13.5 7.125v-1.5a3.375 3.375 0 0 0-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 0 0-9-9Z" /> <path strokeLinecap="round" strokeLinejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 0 0-3.375-3.375h-1.5A1.125 1.125 0 0 1 13.5 7.125v-1.5a3.375 3.375 0 0 0-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 0 0-9-9Z" />
</svg> </svg>
)} )}
<Link <Link to={href} className={isDir ? 'text-[var(--c-brand)] hover:underline font-medium' : 'text-[var(--c-text)] hover:text-[var(--c-brand)]'}>
to={href}
className={isDir ? 'text-[var(--c-brand)] hover:underline font-medium' : 'text-[var(--c-text)] hover:text-[var(--c-brand)]'}
>
{entry.name} {entry.name}
</Link> </Link>
{!isDir && entry.size > 0 && ( {!isDir && entry.size > 0 && (
@@ -106,11 +228,9 @@ export function TreeBrowser({ owner, repo, ref, path = '' }: TreeBrowserProps) {
)} )}
</div> </div>
</td> </td>
{/* Commit message */}
<td className="px-3 py-2 text-xs text-[var(--c-muted)] truncate max-w-0 hidden sm:table-cell"> <td className="px-3 py-2 text-xs text-[var(--c-muted)] truncate max-w-0 hidden sm:table-cell">
<span className="truncate block" title={entry.commitMsg}>{entry.commitMsg}</span> <span className="truncate block" title={entry.commitMsg}>{entry.commitMsg}</span>
</td> </td>
{/* Date */}
<td className="px-3 py-2 text-xs text-[var(--c-muted)] whitespace-nowrap text-right"> <td className="px-3 py-2 text-xs text-[var(--c-muted)] whitespace-nowrap text-right">
{relativeTime(entry.commitDate)} {relativeTime(entry.commitDate)}
</td> </td>
@@ -119,6 +239,7 @@ export function TreeBrowser({ owner, repo, ref, path = '' }: TreeBrowserProps) {
})} })}
</tbody> </tbody>
</table> </table>
)}
</div> </div>
) )
} }
+4
View File
@@ -43,6 +43,10 @@
--c-warning: #FBBF24; --c-warning: #FBBF24;
} }
html {
font-size: 17px;
}
body { body {
margin: 0; margin: 0;
font-family: system-ui, 'Segoe UI', Roboto, sans-serif; font-family: system-ui, 'Segoe UI', Roboto, sans-serif;
+78 -36
View File
@@ -4,6 +4,8 @@ import ReactMarkdown from 'react-markdown'
import remarkGfm from 'remark-gfm' import remarkGfm from 'remark-gfm'
import { useRepo, useRepoBlob, useUpdateBlob } from '../api/queries/repos' import { useRepo, useRepoBlob, useUpdateBlob } from '../api/queries/repos'
import { RepoListSkeleton } from '../ui/Skeleton' import { RepoListSkeleton } from '../ui/Skeleton'
import { CodeEditor } from '../components/repos/CodeEditor'
import { FileSideTree } from '../components/repos/FileSideTree'
export default function BlobPage() { export default function BlobPage() {
const { owner = '', repo: repoName = '' } = useParams<{ owner: string; repo: string }>() const { owner = '', repo: repoName = '' } = useParams<{ owner: string; repo: string }>()
@@ -14,12 +16,17 @@ export default function BlobPage() {
const [commitMsg, setCommitMsg] = useState('') const [commitMsg, setCommitMsg] = useState('')
const [preview, setPreview] = useState(false) const [preview, setPreview] = useState(false)
// New-file mode: ?new=true&path=<desired-path>
const isNew = searchParams.get('new') === 'true'
const [newPath, setNewPath] = useState(searchParams.get('path') ?? '')
const ref = searchParams.get('ref') ?? '' const ref = searchParams.get('ref') ?? ''
const filePath = searchParams.get('path') ?? '' const filePath = isNew ? newPath : (searchParams.get('path') ?? '')
const fileName = filePath.split('/').pop() ?? filePath const fileName = filePath.split('/').pop() ?? filePath
const fileExt = fileName.includes('.') ? fileName.split('.').pop() ?? '' : ''
const { data: repo } = useRepo(owner, repoName) const { data: repo } = useRepo(owner, repoName)
const { data: blob, isLoading, isError } = useRepoBlob(owner, repoName, ref, filePath) const { data: blob, isLoading, isError } = useRepoBlob(owner, repoName, ref, isNew ? '' : filePath)
const updateBlob = useUpdateBlob(owner, repoName) const updateBlob = useUpdateBlob(owner, repoName)
const branch = ref || repo?.defaultBranch || 'main' const branch = ref || repo?.defaultBranch || 'main'
@@ -33,30 +40,55 @@ export default function BlobPage() {
} }
function cancelEdit() { function cancelEdit() {
if (isNew) {
navigate(-1)
} else {
setEditing(false) setEditing(false)
setPreview(false) setPreview(false)
} }
}
async function handleCommit() { async function handleCommit() {
if (!commitMsg.trim() || !filePath) return const path = isNew ? newPath.trim() : filePath
if (!commitMsg.trim() || !path) return
await updateBlob.mutateAsync({ await updateBlob.mutateAsync({
path: filePath, path,
content: editContent, content: editContent,
message: commitMsg.trim(), message: commitMsg.trim(),
branch, branch,
}) })
setEditing(false) setEditing(false)
navigate(`/repos/${owner}/${repoName}/blob?ref=${encodeURIComponent(branch)}&path=${encodeURIComponent(filePath)}`, { replace: true }) navigate(`/repos/${owner}/${repoName}/blob?ref=${encodeURIComponent(branch)}&path=${encodeURIComponent(path)}`, { replace: true })
} }
if (isLoading) return <div className="p-6"><RepoListSkeleton /></div> const isEditingState = editing || isNew
if (isError || !blob) return <div className="p-6 text-sm text-[var(--c-danger)]">File not found.</div>
const lines = blob.content.split('\n') // For new file, start in edit mode with empty content.
const pathParts = filePath.split('/') if (isNew && !editing && editContent === '') {
setEditContent('')
setCommitMsg('Add new file')
setEditing(true)
}
const pathParts = filePath.split('/').filter(Boolean)
const content = blob?.content ?? ''
return ( return (
<div className="max-w-5xl mx-auto px-4 md:px-6 py-6 space-y-4"> <div className="flex h-full min-h-0" style={{ height: 'calc(100vh - 56px)' }}>
{/* Left file tree — hidden on small screens */}
<div className="hidden md:flex">
<FileSideTree
owner={owner}
repo={repoName}
branch={branch}
activePath={filePath}
/>
</div>
{/* Main content */}
<div className="flex-1 min-w-0 overflow-auto">
<div className="w-full px-4 md:px-6 py-6 space-y-4">
{/* Breadcrumb */} {/* Breadcrumb */}
<div className="flex items-center gap-1 text-sm flex-wrap"> <div className="flex items-center gap-1 text-sm flex-wrap">
@@ -76,21 +108,35 @@ export default function BlobPage() {
</span> </span>
) )
})} })}
{isNew && <span className="text-[var(--c-muted)] font-semibold">New file</span>}
</div> </div>
{/* File card */} {/* File card */}
{isLoading && !isNew && <RepoListSkeleton />}
{(isError && !isNew) && <div className="text-sm text-[var(--c-danger)] p-4">File not found.</div>}
{(!isLoading || isNew) && (
<div className="border border-[var(--c-border)] rounded bg-[var(--c-surface)] overflow-hidden"> <div className="border border-[var(--c-border)] rounded bg-[var(--c-surface)] overflow-hidden">
{/* Toolbar */} {/* Toolbar */}
<div className="flex items-center justify-between px-4 py-2.5 border-b border-[var(--c-border)] bg-[var(--c-surface-raised)] gap-3 flex-wrap"> <div className="flex items-center justify-between px-4 py-2.5 border-b border-[var(--c-border)] bg-[var(--c-surface-raised)] gap-3 flex-wrap">
<div className="flex items-center gap-2 text-sm"> <div className="flex items-center gap-2 text-sm">
{/* Branch pill */}
<span className="flex items-center gap-1 px-2 py-0.5 border border-[var(--c-border)] rounded text-xs text-[var(--c-muted)] bg-[var(--c-surface)]"> <span className="flex items-center gap-1 px-2 py-0.5 border border-[var(--c-border)] rounded text-xs text-[var(--c-muted)] bg-[var(--c-surface)]">
<svg width="12" height="12" fill="none" stroke="currentColor" strokeWidth="1.5" viewBox="0 0 24 24"> <svg width="12" height="12" fill="none" stroke="currentColor" strokeWidth="1.5" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" d="M9.568 3H5.25A2.25 2.25 0 0 0 3 5.25v4.318c0 .597.237 1.17.659 1.591l9.581 9.581c.699.699 1.78.872 2.607.33a18.095 18.095 0 0 0 5.223-5.223c.542-.827.369-1.908-.33-2.607L11.16 3.66A2.25 2.25 0 0 0 9.568 3Z" /> <path strokeLinecap="round" strokeLinejoin="round" d="M9.568 3H5.25A2.25 2.25 0 0 0 3 5.25v4.318c0 .597.237 1.17.659 1.591l9.581 9.581c.699.699 1.78.872 2.607.33a18.095 18.095 0 0 0 5.223-5.223c.542-.827.369-1.908-.33-2.607L11.16 3.66A2.25 2.25 0 0 0 9.568 3Z" />
</svg> </svg>
{branch} {branch}
</span> </span>
{isNew ? (
<input
value={newPath}
onChange={e => setNewPath(e.target.value)}
placeholder="path/to/new-file.ts"
className="border border-[var(--c-border)] rounded px-2 py-0.5 text-xs focus:outline-none focus:border-[var(--c-brand-focus)] text-[var(--c-text)] bg-[var(--c-surface)]"
style={{ minWidth: 200 }}
/>
) : (
<>
<span className="text-[var(--c-muted)]">{repoName}</span> <span className="text-[var(--c-muted)]">{repoName}</span>
<span className="text-[var(--c-muted)]">/</span> <span className="text-[var(--c-muted)]">/</span>
<span className="font-medium text-[var(--c-text)]">{fileName}</span> <span className="font-medium text-[var(--c-text)]">{fileName}</span>
@@ -103,9 +149,11 @@ export default function BlobPage() {
<path strokeLinecap="round" strokeLinejoin="round" d="M15.666 3.888A2.25 2.25 0 0 0 13.5 2.25h-3c-1.03 0-1.9.693-2.166 1.638m7.332 0c.055.194.084.4.084.612v0a.75.75 0 0 1-.75.75H9a.75.75 0 0 1-.75-.75v0c0-.212.03-.418.084-.612m7.332 0c.646.049 1.288.11 1.927.184 1.1.128 1.907 1.077 1.907 2.185V19.5a2.25 2.25 0 0 1-2.25 2.25H6.75A2.25 2.25 0 0 1 4.5 19.5V6.257c0-1.108.806-2.057 1.907-2.185a48.208 48.208 0 0 1 1.927-.184" /> <path strokeLinecap="round" strokeLinejoin="round" d="M15.666 3.888A2.25 2.25 0 0 0 13.5 2.25h-3c-1.03 0-1.9.693-2.166 1.638m7.332 0c.055.194.084.4.084.612v0a.75.75 0 0 1-.75.75H9a.75.75 0 0 1-.75-.75v0c0-.212.03-.418.084-.612m7.332 0c.646.049 1.288.11 1.927.184 1.1.128 1.907 1.077 1.907 2.185V19.5a2.25 2.25 0 0 1-2.25 2.25H6.75A2.25 2.25 0 0 1 4.5 19.5V6.257c0-1.108.806-2.057 1.907-2.185a48.208 48.208 0 0 1 1.927-.184" />
</svg> </svg>
</button> </button>
</>
)}
</div> </div>
{!editing && ( {!isEditingState && (
<div className="flex items-center gap-1"> <div className="flex items-center gap-1">
{isMarkdown && ( {isMarkdown && (
<button <button
@@ -125,7 +173,7 @@ export default function BlobPage() {
Edit Edit
</button> </button>
<button <button
onClick={() => navigator.clipboard.writeText(blob.content)} onClick={() => navigator.clipboard.writeText(content)}
className="px-3 py-1.5 text-xs font-medium border border-[var(--c-border)] rounded text-[var(--c-muted)] hover:bg-[var(--c-surface-muted)]" className="px-3 py-1.5 text-xs font-medium border border-[var(--c-border)] rounded text-[var(--c-muted)] hover:bg-[var(--c-surface-muted)]"
> >
Copy Copy
@@ -134,15 +182,14 @@ export default function BlobPage() {
)} )}
</div> </div>
{/* Content */} {/* Content area */}
{editing ? ( {isEditingState ? (
<div className="flex flex-col"> <div className="flex flex-col">
<textarea <CodeEditor
value={editContent} value={editContent}
onChange={e => setEditContent(e.target.value)} onChange={setEditContent}
className="w-full font-mono text-xs text-[var(--c-text)] bg-[var(--c-surface)] p-4 resize-none focus:outline-none border-b border-[var(--c-border)]" language={isNew ? (newPath.split('.').pop() ?? '') : fileExt}
style={{ minHeight: Math.max(300, lines.length * 20) }} minHeight="400px"
spellCheck={false}
/> />
<div className="p-4 bg-[var(--c-surface-raised)] border-t border-[var(--c-border)] space-y-3"> <div className="p-4 bg-[var(--c-surface-raised)] border-t border-[var(--c-border)] space-y-3">
<div> <div>
@@ -157,10 +204,10 @@ export default function BlobPage() {
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<button <button
onClick={handleCommit} onClick={handleCommit}
disabled={updateBlob.isPending || !commitMsg.trim()} disabled={updateBlob.isPending || !commitMsg.trim() || (isNew && !newPath.trim())}
className="px-4 py-2 rounded bg-[var(--c-brand)] text-white text-sm font-medium hover:bg-[var(--c-brand-hover)] disabled:opacity-50" className="px-4 py-2 rounded bg-[var(--c-brand)] text-white text-sm font-medium hover:bg-[var(--c-brand-hover)] disabled:opacity-50"
> >
{updateBlob.isPending ? 'Committing…' : 'Commit changes'} {updateBlob.isPending ? 'Committing…' : isNew ? 'Create file' : 'Commit changes'}
</button> </button>
<button onClick={cancelEdit} className="px-4 py-2 rounded border border-[var(--c-border)] text-sm text-[var(--c-text)] hover:bg-[var(--c-surface-muted)]"> <button onClick={cancelEdit} className="px-4 py-2 rounded border border-[var(--c-border)] text-sm text-[var(--c-text)] hover:bg-[var(--c-surface-muted)]">
Cancel Cancel
@@ -176,25 +223,20 @@ export default function BlobPage() {
prose-headings:text-[var(--c-text)] prose-headings:font-semibold prose-headings:border-b prose-headings:border-[var(--c-border)] prose-headings:pb-1 prose-headings:text-[var(--c-text)] prose-headings:font-semibold prose-headings:border-b prose-headings:border-[var(--c-border)] prose-headings:pb-1
prose-a:text-[var(--c-brand)] prose-code:bg-[var(--c-surface-muted)] prose-code:px-1 prose-code:rounded prose-a:text-[var(--c-brand)] prose-code:bg-[var(--c-surface-muted)] prose-code:px-1 prose-code:rounded
prose-pre:bg-[var(--c-surface-muted)] prose-pre:border prose-pre:border-[var(--c-border)] prose-pre:rounded"> prose-pre:bg-[var(--c-surface-muted)] prose-pre:border prose-pre:border-[var(--c-border)] prose-pre:rounded">
<ReactMarkdown remarkPlugins={[remarkGfm]}>{blob.content}</ReactMarkdown> <ReactMarkdown remarkPlugins={[remarkGfm]}>{content}</ReactMarkdown>
</div> </div>
) : ( ) : (
<div className="overflow-x-auto"> <CodeEditor
<table className="w-full border-collapse font-mono text-xs"> value={content}
<tbody> language={fileExt}
{lines.map((line, i) => ( readOnly
<tr key={i} className="hover:bg-[#FFFBDD]"> minHeight="400px"
<td className="select-none text-right text-[var(--c-muted)] px-4 py-0.5 w-12 border-r border-[var(--c-border)] bg-[var(--c-surface-raised)] sticky left-0"> />
{i + 1} )}
</td>
<td className="px-4 py-0.5 text-[var(--c-text)] whitespace-pre">{line || ' '}</td>
</tr>
))}
</tbody>
</table>
</div> </div>
)} )}
</div> </div>
</div> </div>
</div>
) )
} }
+16 -6
View File
@@ -18,6 +18,7 @@ export default function RepoPage() {
const [showBranches, setShowBranches] = useState(false) const [showBranches, setShowBranches] = useState(false)
const [showClone, setShowClone] = useState(false) const [showClone, setShowClone] = useState(false)
const [cloneTab, setCloneTab] = useState<'https' | 'ssh'>('https') const [cloneTab, setCloneTab] = useState<'https' | 'ssh'>('https')
const [cloneCopied, setCloneCopied] = useState(false)
const branchRef = useRef<HTMLDivElement>(null) const branchRef = useRef<HTMLDivElement>(null)
const cloneRef = useRef<HTMLDivElement>(null) const cloneRef = useRef<HTMLDivElement>(null)
@@ -47,8 +48,8 @@ export default function RepoPage() {
const branch = ref || repo.defaultBranch const branch = ref || repo.defaultBranch
const cloneUrl = `${window.location.origin}/${owner}/${repoName}.git` const cloneUrl = `${window.location.origin}/${owner}/${repoName}.git`
const sshHost = instance?.sshHost ?? window.location.hostname const sshHost = instance?.sshHost || window.location.hostname
const sshPort = instance?.sshPort ?? '2222' const sshPort = instance?.sshPort || '2222'
const sshUrl = sshPort === '22' const sshUrl = sshPort === '22'
? `git@${sshHost}:${owner}/${repoName}.git` ? `git@${sshHost}:${owner}/${repoName}.git`
: `ssh://git@${sshHost}:${sshPort}/${owner}/${repoName}.git` : `ssh://git@${sshHost}:${sshPort}/${owner}/${repoName}.git`
@@ -162,15 +163,24 @@ export default function RepoPage() {
{cloneTab === 'https' ? cloneUrl : sshUrl} {cloneTab === 'https' ? cloneUrl : sshUrl}
</code> </code>
<button <button
onClick={() => navigator.clipboard.writeText(cloneTab === 'https' ? cloneUrl : sshUrl)} onClick={() => {
className="text-[10px] text-[var(--c-brand)] hover:underline shrink-0" navigator.clipboard.writeText(cloneTab === 'https' ? cloneUrl : sshUrl)
setCloneCopied(true)
setTimeout(() => setCloneCopied(false), 1500)
}}
className={`text-[10px] font-medium shrink-0 transition-colors ${
cloneCopied
? 'text-[var(--c-success)]'
: 'text-[var(--c-brand)] hover:underline'
}`}
> >
Copy {cloneCopied ? 'Copied!' : 'Copy'}
</button> </button>
</div> </div>
{cloneTab === 'ssh' && ( {cloneTab === 'ssh' && (
<p className="text-[10px] text-[var(--c-muted)] mt-1.5"> <p className="text-[10px] text-[var(--c-muted)] mt-1.5">
Requires an SSH key added to your account settings. Requires an SSH key added to your{' '}
<Link to="/settings" className="text-[var(--c-brand)] hover:underline">account settings</Link>.
</p> </p>
)} )}
</div> </div>
+6 -3
View File
@@ -28,9 +28,12 @@ func (h *InstanceHandler) Get(w http.ResponseWriter, r *http.Request) {
}) })
} }
// sshHost extracts the hostname from InstanceURL. Falls back to the request // sshHost resolves the SSH hostname to display in clone URLs.
// host when InstanceURL is unset (common in local development). // Priority: SSH_HOST env var > InstanceURL hostname > request Host header > localhost.
func (h *InstanceHandler) sshHost(r *http.Request) string { func (h *InstanceHandler) sshHost(r *http.Request) string {
if h.cfg.SSHHost != "" {
return h.cfg.SSHHost
}
if h.cfg.InstanceURL != "" { if h.cfg.InstanceURL != "" {
if u, err := url.Parse(h.cfg.InstanceURL); err == nil && u.Hostname() != "" { if u, err := url.Parse(h.cfg.InstanceURL); err == nil && u.Hostname() != "" {
return u.Hostname() return u.Hostname()
@@ -41,5 +44,5 @@ func (h *InstanceHandler) sshHost(r *http.Request) string {
if u, err := url.Parse("http://" + host); err == nil { if u, err := url.Parse("http://" + host); err == nil {
return u.Hostname() return u.Hostname()
} }
return host return "localhost"
} }
+124 -6
View File
@@ -1,7 +1,10 @@
package handlers package handlers
import ( import (
"archive/zip"
"bytes"
"encoding/json" "encoding/json"
"fmt"
"io" "io"
"net/http" "net/http"
"net/url" "net/url"
@@ -653,6 +656,7 @@ func (h *RepoHandler) lookupRepo(w http.ResponseWriter, r *http.Request) (*model
// SearchFiles handles GET /repos/{owner}/{repo}/files?q=...&ref=... // SearchFiles handles GET /repos/{owner}/{repo}/files?q=...&ref=...
// Returns up to 20 matching file paths (case-insensitive substring match). // Returns up to 20 matching file paths (case-insensitive substring match).
// When q is empty, returns all file paths up to 500 (used by the sidebar tree).
func (h *RepoHandler) SearchFiles(w http.ResponseWriter, r *http.Request) { func (h *RepoHandler) SearchFiles(w http.ResponseWriter, r *http.Request) {
repo, ok := h.lookupRepo(w, r) repo, ok := h.lookupRepo(w, r)
if !ok { if !ok {
@@ -660,17 +664,17 @@ func (h *RepoHandler) SearchFiles(w http.ResponseWriter, r *http.Request) {
} }
query := strings.TrimSpace(r.URL.Query().Get("q")) query := strings.TrimSpace(r.URL.Query().Get("q"))
if query == "" {
jsonOK(w, []string{})
return
}
ref := r.URL.Query().Get("ref") ref := r.URL.Query().Get("ref")
if ref == "" { if ref == "" {
ref = repo.DefaultBranch ref = repo.DefaultBranch
} }
files, err := gitdomain.SearchFiles(repo.DiskPath, ref, query, 20) limit := 20
if query == "" {
limit = 500
}
files, err := gitdomain.SearchFiles(repo.DiskPath, ref, query, limit)
if err != nil { if err != nil {
jsonError(w, "search failed", http.StatusInternalServerError) jsonError(w, "search failed", http.StatusInternalServerError)
return return
@@ -680,3 +684,117 @@ func (h *RepoHandler) SearchFiles(w http.ResponseWriter, r *http.Request) {
} }
jsonOK(w, files) jsonOK(w, files)
} }
// UploadFiles handles POST /repos/{owner}/{repo}/upload — multipart upload.
// Accepts multiple regular files (field "file[]") and/or a ZIP archive (field "zip").
// All files are committed in a single git commit.
func (h *RepoHandler) UploadFiles(w http.ResponseWriter, r *http.Request) {
repo, ok := h.lookupRepo(w, r)
if !ok {
return
}
username, _ := r.Context().Value(middleware.ContextKeyUsername).(string)
if !HasPermission(h.db, repo, username, "write") {
jsonError(w, "you do not have write access to this repository", http.StatusForbidden)
return
}
const maxUpload = 50 << 20 // 50 MB
if err := r.ParseMultipartForm(maxUpload); err != nil {
jsonError(w, "could not parse upload: "+err.Error(), http.StatusBadRequest)
return
}
branch := r.FormValue("branch")
if branch == "" {
branch = repo.DefaultBranch
}
message := r.FormValue("message")
if message == "" {
message = "Upload files"
}
var uploads []gitdomain.FileUpload
// Regular files (field "file[]" or "file"). Browser sends webkitRelativePath
// via the custom header X-File-Path; fall back to the bare filename.
for _, fhs := range r.MultipartForm.File {
for _, fh := range fhs {
if fh.Size == 0 {
continue
}
f, err := fh.Open()
if err != nil {
continue
}
data, err := io.ReadAll(io.LimitReader(f, 10<<20)) // 10 MB per file
f.Close()
if err != nil {
continue
}
// Prefer the relative path sent by the browser (folder upload),
// otherwise use the bare filename.
relPath := fh.Filename
if rp := fh.Header.Get("X-File-Path"); rp != "" {
relPath = rp
}
if strings.EqualFold(fh.Header.Get("Content-Disposition"), "") {
// Skip the "zip" field — handled separately below.
}
clean := filepath.Clean(filepath.FromSlash(relPath))
if strings.HasPrefix(clean, "..") || filepath.IsAbs(clean) {
jsonError(w, fmt.Sprintf("invalid path: %s", relPath), http.StatusBadRequest)
return
}
uploads = append(uploads, gitdomain.FileUpload{Path: clean, Content: data})
}
}
// ZIP archive (field "zip").
if zipFHs, ok := r.MultipartForm.File["zip"]; ok && len(zipFHs) > 0 {
fh := zipFHs[0]
f, err := fh.Open()
if err == nil {
zipData, err := io.ReadAll(io.LimitReader(f, maxUpload))
f.Close()
if err == nil {
zr, err := zip.NewReader(bytes.NewReader(zipData), int64(len(zipData)))
if err == nil {
for _, zf := range zr.File {
if zf.FileInfo().IsDir() {
continue
}
clean := filepath.Clean(filepath.FromSlash(zf.Name))
if strings.HasPrefix(clean, "..") || filepath.IsAbs(clean) {
continue
}
rc, err := zf.Open()
if err != nil {
continue
}
data, err := io.ReadAll(io.LimitReader(rc, 10<<20))
rc.Close()
if err != nil {
continue
}
uploads = append(uploads, gitdomain.FileUpload{Path: clean, Content: data})
}
}
}
}
}
if len(uploads) == 0 {
jsonError(w, "no files found in upload", http.StatusBadRequest)
return
}
if err := gitdomain.WriteManyFiles(repo.DiskPath, branch, message, username, username+"@forgebucket", uploads); err != nil {
jsonError(w, "commit failed: "+err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]int{"committed": len(uploads)}) //nolint:errcheck
}
+1
View File
@@ -184,6 +184,7 @@ func New(cfg *config.Config, engine *xorm.Engine, store sessions.Store, bus even
r.Get("/archive", archiveH.Download) r.Get("/archive", archiveH.Download)
r.Get("/insights", insightsH.Get) r.Get("/insights", insightsH.Get)
r.Get("/files", repoH.SearchFiles) r.Get("/files", repoH.SearchFiles)
r.With(csrf).Post("/upload", repoH.UploadFiles)
r.Get("/diff", repoH.Diff) r.Get("/diff", repoH.Diff)
r.Route("/pulls", func(r chi.Router) { r.Route("/pulls", func(r chi.Router) {
r.Get("/", prH.List) r.Get("/", prH.List)
+2
View File
@@ -45,6 +45,7 @@ type Config struct {
OCIRoot string OCIRoot string
// SSH server // SSH server
SSHHost string // env: SSH_HOST, empty = auto-detect from request/instance URL
SSHPort string // env: SSH_PORT, default "2222" SSHPort string // env: SSH_PORT, default "2222"
SSHHostKeyPath string // env: SSH_HOST_KEY_PATH, empty = generate ephemeral SSHHostKeyPath string // env: SSH_HOST_KEY_PATH, empty = generate ephemeral
@@ -72,6 +73,7 @@ func Load() (*Config, error) {
cfg.SessionSecret = requireEnv("SESSION_SECRET", &missing) cfg.SessionSecret = requireEnv("SESSION_SECRET", &missing)
cfg.CSRFSecret = requireEnv("CSRF_SECRET", &missing) cfg.CSRFSecret = requireEnv("CSRF_SECRET", &missing)
cfg.SSHHost = os.Getenv("SSH_HOST")
cfg.SSHPort = getEnv("SSH_PORT", "2222") cfg.SSHPort = getEnv("SSH_PORT", "2222")
cfg.SSHHostKeyPath = os.Getenv("SSH_HOST_KEY_PATH") cfg.SSHHostKeyPath = os.Getenv("SSH_HOST_KEY_PATH")
+78
View File
@@ -253,6 +253,84 @@ func WriteFile(repoPath, branch, filePath, content, authorName, authorEmail, mes
return nil return nil
} }
// FileUpload holds a file path and its content for a batch commit.
type FileUpload struct {
Path string // repo-relative path, e.g. "src/main.go"
Content []byte
}
// WriteManyFiles commits all files in a single commit to branch. Each file path
// must be a clean relative path — no ".." or absolute paths allowed.
func WriteManyFiles(repoPath, branch, message, authorName, authorEmail string, files []FileUpload) error {
if len(files) == 0 {
return errors.New("no files to commit")
}
// Validate all paths before touching the filesystem.
for _, f := range files {
clean := filepath.Clean(filepath.FromSlash(f.Path))
if strings.HasPrefix(clean, "..") || filepath.IsAbs(clean) {
return fmt.Errorf("invalid file path: %s", f.Path)
}
}
tmpDir, err := os.MkdirTemp("", "fb-upload-*")
if err != nil {
return fmt.Errorf("mktemp: %w", err)
}
baseEnv := []string{"GIT_TERMINAL_PROMPT=0", "HOME=/tmp"}
authorEnv := append(baseEnv,
"GIT_AUTHOR_NAME="+authorName,
"GIT_AUTHOR_EMAIL="+authorEmail,
"GIT_COMMITTER_NAME="+authorName,
"GIT_COMMITTER_EMAIL="+authorEmail,
)
addWt := exec.Command("git", "worktree", "add", "--force", tmpDir, branch)
addWt.Dir = filepath.Clean(repoPath)
addWt.Env = baseEnv
if out, err := addWt.CombinedOutput(); err != nil {
os.RemoveAll(tmpDir)
return fmt.Errorf("worktree add: %w: %s", err, out)
}
defer func() {
rmWt := exec.Command("git", "worktree", "remove", "--force", tmpDir)
rmWt.Dir = filepath.Clean(repoPath)
rmWt.Env = baseEnv
rmWt.Run()
os.RemoveAll(tmpDir)
}()
for _, f := range files {
clean := filepath.Clean(filepath.FromSlash(f.Path))
fullPath := filepath.Join(tmpDir, clean)
if err := os.MkdirAll(filepath.Dir(fullPath), 0755); err != nil {
return fmt.Errorf("mkdirall %s: %w", clean, err)
}
if err := os.WriteFile(fullPath, f.Content, 0644); err != nil {
return fmt.Errorf("writefile %s: %w", clean, err)
}
}
addC := exec.Command("git", "add", ".")
addC.Dir = tmpDir
addC.Env = authorEnv
if out, err := addC.CombinedOutput(); err != nil {
return fmt.Errorf("git add: %w: %s", err, out)
}
commitC := exec.Command("git", "commit", "-m", message)
commitC.Dir = tmpDir
commitC.Env = authorEnv
if out, err := commitC.CombinedOutput(); err != nil {
return fmt.Errorf("git commit: %w: %s", err, out)
}
return nil
}
type Branch struct { type Branch struct {
Name string `json:"name"` Name string `json:"name"`
} }