- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/client/scripts/import-git.ts?version=293&format=json
209 linesFirst import 77% · whytrail 13% · review 5% · pinch 4% · rename 1%Last change whytrail in version 193, 6 versions changed it
You're reading version 293. The newest is 318, and no version since then changed this file.
1// Import a git repository into a new abso project, with its history (#58;
2// first used for #56, abso hosts abso). Each commit on the first-parent line
3// of --ref becomes a version of shared, oldest first: the first by `avcs
4// init`, each later one by a publish of that commit's tree, with the commit's
5// message and a last line naming the commit, its author and its time. When
6// the repository's issues are on the web (origin on GitHub or GitLab, or
7// --issues <url>), a line after it says where, so "#39" in the message, or
8// in the lines it wrote, names that tracker's issue, not the project's:
9//
10// git 4e1a7c2b9f03, Ada Lovelace, 2026-10-06T20:36:43-05:00
11// Issues: https://github.com/owner/repo/issues
12//
13// abso why and abso blame read these lines (client/src/git-origin.ts).
14// --last-only imports the last commit alone.
15//
16// Before anything is created, the last commit is checked: abso stores text
17// with LF line endings and a final newline, so a file git holds otherwise
18// would come back different, and the imported history would no longer match
19// its commits; and the commit's own ignore rules must leave none of its files
20// out.
21//
22// What a first cut leaves for later (#58): every version's agent is the
23// importing agent and its time is the import's (the commit's author and time
24// are in the message); merges come in as their first parent's line; a run
25// that stops partway goes on with --after <sha> in the same --dir. Version 0
26// is made by init, which says "Start the project", so the first commit's own
27// message and hash aren't on it: they're printed when the import starts.
28//
29// CI counts each imported version as seen as soon as it lands, so it never
30// checks or bisects the history; it checks what is published after the
31// import.
32//
33// node client/scripts/import-git.ts --project <name> [--ref origin/main]
34// [--server <url>] [--agent import] [--dir <empty folder>]
35// [--last-only] [--check-only] [--after <sha>] [--issues <url>]
37import { spawnSync } from "node:child_process";
38import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";
39import { tmpdir } from "node:os";
40import { join, resolve } from "node:path";
41import { parseArgs } from "node:util";
42import { open } from "../src/commands.ts";
43import { loadIgnore } from "../src/folder.ts";
44import { issuesOf } from "../src/git-origin.ts";
45import { main } from "../src/main.ts";
47const { values } = parseArgs({
48 options: {
49 project: { type: "string" },
50 ref: { type: "string", default: "origin/main" },
51 server: { type: "string", default: "https://api.abso.dev" },
52 agent: { type: "string", default: "import" },
53 dir: { type: "string" },
54 "last-only": { type: "boolean", default: false },
55 "check-only": { type: "boolean", default: false },
56 after: { type: "string" },
57 issues: { type: "string" },
58 },
59});
60const checkOnly = values["check-only"] === true;
61if (!values.project && !checkOnly) fail("give the new project a name with --project <name> (or --check-only)");
62if (values.after !== undefined && !values.dir)
63 fail("--after goes on in the folder an earlier run used: give it with --dir");
65const last = git(["rev-parse", "--verify", `${values.ref}^{commit}`]).trim();
66const line = values["last-only"] ? [last] : git(["rev-list", "--reverse", "--first-parent", last]).trim().split("\n");
67const after =
68 values.after === undefined ? undefined : git(["rev-parse", "--verify", `${values.after}^{commit}`]).trim();
69const start = after === undefined ? 0 : line.indexOf(after) + 1;
70if (after !== undefined && start === 0) fail(`${values.after} isn't on ${values.ref}'s first-parent line`);
72const dir = values.dir ? resolve(values.dir) : mkdtempSync(join(tmpdir(), "avcs-import-"));
73mkdirSync(dir, { recursive: true });
74if (after === undefined && readdirSync(dir).length > 0) fail(`${dir} isn't empty`);
75if (
76 after !== undefined &&
77 !existsSync(join(dir, ".abso", "config.json")) &&
78 !existsSync(join(dir, ".avcs", "config.json"))
79)
80 fail(`${dir} isn't an abso folder; --after goes on in an earlier run's folder`);
82// The last commit first: nothing is created unless it passes.
83const check = after === undefined ? dir : mkdtempSync(join(tmpdir(), "avcs-import-check-"));
84const files = extract(last, check);
85const changed = files.flatMap((rel) => {
86 const why = notCanonical(readFileSync(join(check, rel)));
87 return why ? [` ${rel}: ${why}`] : [];
88});
89const ignore = loadIgnore(check);
90const ignored = files.filter((rel) => ignore(rel, false)).map((rel) => ` ${rel}`);
91if (check !== dir) rmSync(check, { recursive: true, force: true });
92console.log(
93 `${values.ref} is ${last.slice(0, 12)}: ${files.length} files, ${line.length} ${line.length === 1 ? "commit" : "commits"} to import${start > 0 ? ` (${line.length - start} after ${after!.slice(0, 12)})` : ""}.`,
94);
95if (ignored.length > 0)
96 fail(
97 `Its ignore rules leave out ${ignored.length} of its own files, so the project would lack them:\n${ignored.join("\n")}`,
98 );
99if (changed.length > 0)
100 fail(
101 `abso would store ${changed.length} of its files differently from git, so the imported history wouldn't match git. Fix them first:\n${changed.join("\n")}`,
102 );
103if (checkOnly) {
104 console.log("Every text file is as abso will store it. Nothing imported (--check-only).");
105 if (after === undefined) rmSync(dir, { recursive: true, force: true });
106 process.exit(0);
107}
109// Where "#N" in the history points: --issues, else origin's issues on GitHub or GitLab.
110if (values.issues !== undefined && !/^https?:\/\/\S+$/.test(values.issues))
111 fail(`--issues is a web address, like https://github.com/owner/repo/issues (got ${JSON.stringify(values.issues)})`);
112const tracker = values.issues ?? issuesOf(origin());
114const env = { cwd: dir, env: process.env, write: () => {} };
115let skipped = 0;
116for (let i = start; i < line.length; i++) {
117 const sha = line[i]!;
118 extract(sha, dir);
119 const message = `${git(["log", "-1", "--format=%B", sha]).trim()}\n\ngit ${sha.slice(0, 12)}, ${git(["log", "-1", "--format=%an, %aI", sha]).trim()}${tracker ? `\nIssues: ${tracker}` : ""}`;
120 if (i === 0) console.log(`Version 0 is commit ${sha.slice(0, 12)}: ${message.split("\n")[0]}`);
121 const subject = message.split("\n")[0]!.slice(0, 72);
122 // The first commit makes the project; --as-is adds no starting .absoignore or avcs.json git never had.
123 const argv =
124 i === 0
125 ? ["init", dir, "--server", values.server!, "--project", values.project!, "--agent", values.agent!, "--as-is"]
126 : ["push", "-m", message];
127 let r = await main(argv, env);
128 // A lost connection: try again. If the lost publish did land, the next try finds nothing to publish.
129 for (
130 let tries = 1;
131 i > 0 && r.exit !== 0 && /could not reach|answered 5\d\d/.test(r.stdout + r.stderr) && tries < 3;
132 tries++
133 ) {
134 await new Promise((ok) => setTimeout(ok, 2000));
135 r = await main(argv, env);
136 }
137 if (r.exit !== 0)
138 fail(
139 `[${i + 1}/${line.length}] ${sha.slice(0, 12)} ${subject}: ${argv[0]} failed (exit ${r.exit}).\n${r.stdout}${r.stderr}\nGo on from the commit before it with --after ${i === 0 ? "(none: start again in an empty folder)" : line[i - 1]!.slice(0, 12)} --dir ${dir}`,
140 );
141 const empty = /^Nothing (to push|pushed)/m.test(r.stdout);
142 if (empty) skipped++;
143 const version = /(?:version|at version) (\d+)/.exec(r.stdout)?.[1];
144 if (version !== undefined) await skipCi(Number(version));
145 console.log(
146 `[${i + 1}/${line.length}] ${sha.slice(0, 12)} ${subject}${empty ? " (no change: no version)" : version ? ` -> version ${version}` : ""}`,
147 );
148}
149console.log(
150 `Imported ${values.ref} (${last.slice(0, 12)}) as project ${values.project}: ${line.length - start - skipped} versions${skipped > 0 ? `, ${skipped} commits with no change` : ""}. ${dir} is agent ${values.agent}'s folder; keep it or delete it.`,
151);
153/** CI: versions through `through` are history, seen already. A server that can't be told is told nothing. */
154async function skipCi(through: number): Promise<void> {
155 try {
156 await open(env).api.ciSkip(through);
157 } catch (e) {
158 if (through === 0)
159 console.log(
160 `Note: CI wasn't told to skip the history (${e instanceof Error ? e.message : String(e)}); it may check and bisect old versions once.`,
161 );
162 }
163}
165/** The commit's tree in `dir`, replacing everything but .avcs and .abso; its files, folder-relative. */
166function extract(sha: string, into: string): string[] {
167 for (const e of readdirSync(into))
168 if (e !== ".avcs" && e !== ".abso") rmSync(join(into, e), { recursive: true, force: true });
169 // Piped, with tar in the folder: no path for tar to misread (GNU tar takes "C:" for a remote host).
170 const archive = spawnSync("git", ["archive", "--format=tar", sha], { maxBuffer: 1 << 30 });
171 if (archive.status !== 0) fail(`git archive: ${archive.stderr.toString().trim()}`);
172 const untar = spawnSync("tar", ["-xf", "-"], { cwd: into, input: archive.stdout, encoding: "utf8" });
173 if (untar.status !== 0) fail(`tar couldn't unpack ${sha}: ${untar.stderr}`);
174 return walk(into).filter((rel) => !rel.startsWith(".avcs/") && !rel.startsWith(".abso/"));
175}
177/** Why abso would store these bytes differently from git, or undefined. Binary files (NUL, or not UTF-8) go up byte for byte. */
178function notCanonical(bytes: Buffer): string | undefined {
179 if (bytes.includes(0)) return undefined;
180 const text = bytes.toString("utf8");
181 if (!Buffer.from(text, "utf8").equals(bytes)) return undefined;
182 if (text.includes("\r")) return "it has a carriage return (abso keeps LF only)";
183 if (text !== "" && !text.endsWith("\n")) return "it has no final newline (abso adds one)";
184 return undefined;
185}
187function walk(root: string, sub = ""): string[] {
188 return readdirSync(join(root, sub), { withFileTypes: true }).flatMap((e) => {
189 const rel = sub === "" ? e.name : `${sub}/${e.name}`;
190 return e.isDirectory() ? walk(root, rel) : [rel];
191 });
192}
194function git(args: string[]): string {
195 const r = spawnSync("git", args, { encoding: "utf8", maxBuffer: 1 << 26 });
196 if (r.status !== 0) fail(`git ${args.join(" ")}: ${r.stderr.trim()}`);
197 return r.stdout;
198}
200/** origin's address, or "" when there's no origin. */
201function origin(): string {
202 const r = spawnSync("git", ["remote", "get-url", "origin"], { encoding: "utf8" });
203 return r.status === 0 ? r.stdout.trim() : "";
204}
206function fail(message: string): never {
207 console.error(message);
208 process.exit(1);
209}