- 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=30&format=json
180 linesFirst import 95% · pinch 4% · review 1%Last change pinch in version 30, 3 versions changed it
You're reading version 30. The newest is 318, and 3 versions 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.
6// --last-only imports the last commit alone.
7//
8// Before anything is created, the last commit is checked: abso stores text
9// with LF line endings and a final newline, so a file git holds otherwise
10// would come back different, and the imported history would no longer match
11// its commits; and the commit's own ignore rules must leave none of its files
12// out.
13//
14// What a first cut leaves for later (#58): every version's agent is the
15// importing agent and its time is the import's (the commit's author and time
16// are in the message); merges come in as their first parent's line; a run
17// that stops partway goes on with --after <sha> in the same --dir.
18//
19// CI counts each imported version as seen as soon as it lands, so it never
20// checks or bisects the history; it checks what is published after the
21// import.
22//
23// node client/scripts/import-git.ts --project <name> [--ref origin/main]
24// [--server <url>] [--agent import] [--dir <empty folder>]
25// [--last-only] [--check-only] [--after <sha>]
27import { spawnSync } from "node:child_process";
28import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";
29import { tmpdir } from "node:os";
30import { join, resolve } from "node:path";
31import { parseArgs } from "node:util";
32import { open } from "../src/commands.ts";
33import { loadIgnore } from "../src/folder.ts";
34import { main } from "../src/main.ts";
36const { values } = parseArgs({
37 options: {
38 project: { type: "string" },
39 ref: { type: "string", default: "origin/main" },
40 server: { type: "string", default: "https://api.abso.dev" },
41 agent: { type: "string", default: "import" },
42 dir: { type: "string" },
43 "last-only": { type: "boolean", default: false },
44 "check-only": { type: "boolean", default: false },
45 after: { type: "string" },
46 },
47});
48const checkOnly = values["check-only"] === true;
49if (!values.project && !checkOnly) fail("give the new project a name with --project <name> (or --check-only)");
50if (values.after !== undefined && !values.dir)
51 fail("--after goes on in the folder an earlier run used: give it with --dir");
53const last = git(["rev-parse", "--verify", `${values.ref}^{commit}`]).trim();
54const line = values["last-only"] ? [last] : git(["rev-list", "--reverse", "--first-parent", last]).trim().split("\n");
55const after =
56 values.after === undefined ? undefined : git(["rev-parse", "--verify", `${values.after}^{commit}`]).trim();
57const start = after === undefined ? 0 : line.indexOf(after) + 1;
58if (after !== undefined && start === 0) fail(`${values.after} isn't on ${values.ref}'s first-parent line`);
60const dir = values.dir ? resolve(values.dir) : mkdtempSync(join(tmpdir(), "avcs-import-"));
61mkdirSync(dir, { recursive: true });
62if (after === undefined && readdirSync(dir).length > 0) fail(`${dir} isn't empty`);
63if (after !== undefined && !existsSync(join(dir, ".avcs", "config.json")))
64 fail(`${dir} isn't an abso folder; --after goes on in an earlier run's folder`);
66// The last commit first: nothing is created unless it passes.
67const check = after === undefined ? dir : mkdtempSync(join(tmpdir(), "avcs-import-check-"));
68const files = extract(last, check);
69const changed = files.flatMap((rel) => {
70 const why = notCanonical(readFileSync(join(check, rel)));
71 return why ? [` ${rel}: ${why}`] : [];
72});
73const ignore = loadIgnore(check);
74const ignored = files.filter((rel) => ignore(rel, false)).map((rel) => ` ${rel}`);
75if (check !== dir) rmSync(check, { recursive: true, force: true });
76console.log(
77 `${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)})` : ""}.`,
78);
79if (ignored.length > 0)
80 fail(
81 `Its ignore rules leave out ${ignored.length} of its own files, so the project would lack them:\n${ignored.join("\n")}`,
82 );
83if (changed.length > 0)
84 fail(
85 `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")}`,
86 );
87if (checkOnly) {
88 console.log("Every text file is as abso will store it. Nothing imported (--check-only).");
89 if (after === undefined) rmSync(dir, { recursive: true, force: true });
90 process.exit(0);
91}
93const env = { cwd: dir, env: process.env, write: () => {} };
94let skipped = 0;
95for (let i = start; i < line.length; i++) {
96 const sha = line[i]!;
97 extract(sha, dir);
98 const message = `${git(["log", "-1", "--format=%B", sha]).trim()}\n\ngit ${sha.slice(0, 12)}, ${git(["log", "-1", "--format=%an, %aI", sha]).trim()}`;
99 const subject = message.split("\n")[0]!.slice(0, 72);
100 // The first commit makes the project; --as-is adds no starting .absoignore or avcs.json git never had.
101 const argv =
102 i === 0
103 ? ["init", dir, "--server", values.server!, "--project", values.project!, "--agent", values.agent!, "--as-is"]
104 : ["publish", "-m", message];
105 let r = await main(argv, env);
106 // A lost connection: try again. If the lost publish did land, the next try finds nothing to publish.
107 for (
108 let tries = 1;
109 i > 0 && r.exit !== 0 && /could not reach|answered 5\d\d/.test(r.stdout + r.stderr) && tries < 3;
110 tries++
111 ) {
112 await new Promise((ok) => setTimeout(ok, 2000));
113 r = await main(argv, env);
114 }
115 if (r.exit !== 0)
116 fail(
117 `[${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}`,
118 );
119 const empty = /^Nothing (to publish|published)/m.test(r.stdout);
120 if (empty) skipped++;
121 const version = /(?:version|at version) (\d+)/.exec(r.stdout)?.[1];
122 if (version !== undefined) await skipCi(Number(version));
123 console.log(
124 `[${i + 1}/${line.length}] ${sha.slice(0, 12)} ${subject}${empty ? " (no change: no version)" : version ? ` -> version ${version}` : ""}`,
125 );
126}
127console.log(
128 `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.`,
129);
131/** CI: versions through `through` are history, seen already. A server that can't be told is told nothing. */
132async function skipCi(through: number): Promise<void> {
133 try {
134 await open(env).api.ciSkip(through);
135 } catch (e) {
136 if (through === 0)
137 console.log(
138 `Note: CI wasn't told to skip the history (${e instanceof Error ? e.message : String(e)}); it may check and bisect old versions once.`,
139 );
140 }
141}
143/** The commit's tree in `dir`, replacing everything but .avcs; its files, folder-relative. */
144function extract(sha: string, into: string): string[] {
145 for (const e of readdirSync(into)) if (e !== ".avcs") rmSync(join(into, e), { recursive: true, force: true });
146 // Piped, with tar in the folder: no path for tar to misread (GNU tar takes "C:" for a remote host).
147 const archive = spawnSync("git", ["archive", "--format=tar", sha], { maxBuffer: 1 << 30 });
148 if (archive.status !== 0) fail(`git archive: ${archive.stderr.toString().trim()}`);
149 const untar = spawnSync("tar", ["-xf", "-"], { cwd: into, input: archive.stdout, encoding: "utf8" });
150 if (untar.status !== 0) fail(`tar couldn't unpack ${sha}: ${untar.stderr}`);
151 return walk(into).filter((rel) => !rel.startsWith(".avcs/"));
152}
154/** Why abso would store these bytes differently from git, or undefined. Binary files (NUL, or not UTF-8) go up byte for byte. */
155function notCanonical(bytes: Buffer): string | undefined {
156 if (bytes.includes(0)) return undefined;
157 const text = bytes.toString("utf8");
158 if (!Buffer.from(text, "utf8").equals(bytes)) return undefined;
159 if (text.includes("\r")) return "it has a carriage return (abso keeps LF only)";
160 if (text !== "" && !text.endsWith("\n")) return "it has no final newline (abso adds one)";
161 return undefined;
162}
164function walk(root: string, sub = ""): string[] {
165 return readdirSync(join(root, sub), { withFileTypes: true }).flatMap((e) => {
166 const rel = sub === "" ? e.name : `${sub}/${e.name}`;
167 return e.isDirectory() ? walk(root, rel) : [rel];
168 });
169}
171function git(args: string[]): string {
172 const r = spawnSync("git", args, { encoding: "utf8", maxBuffer: 1 << 26 });
173 if (r.status !== 0) fail(`git ${args.join(" ")}: ${r.stderr.trim()}`);
174 return r.stdout;
175}
177function fail(message: string): never {
178 console.error(message);
179 process.exit(1);
180}