import { spawn } from 'node:child_process' import { Buffer } from 'node:buffer' import { createHash } from 'node:crypto' import { resolve } from 'node:path' function joinStdout(chunks) { return Buffer.concat(chunks) } export function runGit(args, { cwd, env, input } = {}) { return new Promise((resolvePromise, rejectPromise) => { const child = spawn('git', args, { cwd, env: { ...process.env, ...env }, stdio: ['pipe', 'pipe', 'pipe'], }) const stdout = [] const stderr = [] child.stdout.on('data', (chunk) => stdout.push(Buffer.from(chunk))) child.stderr.on('data', (chunk) => stderr.push(Buffer.from(chunk))) child.on('error', rejectPromise) child.on('close', (code) => { const out = joinStdout(stdout) const err = joinStdout(stderr) if (code === 0) { resolvePromise(out) return } rejectPromise( new Error( `git ${args.join(' ')} failed with exit code ${code}: ${err.toString('utf8')}`, ), ) }) if (input !== undefined) { child.stdin.end(input) } else { child.stdin.end() } }) } export async function runGitText(args, options = {}) { return (await runGit(args, options)).toString('utf8') } export function resolveRepoDir(env = process.env, fallbackCwd = process.cwd()) { const gitDir = env.GIT_DIR if (!gitDir) { return fallbackCwd } return resolve(fallbackCwd, gitDir, '..') } export async function resolveRefOid(repoDir, ref) { const out = await runGitText(['rev-parse', '--verify', ref], { cwd: repoDir }) return out.trim() } export async function exportFastExport(repoDir, refs) { const uniqueRefs = [...new Set(refs.filter(Boolean))] if (uniqueRefs.length === 0) { return Buffer.alloc(0) } const input = `${uniqueRefs.join('\n')}\n` return runGit(['fast-export', '--stdin', '--signed-tags=verbatim'], { cwd: repoDir, input, }) } function rewriteCommandHeader(line, refMap) { const replacements = ['commit ', 'tag ', 'reset '] for (const prefix of replacements) { if (!line.startsWith(prefix)) continue const ref = line.slice(prefix.length) const replacement = refMap.get(ref) if (!replacement) return line return `${prefix}${replacement}` } return line } export function rewriteFastExportRefs(stream, refMap) { if (stream.length === 0 || refMap.size === 0) { return stream } const pieces = [] let offset = 0 while (offset < stream.length) { const lineEnd = stream.indexOf(0x0a, offset) if (lineEnd === -1) { throw new Error('fast-export stream ended without newline') } const line = stream.toString('utf8', offset, lineEnd) const rewritten = rewriteCommandHeader(line, refMap) pieces.push(Buffer.from(`${rewritten}\n`, 'utf8')) offset = lineEnd + 1 if (line.startsWith('data ')) { const length = Number.parseInt(line.slice(5), 10) if (!Number.isFinite(length) || length < 0) { throw new Error(`invalid fast-export data length: ${line}`) } if (offset + length > stream.length) { throw new Error('fast-export stream ended during data payload') } pieces.push(stream.subarray(offset, offset + length)) offset += length if (offset < stream.length && stream[offset] === 0x0a) { pieces.push(stream.subarray(offset, offset + 1)) offset += 1 } } } return Buffer.concat(pieces) } export async function listLocalRefs(repoDir) { const text = await runGitText( ['for-each-ref', '--format=%(refname)\t%(objectname)'], { cwd: repoDir }, ) return text .split('\n') .map((line) => line.trim()) .filter(Boolean) .map((line) => { const [refname, oid] = line.split('\t') return { refname, oid } }) } export async function listExportableRefs(repoDir) { const refs = (await listLocalRefs(repoDir)).filter( ({ refname }) => refname.startsWith('refs/heads/') || refname.startsWith('refs/tags/'), ) try { await runGitText(['symbolic-ref', '-q', 'HEAD'], { cwd: repoDir }) } catch { refs.push({ refname: 'HEAD', oid: (await resolveRefOid(repoDir, 'HEAD')).trim() }) } return refs } export function sha256Hex(buffer) { return createHash('sha256').update(buffer).digest('hex') }