import { findSweepRepo, ref, sweepBranchPrefix } from './shared.ts' /** Most files one push may change. */ export const maxPushFiles = 300 /** Most total content bytes (decoded) one push may upload. */ export const maxPushBytes = 8 * 1024 * 1024 /** Blob uploads in flight at once. */ const blobConcurrency = 4 export type PushFile = { /** Repo-relative path, forward slashes. */ path: string /** File content. Omit with `delete: true`. */ content?: string /** `base64` for binary-safe content (default `utf-8`). */ encoding?: 'utf-8' | 'base64' /** Git file mode (default `100644`). */ mode?: '100644' | '100755' | '120000' /** Delete this path instead of writing it. */ delete?: boolean } export type PushBranchInput = { /** `owner/name`; must be a sweep repo. */ repo: string /** Head branch; must start with the sweep branch prefix. */ branch: string /** Commit message (required when `files` is set). */ message?: string /** Changes relative to the current branch head (or the base for a new branch). */ files?: Array /** Remote branch head the changes were built on. Refuses when the branch moved. Omit only for a new branch. */ expectedHeadSha?: string | null /** Base branch (default `main`). */ base?: string /** New branch only: base commit the changes were built on (default: current base head). */ baseSha?: string | null /** Open (or find) the PR for this branch after pushing. */ pullRequest?: { title: string; body: string; draft?: boolean } /** Merge the base branch into the open PR's branch (GitHub update-branch) instead of pushing files. */ updateFromBase?: boolean /** Preview only: validate the request and return what would happen. No GitHub calls. */ dryRun?: boolean } export type Request = (params: Record) => Promise<{ ok: boolean; status: number; data: any; text?: string }> const contentWrite = { 'x-kody-secret-resolution': 'headers-only' } const allowedModes = new Set(['100644', '100755', '120000']) function fail(message: string): never { throw new Error(`push-branch: ${message}`) } function decodedSize(file: PushFile) { const content = file.content ?? '' if (file.encoding === 'base64') return Math.floor((content.replace(/=+$/, '').length * 3) / 4) return new TextEncoder().encode(content).length } /** Validates input and returns normalized values. Pure; exported for tests. */ export function validatePushInput(input: PushBranchInput) { const sweepRepo = findSweepRepo(input?.repo) if (!sweepRepo) fail('repo must be one of the sweep repos') const repo = sweepRepo.slug const branch = String(input?.branch ?? '').trim() if (!branch.startsWith(sweepBranchPrefix)) fail(`branch must start with ${sweepBranchPrefix}`) if (!/^[A-Za-z0-9._/-]+$/.test(branch) || branch.includes('..') || branch.endsWith('/') || branch.endsWith('.lock')) { fail('branch has unsupported characters') } const base = String(input?.base ?? ref).trim() || ref if (!/^[A-Za-z0-9._/-]+$/.test(base) || base.includes('..')) fail('base has unsupported characters') const updateFromBase = input?.updateFromBase === true const files = Array.isArray(input?.files) ? input.files : [] if (updateFromBase && files.length) fail('pass either files or updateFromBase, not both') if (!updateFromBase && files.length === 0 && !input?.pullRequest) fail('nothing to do: pass files, pullRequest, or updateFromBase') if (files.length > maxPushFiles) fail(`at most ${maxPushFiles} files per push`) const seen = new Set() let bytes = 0 for (const file of files) { const path = String(file?.path ?? '') if (!path || path.startsWith('/') || path.includes('\\') || path.split('/').some((part) => part === '' || part === '.' || part === '..')) { fail(`invalid path: ${path.slice(0, 200)}`) } if (path === '.git' || path.startsWith('.git/')) fail('paths under .git are not allowed') if (seen.has(path)) fail(`duplicate path: ${path.slice(0, 200)}`) seen.add(path) if (file.mode !== undefined && !allowedModes.has(file.mode)) fail(`unsupported mode for ${path.slice(0, 200)}`) if (file.encoding !== undefined && file.encoding !== 'utf-8' && file.encoding !== 'base64') fail('encoding must be utf-8 or base64') if (file.delete === true) { if (file.content !== undefined) fail(`delete and content both set for ${path.slice(0, 200)}`) continue } if (typeof file.content !== 'string') fail(`content is required for ${path.slice(0, 200)}`) bytes += decodedSize(file) } if (bytes > maxPushBytes) fail(`push is too large (${bytes} bytes, max ${maxPushBytes})`) const message = String(input?.message ?? '').trim() if (files.length && !message) fail('message is required') const expectedHeadSha = input?.expectedHeadSha ? String(input.expectedHeadSha).trim() : null if (expectedHeadSha && !/^[0-9a-f]{40}$/i.test(expectedHeadSha)) fail('expectedHeadSha must be a full 40-character sha') const baseSha = input?.baseSha ? String(input.baseSha).trim() : null if (baseSha && !/^[0-9a-f]{40}$/i.test(baseSha)) fail('baseSha must be a full 40-character sha') const pullRequest = input?.pullRequest ? { title: String(input.pullRequest.title ?? '').trim(), body: String(input.pullRequest.body ?? ''), draft: input.pullRequest.draft === true, } : null if (pullRequest && !pullRequest.title) fail('pullRequest.title is required') return { repo, branch, base, baseSha, files, message, expectedHeadSha, pullRequest, updateFromBase } } async function call(request: Request, params: Record, what: string) { const method = String(params.method ?? 'GET').toUpperCase() const response = await request(method === 'GET' ? params : { ...params, confirm: true }) if (!response.ok) { const detail = String(response.data?.message ?? response.text ?? '').slice(0, 300) fail(`${what} failed (${response.status})${detail ? `: ${detail}` : ''}`) } return response.data } async function readRef(request: Request, repo: string, branch: string) { const response = await request({ method: 'GET', path: `/repos/${repo}/git/ref/heads/${branch}` }) if (response.status === 404) return null if (!response.ok) fail(`read ref ${branch} failed (${response.status})`) const sha = response.data?.object?.sha return typeof sha === 'string' ? sha : null } async function findOpenPr(request: Request, repo: string, branch: string) { const owner = repo.split('/')[0] const list = await call( request, { method: 'GET', path: `/repos/${repo}/pulls`, query: { head: `${owner}:${branch}`, state: 'open', per_page: 5 } }, 'list pull requests', ) const pr = Array.isArray(list) ? list[0] : null return pr ? { number: pr.number as number, url: pr.html_url as string, author: pr.user?.login ?? null } : null } async function mapLimit(items: ReadonlyArray, limit: number, fn: (item: T) => Promise) { const results: Array = new Array(items.length) let next = 0 const workers = Array.from({ length: Math.min(limit, items.length) }, async () => { while (next < items.length) { const index = next++ results[index] = await fn(items[index]) } }) await Promise.all(workers) return results } /** Core push flow with an injected GitHub request (for tests). */ export async function pushBranchWith(request: Request, input: PushBranchInput) { const v = validatePushInput(input) const { repo, branch, base } = v if (v.updateFromBase) { const pr = await findOpenPr(request, repo, branch) if (!pr) fail(`no open PR for ${branch}`) const headSha = await readRef(request, repo, branch) await call( request, { method: 'PUT', path: `/repos/${repo}/pulls/${pr.number}/update-branch`, body: headSha ? { expected_head_sha: headSha } : {} }, 'update branch from base', ) return { ok: true, repo, branch, action: 'update-branch' as const, previousHeadSha: headSha, pr, next: 'Wait a few seconds, then git fetch origin and git reset --hard origin/ before your next change.' } } let commit: { sha: string; url: string; parentSha: string; createdBranch: boolean } | null = null if (v.files.length) { const headSha = await readRef(request, repo, branch) if (headSha && v.expectedHeadSha && headSha.toLowerCase() !== v.expectedHeadSha.toLowerCase()) { fail(`branch moved: remote head is ${headSha}, expected ${v.expectedHeadSha}. git fetch origin, git reset --hard origin/${branch}, reapply, and push again`) } if (headSha && !v.expectedHeadSha) fail(`branch ${branch} exists; pass expectedHeadSha (its current remote head)`) if (!headSha && v.expectedHeadSha) fail(`branch ${branch} does not exist on the remote; omit expectedHeadSha for a new branch`) const parentSha = headSha ?? v.baseSha ?? (await readRef(request, repo, base)) if (!parentSha) fail(`base branch ${base} not found`) const parent = await call(request, { method: 'GET', path: `/repos/${repo}/git/commits/${parentSha}` }, 'read parent commit') const baseTree = parent?.tree?.sha if (typeof baseTree !== 'string') fail('parent commit has no tree') const entries = await mapLimit(v.files, blobConcurrency, async (file) => { const mode = file.mode ?? '100644' if (file.delete === true) return { path: file.path, mode, type: 'blob', sha: null } const blob = await call( request, { method: 'POST', path: `/repos/${repo}/git/blobs`, headers: contentWrite, body: { content: file.content, encoding: file.encoding === 'base64' ? 'base64' : 'utf-8' }, }, `upload ${file.path.slice(0, 200)}`, ) return { path: file.path, mode, type: 'blob', sha: blob?.sha } }) const tree = await call( request, { method: 'POST', path: `/repos/${repo}/git/trees`, headers: contentWrite, body: { base_tree: baseTree, tree: entries } }, 'create tree', ) if (tree?.sha === baseTree) fail('no changes: the files already match the branch head') const created = await call( request, { method: 'POST', path: `/repos/${repo}/git/commits`, headers: contentWrite, body: { message: v.message, tree: tree?.sha, parents: [parentSha] } }, 'create commit', ) const sha = String(created?.sha ?? '') if (!sha) fail('create commit returned no sha') if (headSha) { await call(request, { method: 'PATCH', path: `/repos/${repo}/git/refs/heads/${branch}`, body: { sha, force: false } }, 'update branch') } else { await call(request, { method: 'POST', path: `/repos/${repo}/git/refs`, body: { ref: `refs/heads/${branch}`, sha } }, 'create branch') } commit = { sha, url: `https://github.com/${repo}/commit/${sha}`, parentSha, createdBranch: !headSha } } let pr: { number: number; url: string; author: string | null; created: boolean } | null = null if (v.pullRequest) { const existing = await findOpenPr(request, repo, branch) if (existing) { pr = { ...existing, created: false } } else { const opened = await call( request, { method: 'POST', path: `/repos/${repo}/pulls`, body: { title: v.pullRequest.title, body: v.pullRequest.body, head: branch, base, draft: v.pullRequest.draft }, }, 'open pull request', ) pr = { number: opened?.number, url: opened?.html_url, author: opened?.user?.login ?? null, created: true } } } return { ok: true, repo, branch, action: 'push' as const, commit, pr, next: commit ? `git fetch origin && git reset --hard origin/${branch} (the remote commit replaces your local one)` : null, } }