- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/src/gitview/view.ts?version=33&format=json
313 linesFirst import 100%Last change First import in version 0, 1 version changed it
You're reading version 33. The newest is 318, and no version since then changed this file.
1// The git view: a real git repo for a set of atoms. Each commit's tree is the
2// projection of a closed set, and its message carries trailers naming the
3// atoms, so the same set and options always give the same commit hashes.
4//
5// Two shapes:
6// - per atom (the default): one commit per atom in history order. Every
7// prefix of history order is closed, so every commit is a real state.
8// - by label: a root commit for a0, then one commit per label whose head is
9// in the set (each adds the label's closure), then one commit for whatever
10// no label covered.
11// Commit sets only grow, so each commit's set is a prefix of one order (the
12// plan's `order`) and a commit records only how long its prefix is.
14import fs from "node:fs";
15import { checkout, init, writeCommit, writeRef } from "isomorphic-git";
16import {
17 type Atom,
18 type AtomId,
19 type Graph,
20 history,
21 isClosed,
22 missingDeps,
23 project,
24 sortBySeq,
25 stateOf,
26} from "../engine/index.ts";
27import { GitViewError } from "./errors.ts";
28import { type Trailer, VIEW_HEADS, withTrailers } from "./trailers.ts";
29import { gitContext, writeCache, writeFilesTree } from "./tree.ts";
31/** A ref (atom id or label name: its closure) or an explicit closed set of atoms. */
32export type ViewTarget = string | Iterable<AtomId>;
34export interface ViewOptions {
35 /** One commit per label instead of one per atom. */
36 readonly byLabel?: boolean;
37 /** Branch to write; HEAD points at it. Default "main". */
38 readonly branch?: string;
39 /** Check the branch out into the directory's working tree. Default true. */
40 readonly checkout?: boolean;
41}
43export interface ViewCommitPlan {
44 /** Atoms this commit adds, in history order. */
45 readonly atoms: readonly AtomId[];
46 /** Size of this commit's set: it is `order.slice(0, count)` of the plan. */
47 readonly count: number;
48 /** Maximal atoms of this commit's set (no atom in the set depends on them), by seq. */
49 readonly heads: readonly AtomId[];
50 /** The label this commit stands for (by-label mode). */
51 readonly label?: string;
52 /** Full commit message, trailers included. */
53 readonly message: string;
54 /** Git author name and time (ms) of the commit. */
55 readonly author: string;
56 readonly time: number;
57}
59export interface ViewPlan {
60 /** Every atom of the set, in the order commits add them. */
61 readonly order: readonly AtomId[];
62 readonly commits: readonly ViewCommitPlan[];
63}
65export interface ViewCommit {
66 readonly oid: string;
67 readonly atoms: readonly AtomId[];
68 readonly heads: readonly AtomId[];
69 readonly label?: string;
70 readonly message: string;
71}
73export interface ViewResult {
74 readonly dir: string;
75 readonly branch: string;
76 /** The tip commit (what the branch and HEAD point at). */
77 readonly head: string;
78 /** The whole set, by seq. */
79 readonly set: readonly AtomId[];
80 /** Oldest first. */
81 readonly commits: readonly ViewCommit[];
82}
84/** Domain for derived author emails (.invalid is reserved: it can never be a real address). */
85export const EMAIL_DOMAIN = "atoms.invalid";
87/**
88 * Resolve a target to a closed set. A string is a ref (its closure); anything
89 * else is an explicit set, which must be closed.
90 */
91export function resolveTarget(graph: Graph, target: ViewTarget): Set<AtomId> {
92 let set: Set<AtomId>;
93 if (typeof target === "string") {
94 set = new Set(stateOf(graph, target));
95 } else {
96 set = new Set(target);
97 for (const id of set) graph.atom(id); // unknown ids throw EngineError('unknown-atom')
98 if (!isClosed(graph, set)) {
99 const missing = missingDeps(graph, set)
100 .map((m) => `${m.atom} needs ${m.missing.join(", ")}`)
101 .join("; ");
102 throw new GitViewError("not-closed", `the set is not closed: ${missing}`);
103 }
104 }
105 if (set.size === 0) throw new GitViewError("empty-set", "there are no atoms to view");
106 return set;
107}
109/**
110 * Plan the commits of a view without touching any disk: which atoms each
111 * commit adds, its heads, author, time and message. Pure: the same set and
112 * options give the same plan, whatever order the set was listed in.
113 */
114export function planView(graph: Graph, target: ViewTarget, options: Pick<ViewOptions, "byLabel"> = {}): ViewPlan {
115 const set = resolveTarget(graph, target);
116 const order: AtomId[] = [];
117 const heads = new Set<AtomId>();
118 const commits: ViewCommitPlan[] = [];
120 // Add atoms to the running set. Each atom's deps are already in it (atoms
121 // come in history order, and the running set is closed), so the atom is a
122 // new head and its deps stop being heads.
123 const addAll = (atoms: readonly Atom[]): void => {
124 for (const atom of atoms) {
125 for (const d of atom.deps) heads.delete(d);
126 heads.add(atom.id);
127 order.push(atom.id);
128 }
129 };
130 const headList = (): AtomId[] => sortBySeq(graph, heads);
132 if (!options.byLabel) {
133 for (const atom of history(graph, set)) {
134 addAll([atom]);
135 const h = headList();
136 commits.push({
137 atoms: [atom.id],
138 count: order.length,
139 heads: h,
140 message: atomMessage(atom, h),
141 author: atom.author,
142 time: atom.time,
143 });
144 }
145 return { order, commits };
146 }
148 const covered = new Set<AtomId>();
149 const take = (ids: Iterable<AtomId>): Atom[] => {
150 const fresh = history(
151 graph,
152 [...ids].filter((id) => !covered.has(id)),
153 );
154 for (const atom of fresh) covered.add(atom.id);
155 addAll(fresh);
156 return fresh;
157 };
159 // The starting snapshot is the root commit.
160 if (set.has("a0")) {
161 const [a0] = take(["a0"]);
162 const h = headList();
163 commits.push({
164 atoms: ["a0"],
165 count: order.length,
166 heads: h,
167 message: atomMessage(a0!, h),
168 author: a0!.author,
169 time: a0!.time,
170 });
171 }
173 // Labels in the order of their heads' priority: a label whose head is in
174 // another's closure has the lower priority, so it comes first.
175 const labels = graph
176 .labels()
177 .filter((l) => set.has(l.head))
178 .sort((a, b) => graph.comparePriority(a.head, b.head) || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
179 for (const label of labels) {
180 const fresh = take(graph.closure(label.head));
181 const h = headList();
182 // Author and time of the commit are its last atom's (normally the label's head).
183 const last = fresh[fresh.length - 1] ?? graph.atom(label.head);
184 const ids = fresh.map((a) => a.id);
185 const trailers: Trailer[] = [
186 { key: "Label", value: label.name },
187 ...(ids.length > 0 ? [{ key: "Atoms", value: ids.join(" ") }] : []),
188 ...fresh.flatMap(reasonTrailers),
189 { key: VIEW_HEADS, value: h.join(" ") },
190 ];
191 const text = label.message.trim() !== "" ? `${label.title}\n\n${label.message}` : label.title;
192 commits.push({
193 atoms: ids,
194 count: order.length,
195 heads: h,
196 label: label.name,
197 message: withTrailers(text, trailers, `Label ${label.name}`),
198 author: last.author,
199 time: last.time,
200 });
201 }
203 // Whatever no label covered.
204 const rest = [...set].filter((id) => !covered.has(id));
205 if (rest.length > 0) {
206 const fresh = take(rest);
207 const h = headList();
208 const last = fresh[fresh.length - 1]!;
209 const trailers: Trailer[] = [
210 { key: "Atoms", value: fresh.map((a) => a.id).join(" ") },
211 ...fresh.flatMap(reasonTrailers),
212 { key: VIEW_HEADS, value: h.join(" ") },
213 ];
214 commits.push({
215 atoms: fresh.map((a) => a.id),
216 count: order.length,
217 heads: h,
218 message: withTrailers("Atoms outside any label", trailers, ""),
219 author: last.author,
220 time: last.time,
221 });
222 }
223 return { order, commits };
224}
226/** A per-atom commit message: the atom's message, then Atom, Deps, Resolves, Reason and View-Heads trailers. */
227function atomMessage(atom: Atom, heads: readonly AtomId[]): string {
228 const trailers: Trailer[] = [{ key: "Atom", value: atom.id }];
229 if (atom.deps.length > 0) trailers.push({ key: "Deps", value: atom.deps.join(" ") });
230 if (atom.resolves.length > 0) trailers.push({ key: "Resolves", value: atom.resolves.join(" ") });
231 trailers.push(...reasonTrailers(atom));
232 trailers.push({ key: VIEW_HEADS, value: heads.join(" ") });
233 return withTrailers(atom.message, trailers, `Atom ${atom.id}`);
234}
236/** One "Reason: <from> <kind> <to>: <text>" trailer per reason the atom carries. */
237function reasonTrailers(atom: Atom): Trailer[] {
238 return atom.reasons.map((r) => ({ key: "Reason", value: `${atom.id} ${r.kind} ${r.to}: ${r.text}` }));
239}
241/** A git author name: no angle brackets or line breaks (git can't store them), never empty. */
242export function gitName(author: string): string {
243 return author.replace(/[<>\r\n]/g, "").trim() || "unknown";
244}
246/** A deterministic email for an author name: a lowercase slug at atoms.invalid. */
247export function gitEmail(author: string): string {
248 const slug = author
249 .normalize("NFKD")
250 .toLowerCase()
251 .replace(/[^a-z0-9._-]+/g, "-")
252 .replace(/^[-.]+|[-.]+$/g, "");
253 return `${slug || "unknown"}@${EMAIL_DOMAIN}`;
254}
256/** Author and committer of a view commit: the atom's author at the atom's time (seconds, UTC). */
257function signature(
258 author: string,
259 time: number,
260): { name: string; email: string; timestamp: number; timezoneOffset: number } {
261 return {
262 name: gitName(author),
263 email: gitEmail(author),
264 timestamp: Math.max(0, Math.floor(time / 1000)),
265 timezoneOffset: 0,
266 };
267}
269/**
270 * Write a git repo at `dir` (which must be missing or empty) for the set.
271 * Each commit's tree is the projection of its set; HEAD points at `branch`.
272 */
273export async function writeView(
274 graph: Graph,
275 target: ViewTarget,
276 dir: string,
277 options: ViewOptions = {},
278): Promise<ViewResult> {
279 const plan = planView(graph, target, options);
280 const branch = options.branch ?? "main";
282 if (fs.existsSync(dir) && fs.readdirSync(dir).length > 0) {
283 throw new GitViewError("dir-not-empty", `${dir} already has files in it`);
284 }
285 fs.mkdirSync(dir, { recursive: true });
286 const ctx = gitContext(dir);
287 await init({ fs, dir, defaultBranch: branch });
289 const cache = writeCache();
290 const commits: ViewCommit[] = [];
291 let parent: string | undefined;
292 for (const c of plan.commits) {
293 const tree = await writeFilesTree(ctx, project(graph, plan.order.slice(0, c.count)), cache);
294 const sig = signature(c.author, c.time);
295 const oid = await writeCommit({
296 fs,
297 dir,
298 commit: { message: c.message, tree, parent: parent ? [parent] : [], author: sig, committer: sig },
299 });
300 commits.push({
301 oid,
302 atoms: c.atoms,
303 heads: c.heads,
304 ...(c.label !== undefined ? { label: c.label } : {}),
305 message: c.message,
306 });
307 parent = oid;
308 }
309 await writeRef({ fs, dir, ref: `refs/heads/${branch}`, value: parent!, force: true });
310 if (options.checkout !== false) await checkout({ fs, dir, ref: branch, force: true, cache: ctx.cache });
312 return { dir, branch, head: parent!, set: sortBySeq(graph, plan.order), commits };
313}