|
| 1 | +import { diffArrays } from 'diff'; |
| 2 | +import type { Plan } from './plan.ts'; |
| 3 | + |
| 4 | +export interface FileVersion { oid: string; mode: string; text: string | null } |
| 5 | +export interface ContextRange { oldStart: number; oldCount: number; newStart: number; newCount: number; name: string } |
| 6 | +export interface FileDelta { |
| 7 | + oldPath: string | null; newPath: string | null; |
| 8 | + before: FileVersion | null; after: FileVersion | null; |
| 9 | + contexts: ContextRange[]; |
| 10 | +} |
| 11 | +export interface CommitDelta { sha: string; parent: string; files: FileDelta[] } |
| 12 | +export interface History { base: string; head: string; commits: CommitDelta[]; final: FileDelta[] } |
| 13 | +export interface Segment { |
| 14 | + path: string; oldPath: string | null; kind: 'text' | 'file'; |
| 15 | + /** Null means a foreign commit. Caller-supplied ledger is the sole authority. */ |
| 16 | + owners: (string | null)[]; |
| 17 | + row: string; scope: 'in-scope' | 'out-of-scope' | 'unplanned' | 'ambiguous'; |
| 18 | + oldLine: number | null; newLine: number | null; operation: '+' | '-' | null; |
| 19 | + content: string; context: string; hunk: number; sharesHunkWith: string[]; |
| 20 | +} |
| 21 | +interface TrackedLine { text: string; owners: (string | null)[]; origins: string[]; movedOwners: (string | null)[] } |
| 22 | +interface TrackedFile { lines: TrackedLine[]; metadataOwners: (string | null)[] } |
| 23 | +const lines = (text: string | null | undefined): string[] => text?.match(/[^\n]*\n|[^\n]+$/g) ?? []; |
| 24 | +const unique = <T>(values: T[]): T[] => [...new Set(values)]; |
| 25 | +const origin = (path: string, i: number) => `${path}\0${i}`; |
| 26 | +function textFile(file: FileVersion | null): boolean { |
| 27 | + return file !== null && file.text !== null && ['100644', '100755'].includes(file.mode); |
| 28 | +} |
| 29 | +function metadataChange(delta: FileDelta): boolean { |
| 30 | + return delta.oldPath !== delta.newPath || delta.before?.mode !== delta.after?.mode || |
| 31 | + !textFile(delta.before) || !textFile(delta.after); |
| 32 | +} |
| 33 | +function classify(plan: Plan, owners: (string | null)[], paths: string[]): Pick<Segment, 'row' | 'scope'> { |
| 34 | + if (!owners.length || owners.includes(null)) return { row: 'Unplanned', scope: 'unplanned' }; |
| 35 | + if (owners.length > 1) return { row: 'Ambiguous', scope: 'ambiguous' }; |
| 36 | + const item = plan.items.find(item => item.id === owners[0]); |
| 37 | + if (!item) throw new Error(`Ledger references unknown plan item ${owners[0]}.`); |
| 38 | + const declared = new Set(item.files.flatMap(file => [file.path, ...(file.renamed_from ? [file.renamed_from] : [])])); |
| 39 | + return { row: item.id, scope: paths.every(path => declared.has(path)) ? 'in-scope' : 'out-of-scope' }; |
| 40 | +} |
| 41 | + |
| 42 | +/** Replays a linear history. Commit messages and Plan-Item trailers are never trusted. */ |
| 43 | +export function linkHistory(plan: Plan, history: History, ledger: ReadonlyMap<string, string>): Segment[] { |
| 44 | + const files = new Map<string, TrackedFile>(); |
| 45 | + const removed = new Map<string, (string | null)[]>(); |
| 46 | + // Deletions retain metadata even after the file leaves the tree. |
| 47 | + const metadata = new Map<string, (string | null)[]>(); |
| 48 | + let parent = history.base; |
| 49 | + for (const commit of history.commits) { |
| 50 | + if (commit.parent !== parent) throw new Error('Linking requires a contiguous linear history.'); |
| 51 | + parent = commit.sha; |
| 52 | + const owner = ledger.get(commit.sha) ?? null; |
| 53 | + if (owner !== null && !plan.items.some(item => item.id === owner)) throw new Error(`Unknown ledger item: ${owner}`); |
| 54 | + for (const delta of commit.files) { |
| 55 | + const oldPath = delta.oldPath; |
| 56 | + const path = delta.newPath ?? oldPath!; |
| 57 | + let previous = oldPath ? files.get(oldPath) : undefined; |
| 58 | + if (!previous) previous = { |
| 59 | + lines: lines(textFile(delta.before) ? delta.before!.text : '').map((text, i) => ({ text, owners: [], origins: [origin(oldPath!, i)], movedOwners: [] })), |
| 60 | + metadataOwners: [], |
| 61 | + }; |
| 62 | + const next: TrackedLine[] = []; |
| 63 | + const changes = diffArrays(previous.lines.map(line => line.text), lines(textFile(delta.after) ? delta.after!.text : ''), { timeout: 2000 }); |
| 64 | + if (!changes) throw new Error('Line attribution exceeded the diff time budget.'); |
| 65 | + let cursor = 0; |
| 66 | + for (let n = 0; n < changes.length; n++) { |
| 67 | + const change = changes[n]!; |
| 68 | + if (!change.added && !change.removed) { next.push(...previous.lines.slice(cursor, cursor + change.value.length)); cursor += change.value.length; continue; } |
| 69 | + const deleted = change.removed ? previous.lines.slice(cursor, cursor + change.value.length) : []; |
| 70 | + if (change.removed) cursor += change.value.length; |
| 71 | + const owners = unique([...deleted.flatMap(line => line.owners), owner]); |
| 72 | + const origins = unique(deleted.flatMap(line => line.origins)); |
| 73 | + for (const id of origins) removed.set(id, owners); |
| 74 | + const added = change.added ? change : changes[n + 1]?.added ? changes[++n]! : undefined; |
| 75 | + if (added) for (const text of added.value) next.push({ text, owners, origins, movedOwners: unique(deleted.flatMap(line => line.movedOwners)) }); |
| 76 | + } |
| 77 | + if (oldPath && delta.newPath && oldPath !== delta.newPath) { |
| 78 | + for (let i = 0; i < next.length; i++) { |
| 79 | + const line = next[i]!; |
| 80 | + next[i] = { ...line, movedOwners: unique([...line.movedOwners, owner]) }; |
| 81 | + for (const id of line.origins) if (!removed.has(id)) removed.set(id, unique([...line.owners, owner])); |
| 82 | + } |
| 83 | + } |
| 84 | + const metadataOwners = metadataChange(delta) ? unique([...previous.metadataOwners, owner]) : previous.metadataOwners; |
| 85 | + if (oldPath) { files.delete(oldPath); metadata.set(oldPath, metadataOwners); } |
| 86 | + if (delta.newPath) { files.set(delta.newPath, { lines: next, metadataOwners }); metadata.set(delta.newPath, metadataOwners); } |
| 87 | + } |
| 88 | + } |
| 89 | + if (parent !== history.head) throw new Error('History does not end at the requested head.'); |
| 90 | + const segments: Segment[] = []; |
| 91 | + for (const delta of history.final) { |
| 92 | + const path = delta.newPath ?? delta.oldPath!; |
| 93 | + const tracked = delta.newPath ? files.get(delta.newPath) : undefined; |
| 94 | + const oldLines = lines(textFile(delta.before) ? delta.before!.text : ''); |
| 95 | + const newLines = lines(textFile(delta.after) ? delta.after!.text : ''); |
| 96 | + let oldIndex = 0, newIndex = 0, hunk = 0; |
| 97 | + const fileSegments: Segment[] = []; |
| 98 | + const affectedPaths = unique([delta.oldPath, delta.newPath].filter((p): p is string => p !== null)); |
| 99 | + const push = (part: Omit<Segment, 'row' | 'scope' | 'sharesHunkWith'>) => fileSegments.push({ |
| 100 | + ...part, ...classify(plan, part.owners, affectedPaths), sharesHunkWith: [], |
| 101 | + }); |
| 102 | + if (metadataChange(delta)) { |
| 103 | + const owners = unique(affectedPaths.flatMap(path => metadata.get(path) ?? [])); |
| 104 | + push({ path, oldPath: delta.oldPath, kind: 'file', owners, oldLine: null, newLine: null, |
| 105 | + operation: null, context: '', hunk: -1, |
| 106 | + content: JSON.stringify({ oldPath: delta.oldPath, newPath: delta.newPath, |
| 107 | + oldMode: delta.before?.mode ?? null, newMode: delta.after?.mode ?? null, |
| 108 | + oldOid: delta.before?.oid ?? null, newOid: delta.after?.oid ?? null }), |
| 109 | + }); |
| 110 | + } |
| 111 | + const finalChanges = diffArrays(oldLines, newLines, { timeout: 2000 }); |
| 112 | + if (!finalChanges) throw new Error('Final diff exceeded the time budget.'); |
| 113 | + for (const change of finalChanges) { |
| 114 | + if (!change.added && !change.removed) { |
| 115 | + oldIndex += change.value.length; newIndex += change.value.length; |
| 116 | + if (change.value.length > 6) hunk++; |
| 117 | + continue; |
| 118 | + } |
| 119 | + for (const text of change.value) { |
| 120 | + const trackedLine = tracked?.lines[newIndex]; |
| 121 | + const owners = change.added |
| 122 | + ? trackedLine?.owners.length ? trackedLine.owners : trackedLine?.movedOwners ?? [] |
| 123 | + : removed.get(origin(delta.oldPath!, oldIndex)) ?? []; |
| 124 | + const context = delta.contexts.find(range => change.added |
| 125 | + ? newIndex + 1 >= range.newStart && newIndex + 1 < range.newStart + range.newCount |
| 126 | + : oldIndex + 1 >= range.oldStart && oldIndex + 1 < range.oldStart + range.oldCount)?.name ?? ''; |
| 127 | + push({ path, oldPath: delta.oldPath, kind: 'text', owners, content: text, context, hunk, |
| 128 | + oldLine: change.removed ? oldIndex + 1 : null, newLine: change.added ? newIndex + 1 : null, |
| 129 | + operation: change.added ? '+' : '-', |
| 130 | + }); |
| 131 | + if (change.added) newIndex++; else oldIndex++; |
| 132 | + } |
| 133 | + } |
| 134 | + // Adjacent lines with identical ownership/context form one segment. |
| 135 | + const grouped: Segment[] = []; |
| 136 | + for (const part of fileSegments) { |
| 137 | + const last = grouped.at(-1); |
| 138 | + if (last && part.kind === 'text' && last.kind === 'text' && last.hunk === part.hunk && |
| 139 | + last.operation === part.operation && last.context === part.context && |
| 140 | + (part.operation === '+' ? last.newLine! + lines(last.content).length === part.newLine : last.oldLine! + lines(last.content).length === part.oldLine) && |
| 141 | + JSON.stringify(last.owners) === JSON.stringify(part.owners)) last.content += part.content; |
| 142 | + else grouped.push({ ...part }); |
| 143 | + } |
| 144 | + for (const part of grouped) part.sharesHunkWith = unique(grouped |
| 145 | + .filter(other => other !== part && other.hunk === part.hunk && other.row !== part.row) |
| 146 | + .flatMap(other => other.owners.filter((owner): owner is string => owner !== null))); |
| 147 | + segments.push(...grouped); |
| 148 | + } |
| 149 | + return segments; |
| 150 | +} |
0 commit comments