// Git text representations over the object store (architecture, The engine slot). import { decodeCommit, type GitObjectStore, type Ident } from './objects.ts'; import { diffTrees, lineDiff, unifiedPatch, type TreeChange } from './history.ts'; const decoder = new TextDecoder(); const binary = (bytes: Uint8Array): boolean => bytes.slice(0, 8000).includes(0); const pathName = (path: string): string => /[\s"\\\x00-\x1f]/.test(path) ? JSON.stringify(path) : path; async function bytesOf(store: GitObjectStore, sha?: string, mode?: string): Promise { if (!sha) return new Uint8Array(); if (mode === '160000') return new TextEncoder().encode(`Subproject commit ${sha}\n`); return (await store.read(sha))?.payload ?? new Uint8Array(); } async function fileDiff(store: GitObjectStore, change: TreeChange): Promise<{ text: string; additions: number; deletions: number }> { const oldBytes = await bytesOf(store, change.oldSha, change.oldMode); const newBytes = await bytesOf(store, change.newSha, change.newMode); const left = pathName(`a/${change.path}`), right = pathName(`b/${change.path}`); let text = `diff --git ${left} ${right}\n`; if (!change.oldSha) text += `new file mode ${change.newMode}\n`; else if (!change.newSha) text += `deleted file mode ${change.oldMode}\n`; else if (change.oldMode !== change.newMode) text += `old mode ${change.oldMode}\nnew mode ${change.newMode}\n`; if (change.oldSha === change.newSha) return { text, additions: 0, deletions: 0 }; text += `index ${(change.oldSha ?? '0000000').slice(0, 7)}..${(change.newSha ?? '0000000').slice(0, 7)}${change.oldSha && change.newSha && change.oldMode === change.newMode ? ` ${change.newMode}` : ''}\n`; if (binary(oldBytes) || binary(newBytes)) return { text: `${text}Binary files ${change.oldSha ? left : '/dev/null'} and ${change.newSha ? right : '/dev/null'} differ\n`, additions: 0, deletions: 0 }; const oldText = decoder.decode(oldBytes), newText = decoder.decode(newBytes); const edits = lineDiff(oldText, newText); text += `--- ${change.oldSha ? left : '/dev/null'}\n+++ ${change.newSha ? right : '/dev/null'}\n${unifiedPatch(oldText, newText)}\n`; return { text, additions: edits.filter((edit) => edit.kind === '+').length, deletions: edits.filter((edit) => edit.kind === '-').length }; } /** A complete unified diff between two trees or commits, with null as the empty preimage. */ export async function diffText(store: GitObjectStore, from: string | null, to: string): Promise { const changes = await diffTrees(store, from, to); return (await Promise.all(changes.map((change) => fileDiff(store, change)))).map((file) => file.text).join(''); } function mailDate(author: Ident): string { const sign = author.tz.startsWith('-') ? -1 : 1; const offset = sign * (Number(author.tz.slice(1, 3)) * 60 + Number(author.tz.slice(3, 5))); const date = new Date((author.time + offset * 60) * 1000); const weekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; const pad = (n: number): string => String(n).padStart(2, '0'); return `${weekdays[date.getUTCDay()]}, ${date.getUTCDate()} ${months[date.getUTCMonth()]} ${date.getUTCFullYear()} ${pad(date.getUTCHours())}:${pad(date.getUTCMinutes())}:${pad(date.getUTCSeconds())} ${author.tz}`; } /** One commit as an email patch; series metadata numbers the subject for a comparison's commits. */ export async function formatPatch(store: GitObjectStore, sha: string, series?: { number: number; total: number }): Promise { const object = await store.read(sha); if (!object || object.type !== 'commit') return null; const commit = decodeCommit(object.payload); const changes = await diffTrees(store, commit.parents[0] ?? null, sha); const files = await Promise.all(changes.map((change) => fileDiff(store, change))); const width = Math.max(0, ...changes.map((change) => change.path.length)); const stats = changes.map((change, i) => { const file = files[i]!; return ` ${change.path.padEnd(width)} | ${file.additions + file.deletions} ${'+'.repeat(file.additions)}${'-'.repeat(file.deletions)}\n`; }).join(''); const additions = files.reduce((sum, file) => sum + file.additions, 0), deletions = files.reduce((sum, file) => sum + file.deletions, 0); const summary = `${changes.length} file${changes.length === 1 ? '' : 's'} changed${additions ? `, ${additions} insertion${additions === 1 ? '' : 's'}(+)` : ''}${deletions ? `, ${deletions} deletion${deletions === 1 ? '' : 's'}(-)` : ''}`; const [title = '', ...rest] = commit.message.trimEnd().split('\n'); const body = rest.join('\n').trim(); const numbered = series && series.total > 1 ? ` ${series.number}/${series.total}` : ''; return `From ${sha} Mon Sep 17 00:00:00 2001\nFrom: ${commit.author.name} <${commit.author.email}>\nDate: ${mailDate(commit.author)}\nSubject: [PATCH${numbered}] ${title}\n\n${body ? `${body}\n\n` : ''}---\n${stats} ${summary}\n\n${files.map((file) => file.text).join('')}`; } /** Submodule paths and URLs declared by a .gitmodules file (git configuration syntax). */ export function parseSubmodules(text: string): Array<{ name: string; path: string; url: string }> { const modules: Array<{ name: string; path: string; url: string }> = []; let current: { name: string; path: string; url: string } | undefined; for (const raw of text.split(/\r?\n/)) { const line = raw.trim(); const section = /^\[submodule\s+"((?:[^"\\]|\\.)*)"\]\s*(?:[#;].*)?$/.exec(line); if (section) { current = { name: section[1]!.replace(/\\(.)/g, '$1'), path: '', url: '' }; modules.push(current); continue; } if (line.startsWith('[')) { current = undefined; continue; } const field = /^(path|url)\s*=\s*(.*)$/i.exec(line); if (!current || !field) continue; const value = field[2]!.replace(/\s+[#;].*$/, '').trim(); current[field[1]!.toLowerCase() as 'path' | 'url'] = value.startsWith('"') && value.endsWith('"') ? value.slice(1, -1).replace(/\\(.)/g, '$1') : value; } return modules.filter((module) => module.path && module.url); } /** A repository-relative symbolic-link target; targets escaping the repository have no local path. */ export function symlinkPath(path: string, target: string): string | undefined { if (target.startsWith('/')) return undefined; const segments = path.split('/').slice(0, -1); for (const part of target.split('/')) { if (!part || part === '.') continue; if (part === '..') { if (!segments.length) return undefined; segments.pop(); } else segments.push(part); } return segments.join('/'); }