- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/src/gitview/ingest.ts?version=57&format=json
443 linesFirst import 100%Last change First import in version 0, 1 version changed it
You're reading version 57. The newest is 318, and no version since then changed this file.
1// Plain git in: a person (or a plain agent) cloned a view, made ordinary git
2// commits, and hands the repo back. Each commit is cut into atoms, one per
3// hunk, with the default claims (the "fifteen parallel lines"): the hunks of
4// one commit are written against the same state, so none depends on another.
5// Each commit then gets a tie atom and a label, so the git history survives
6// as labels.
7//
8// The commits sit on a base: the newest commit on the first-parent chain that
9// is either a view commit (a View-Heads trailer naming atoms of this graph)
10// or a commit an earlier ingest already took in (a tie atom carries its sha).
11// The base set is the closure of those heads (or of that tie). When a view
12// commit's tree isn't exactly the projection of its heads but its parent's
13// is, a person amended it: the commit is ingested too, as their own change on
14// top of its heads.
15//
16// The labels chain like git commits: commit i's tie needs its hunks and the
17// tie before it (the first needs the base), and its label's base is the
18// label before it. So closure(tie i) is exactly the state after commit i,
19// and label i holds exactly commit i's hunks and tie.
21import { type CommitObject, readCommit, resolveRef } from "isomorphic-git";
22import {
23 type Atom,
24 type AtomId,
25 type AtomSet,
26 buildAtom,
27 type Conflict,
28 conflicts,
29 diffLines,
30 Graph,
31 type Label,
32 type Mode,
33 project,
34 sortBySeq,
35 splitLines,
36 View,
37} from "../engine/index.ts";
38import { GitViewError } from "./errors.ts";
39import { headsOf, hunkLocation, labelName } from "./plain.ts";
40import {
41 GIT_COMMIT,
42 parseTrailers,
43 splitSubject,
44 stripViewTrailers,
45 trailerValue,
46 VIEW_HEADS,
47 withTrailers,
48} from "./trailers.ts";
49import { type GitContext, gitContext, readTreeFiles, type SkipReason, sameFiles, type TreeFiles } from "./tree.ts";
51export { headsOf, hunkLocation, labelName };
53export interface IngestOptions {
54 /** Claim mode for every hunk atom. Default 'both', the git-like claims. */
55 readonly mode?: Mode;
56 /** Whose first-parent chain to ingest. Default "HEAD". */
57 readonly ref?: string;
58}
60/** A file in a commit that can't be atoms' lines, listed once each time its content changes. */
61export interface SkippedFile {
62 readonly commit: string;
63 readonly path: string;
64 readonly reason: SkipReason;
65}
67export interface IngestBase {
68 /**
69 * The commit the ingested commits sit on. When it is a view commit a person
70 * amended (its tree isn't the projection of its heads), it is also the
71 * first of `commits`.
72 */
73 readonly commit: string;
74 /**
75 * 'view': a view commit whose tree is the projection of its View-Heads.
76 * 'ingested': a commit an earlier ingest took in (ingesting again resumes there).
77 */
78 readonly kind: "view" | "ingested";
79 /** Maximal atoms of the base set. */
80 readonly heads: readonly AtomId[];
81 /**
82 * One atom whose closure is the base set, and the first label's base: the
83 * single head, an anchor (several heads), or the earlier tie. Missing only
84 * when nothing was ingested and the base has several heads but no anchor yet.
85 */
86 readonly atom?: AtomId;
87 /** The earlier ingest's label for the base commit ('ingested' kind), if it has one. */
88 readonly label?: string;
89 /** Set when the base has several heads: the atom that ties them, made by this ingest or an earlier one. */
90 readonly anchor?: AtomId;
91}
93export interface IngestedCommit {
94 /** Full sha of the git commit. */
95 readonly commit: string;
96 readonly label: string;
97 readonly tie: AtomId;
98 /** One atom per hunk, in path then position order. Empty when the commit changed no text. */
99 readonly hunks: readonly AtomId[];
100 readonly author: string;
101 /** Author time in ms. */
102 readonly time: number;
103 readonly message: string;
104}
106export interface IngestResult {
107 readonly base: IngestBase;
108 /** Oldest first. */
109 readonly commits: readonly IngestedCommit[];
110 /** Every new atom (an anchor if one was made, then each commit's hunks and tie), in seq order. */
111 readonly atoms: readonly Atom[];
112 /** One per commit, oldest first. */
113 readonly labels: readonly Label[];
114 /** The shared set with the ingested state added. */
115 readonly shared: Set<AtomId>;
116 /** Atoms of the base that had left the shared set and came back because the ingested atoms need them. */
117 readonly revived: readonly AtomId[];
118 /** Conflicts in the new shared set that involve at least one atom that wasn't in it before. */
119 readonly conflicts: readonly Conflict[];
120 readonly skipped: readonly SkippedFile[];
121}
123interface Pending {
124 readonly oid: string;
125 readonly commit: CommitObject;
126 readonly tree: TreeFiles;
127}
129interface FoundBase {
130 readonly oid: string;
131 readonly commit: CommitObject;
132 readonly tree: TreeFiles;
133 readonly kind: "view" | "ingested";
134 /** 'view': maximal atoms of the View-Heads closure. 'ingested': the tie. */
135 readonly heads: readonly AtomId[];
136 /** Its tree is exactly the base set's projection (otherwise it is ingested too). */
137 readonly exact: boolean;
138}
140/**
141 * Ingest the commits a person made on top of a view. On success the new atoms
142 * and labels are added to `graph` (nothing is added if it throws); the shared
143 * set passed in is not changed, the updated one is returned. Nothing is
144 * written to disk.
145 */
146export async function ingest(
147 graph: Graph,
148 sharedSet: AtomSet,
149 repoDir: string,
150 options: IngestOptions = {},
151): Promise<IngestResult> {
152 const mode = options.mode ?? "both";
153 const ctx = gitContext(repoDir);
155 // Read everything from git first, so a bad repo fails before any atom is built.
156 const { base, pending } = await findBase(ctx, graph, options.ref ?? "HEAD");
157 pending.reverse(); // oldest first
159 const baseLabel = base.kind === "ingested" ? graph.labels().find((l) => l.head === base.heads[0])?.name : undefined;
160 const existingAnchor = base.heads.length > 1 ? findAnchor(graph, base.heads) : undefined;
162 if (pending.length === 0) {
163 const atom = base.heads.length === 1 ? base.heads[0] : existingAnchor;
164 return {
165 base: {
166 commit: base.oid,
167 kind: base.kind,
168 heads: base.heads,
169 ...(atom !== undefined ? { atom } : {}),
170 ...(baseLabel !== undefined ? { label: baseLabel } : {}),
171 ...(existingAnchor !== undefined ? { anchor: existingAnchor } : {}),
172 },
173 commits: [],
174 atoms: [],
175 labels: [],
176 shared: new Set(sharedSet),
177 revived: [],
178 conflicts: [],
179 skipped: [],
180 };
181 }
183 // Build on a copy, then replay onto `graph`, so a failure leaves it untouched.
184 const scratch = Graph.fromJSON(graph.toJSON());
185 const added: Atom[] = [];
186 const accept = (atom: Atom): Atom => {
187 scratch.add(atom);
188 const frozen = scratch.atom(atom.id);
189 added.push(frozen);
190 return frozen;
191 };
193 // The one atom the first label is based on.
194 let anchor = existingAnchor;
195 let baseAtom: AtomId;
196 if (base.heads.length === 1) {
197 baseAtom = base.heads[0]!;
198 } else {
199 if (anchor === undefined) {
200 const view = new View(scratch, scratch.closureOf(base.heads));
201 anchor = accept(
202 buildAtom(view, {
203 author: "ingest",
204 message: anchorMessage(base.heads),
205 time: base.commit.author.timestamp * 1000,
206 needs: base.heads,
207 }),
208 ).id;
209 }
210 baseAtom = anchor;
211 }
213 const state = scratch.closure(baseAtom);
214 let view = new View(scratch, state);
215 let prevAtom = baseAtom;
216 let prevLabel = baseLabel;
217 const labels: Label[] = [];
218 const commits: IngestedCommit[] = [];
219 const skipped: SkippedFile[] = [];
220 // Skipped files are listed when they first appear or change, not in every commit.
221 let skippedBefore = new Map(base.exact ? base.tree.skipped.map((s) => [s.path, s.oid]) : []);
223 for (const p of pending) {
224 const author = p.commit.author.name;
225 const time = p.commit.author.timestamp * 1000;
226 const message = stripViewTrailers(p.commit.message);
227 const short = p.oid.slice(0, 7);
229 // Binary files, symlinks and the like leave the projection's file as it
230 // is; an emptied file loses all its lines (a projection has no empty files).
231 const untouchable = new Set<string>();
232 for (const s of p.tree.skipped) {
233 if (s.reason !== "empty") untouchable.add(s.path);
234 if (skippedBefore.get(s.path) !== s.oid) skipped.push({ commit: p.oid, path: s.path, reason: s.reason });
235 }
236 skippedBefore = new Map(p.tree.skipped.map((s) => [s.path, s.oid]));
238 // One atom per hunk, all written against the state before this commit.
239 const hunks: AtomId[] = [];
240 const paths = [...new Set([...view.paths(), ...p.tree.files.keys()])].sort();
241 for (const path of paths) {
242 if (untouchable.has(path)) continue;
243 const old = view.lines(path).map((l) => l.text);
244 const text = p.tree.files.get(path);
245 const next = text === undefined ? [] : splitLines(text);
246 let shift = 0;
247 for (const hunk of diffLines(old, next)) {
248 const atom = buildAtom(view, {
249 author,
250 message: withTrailers(
251 message,
252 [{ key: "Hunk", value: hunkLocation(path, hunk, shift) }],
253 `Commit ${short}`,
254 ).trimEnd(),
255 time,
256 edits: [{ file: path, start: hunk.start, end: hunk.end, lines: hunk.lines, mode }],
257 });
258 hunks.push(accept(atom).id);
259 shift += hunk.lines.length - (hunk.end - hunk.start);
260 }
261 }
262 for (const id of hunks) state.add(id);
263 view = new View(scratch, state);
265 // The tie: needs this commit's hunks and the state before it.
266 const tie = accept(
267 buildAtom(view, {
268 author,
269 message: withTrailers(message, [{ key: GIT_COMMIT, value: p.oid }], `Commit ${short}`).trimEnd(),
270 time,
271 needs: [...hunks, prevAtom],
272 }),
273 );
274 state.add(tie.id);
276 const { subject, body } = splitSubject(message);
277 const name = labelName(scratch, p.oid);
278 scratch.setLabel({
279 name,
280 head: tie.id,
281 base: prevLabel ?? baseAtom,
282 title: subject || `Commit ${short}`,
283 message: body,
284 ...(prevLabel !== undefined ? { follows: [prevLabel] } : {}),
285 });
286 labels.push(scratch.label(name)!);
287 commits.push({ commit: p.oid, label: name, tie: tie.id, hunks, author, time, message });
288 prevAtom = tie.id;
289 prevLabel = name;
290 }
292 // The shared set gains the whole ingested state (closure of the last tie).
293 const isNew = new Set(added.map((a) => a.id));
294 const shared = new Set(sharedSet);
295 const revived: AtomId[] = [];
296 for (const id of sortBySeq(scratch, state)) {
297 if (shared.has(id)) continue;
298 shared.add(id);
299 if (!isNew.has(id)) revived.push(id);
300 }
301 const introduced = conflicts(scratch, shared).filter((c) => !sharedSet.has(c.atoms[0]) || !sharedSet.has(c.atoms[1]));
303 // Everything worked: replay onto the caller's graph, and report its copies.
304 for (const atom of added) graph.add(atom);
305 for (const label of labels) graph.setLabel(label);
307 return {
308 base: {
309 commit: base.oid,
310 kind: base.kind,
311 heads: base.heads,
312 atom: baseAtom,
313 ...(baseLabel !== undefined ? { label: baseLabel } : {}),
314 ...(anchor !== undefined ? { anchor } : {}),
315 },
316 commits,
317 atoms: added.map((a) => graph.atom(a.id)),
318 labels: labels.map((l) => graph.label(l.name)!),
319 shared,
320 revived,
321 conflicts: introduced,
322 skipped,
323 };
324}
326/**
327 * Walk HEAD's first-parent chain back to the base. Returns the base and the
328 * commits after it, newest first, with their trees already read.
329 *
330 * A commit is the base when an earlier ingest took it in, or when it carries
331 * View-Heads naming atoms of this graph and its tree is exactly their
332 * projection. A View-Heads commit whose tree differs is a view commit a
333 * person amended only when its parent passes the exact test (that is what
334 * shows the trailer belongs to this graph); it is then the base set and is
335 * ingested too. Any other commit is the person's and the walk goes on.
336 */
337async function findBase(ctx: GitContext, graph: Graph, ref: string): Promise<{ base: FoundBase; pending: Pending[] }> {
338 let oid: string;
339 try {
340 oid = await resolveRef({ fs: ctx.fs, dir: ctx.dir, ref });
341 } catch (err) {
342 throw new GitViewError("bad-repo", `can't resolve ${ref} in ${ctx.dir}: ${(err as Error).message}`);
343 }
344 const ties = tiesByCommit(graph);
345 const seen = new Map<string, Classified>();
346 const classify = async (oid: string): Promise<Classified> => {
347 let c = seen.get(oid);
348 if (!c) {
349 c = await classifyCommit(ctx, graph, ties, oid);
350 seen.set(oid, c);
351 }
352 return c;
353 };
355 const pending: Pending[] = [];
356 for (;;) {
357 const c = await classify(oid);
358 if (c.kind === "ingested" || c.kind === "view") {
359 return { base: { oid, commit: c.commit, tree: c.tree, kind: c.kind, heads: c.heads, exact: true }, pending };
360 }
361 const parent = c.commit.parent[0];
362 if (c.kind === "amended-view" && parent !== undefined) {
363 const p = await classify(parent);
364 if (p.kind === "ingested" || p.kind === "view") {
365 pending.push({ oid, commit: c.commit, tree: c.tree });
366 return { base: { oid, commit: c.commit, tree: c.tree, kind: "view", heads: c.heads, exact: false }, pending };
367 }
368 }
369 pending.push({ oid, commit: c.commit, tree: c.tree });
370 if (parent === undefined) {
371 throw new GitViewError(
372 "no-view-base",
373 `no commit on the first-parent chain of ${ref} is a view of this graph (View-Heads naming its atoms, with their projection as its tree) or an ingested commit`,
374 );
375 }
376 oid = parent;
377 }
378}
380interface Classified {
381 readonly commit: CommitObject;
382 readonly tree: TreeFiles;
383 /**
384 * ingested: an earlier ingest's tie carries its sha. view: View-Heads of
385 * this graph and the tree is their projection. amended-view: View-Heads
386 * naming atoms of this graph, but the tree differs. plain: anything else.
387 */
388 readonly kind: "ingested" | "view" | "amended-view" | "plain";
389 readonly heads: readonly AtomId[];
390}
392async function classifyCommit(
393 ctx: GitContext,
394 graph: Graph,
395 ties: ReadonlyMap<string, AtomId>,
396 oid: string,
397): Promise<Classified> {
398 let commit: CommitObject;
399 try {
400 ({ commit } = await readCommit({ fs: ctx.fs, dir: ctx.dir, oid, cache: ctx.cache }));
401 } catch (err) {
402 throw new GitViewError(
403 "no-view-base",
404 `reached commit ${oid}, which can't be read (${(err as Error).message}), without finding a view commit`,
405 );
406 }
407 const tree = await readTreeFiles(ctx, commit.tree);
408 const tie = ties.get(oid);
409 if (tie !== undefined) return { commit, tree, kind: "ingested", heads: [tie] };
410 const value = trailerValue(parseTrailers(commit.message), VIEW_HEADS);
411 const ids = (value ?? "").split(/\s+/).filter((s) => s !== "");
412 if (ids.length === 0 || !ids.every((id) => graph.has(id))) return { commit, tree, kind: "plain", heads: [] };
413 const set = graph.closureOf(ids);
414 const exact = tree.skipped.length === 0 && sameFiles(tree.files, project(graph, set));
415 return { commit, tree, kind: exact ? "view" : "amended-view", heads: headsOf(graph, set) };
416}
418/** Tie atoms of earlier ingests and pushes, by the full sha of the git commit they stand for. A pushed tie may hold lines (Relies-On). */
419function tiesByCommit(graph: Graph): Map<string, AtomId> {
420 const out = new Map<string, AtomId>();
421 for (const atom of graph.atoms()) {
422 if (atom.inserts.length > 0 || atom.deletes.length > 0) continue;
423 const sha = trailerValue(parseTrailers(atom.message), GIT_COMMIT);
424 if (sha !== undefined && !out.has(sha)) out.set(sha, atom.id);
425 }
426 return out;
427}
429function anchorMessage(heads: readonly AtomId[]): string {
430 return `Base of a git view: ${heads.join(" ")}`;
431}
433/** An anchor an earlier ingest made for the same heads: no edits or claims, needs exactly the heads. */
434function findAnchor(graph: Graph, heads: readonly AtomId[]): AtomId | undefined {
435 const message = anchorMessage(heads);
436 const want = [...heads].sort().join(" ");
437 for (const atom of graph.atoms()) {
438 if (atom.message !== message || atom.inserts.length > 0 || atom.deletes.length > 0) continue;
439 if (atom.holds.length > 0 || atom.resolves.length > 0 || atom.reasons.length > 0) continue;
440 if ([...atom.needs].sort().join(" ") === want) return atom.id;
441 }
442 return undefined;
443}