- 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=149&format=json
185 linesFirst import 89% · review 5% · pinch 4% · rename 1%Last change rename in version 100, 5 versions changed it
You're reading version 149. The newest is 318, and 1 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.
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 (
64 after !== undefined &&
65 !existsSync(join(dir, ".abso", "config.json")) &&
66 !existsSync(join(dir, ".avcs", "config.json"))
67)
68 fail(`${dir} isn't an abso folder; --after goes on in an earlier run's folder`);
70// The last commit first: nothing is created unless it passes.
71const check = after === undefined ? dir : mkdtempSync(join(tmpdir(), "avcs-import-check-"));
72const files = extract(last, check);
73const changed = files.flatMap((rel) => {
74 const why = notCanonical(readFileSync(join(check, rel)));
75 return why ? [` ${rel}: ${why}`] : [];
76});
77const ignore = loadIgnore(check);
78const ignored = files.filter((rel) => ignore(rel, false)).map((rel) => ` ${rel}`);
79if (check !== dir) rmSync(check, { recursive: true, force: true });
80console.log(
81 `${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)})` : ""}.`,
82);
83if (ignored.length > 0)
84 fail(
85 `Its ignore rules leave out ${ignored.length} of its own files, so the project would lack them:\n${ignored.join("\n")}`,
86 );
87if (changed.length > 0)
88 fail(
89 `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")}`,
90 );
91if (checkOnly) {
92 console.log("Every text file is as abso will store it. Nothing imported (--check-only).");
93 if (after === undefined) rmSync(dir, { recursive: true, force: true });
94 process.exit(0);
95}
97const env = { cwd: dir, env: process.env, write: () => {} };
98let skipped = 0;
99for (let i = start; i < line.length; i++) {
100 const sha = line[i]!;
101 extract(sha, dir);
102 const message = `${git(["log", "-1", "--format=%B", sha]).trim()}\n\ngit ${sha.slice(0, 12)}, ${git(["log", "-1", "--format=%an, %aI", sha]).trim()}`;
103 const subject = message.split("\n")[0]!.slice(0, 72);
104 // The first commit makes the project; --as-is adds no starting .absoignore or avcs.json git never had.
105 const argv =
106 i === 0
107 ? ["init", dir, "--server", values.server!, "--project", values.project!, "--agent", values.agent!, "--as-is"]
108 : ["push", "-m", message];
109 let r = await main(argv, env);
110 // A lost connection: try again. If the lost publish did land, the next try finds nothing to publish.
111 for (
112 let tries = 1;
113 i > 0 && r.exit !== 0 && /could not reach|answered 5\d\d/.test(r.stdout + r.stderr) && tries < 3;
114 tries++
115 ) {
116 await new Promise((ok) => setTimeout(ok, 2000));
117 r = await main(argv, env);
118 }
119 if (r.exit !== 0)
120 fail(
121 `[${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}`,
122 );
123 const empty = /^Nothing (to push|pushed)/m.test(r.stdout);
124 if (empty) skipped++;
125 const version = /(?:version|at version) (\d+)/.exec(r.stdout)?.[1];
126 if (version !== undefined) await skipCi(Number(version));
127 console.log(
128 `[${i + 1}/${line.length}] ${sha.slice(0, 12)} ${subject}${empty ? " (no change: no version)" : version ? ` -> version ${version}` : ""}`,
129 );
130}
131console.log(
132 `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.`,
133);
135/** CI: versions through `through` are history, seen already. A server that can't be told is told nothing. */
136async function skipCi(through: number): Promise<void> {
137 try {
138 await open(env).api.ciSkip(through);
139 } catch (e) {
140 if (through === 0)
141 console.log(
142 `Note: CI wasn't told to skip the history (${e instanceof Error ? e.message : String(e)}); it may check and bisect old versions once.`,
143 );
144 }
145}
147/** The commit's tree in `dir`, replacing everything but .avcs and .abso; its files, folder-relative. */
148function extract(sha: string, into: string): string[] {
149 for (const e of readdirSync(into))
150 if (e !== ".avcs" && e !== ".abso") rmSync(join(into, e), { recursive: true, force: true });
151 // Piped, with tar in the folder: no path for tar to misread (GNU tar takes "C:" for a remote host).
152 const archive = spawnSync("git", ["archive", "--format=tar", sha], { maxBuffer: 1 << 30 });
153 if (archive.status !== 0) fail(`git archive: ${archive.stderr.toString().trim()}`);
154 const untar = spawnSync("tar", ["-xf", "-"], { cwd: into, input: archive.stdout, encoding: "utf8" });
155 if (untar.status !== 0) fail(`tar couldn't unpack ${sha}: ${untar.stderr}`);
156 return walk(into).filter((rel) => !rel.startsWith(".avcs/") && !rel.startsWith(".abso/"));
157}
159/** Why abso would store these bytes differently from git, or undefined. Binary files (NUL, or not UTF-8) go up byte for byte. */
160function notCanonical(bytes: Buffer): string | undefined {
161 if (bytes.includes(0)) return undefined;
162 const text = bytes.toString("utf8");
163 if (!Buffer.from(text, "utf8").equals(bytes)) return undefined;
164 if (text.includes("\r")) return "it has a carriage return (abso keeps LF only)";
165 if (text !== "" && !text.endsWith("\n")) return "it has no final newline (abso adds one)";
166 return undefined;
167}
169function walk(root: string, sub = ""): string[] {
170 return readdirSync(join(root, sub), { withFileTypes: true }).flatMap((e) => {
171 const rel = sub === "" ? e.name : `${sub}/${e.name}`;
172 return e.isDirectory() ? walk(root, rel) : [rel];
173 });
174}
176function git(args: string[]): string {
177 const r = spawnSync("git", args, { encoding: "utf8", maxBuffer: 1 << 26 });
178 if (r.status !== 0) fail(`git ${args.join(" ")}: ${r.stderr.trim()}`);
179 return r.stdout;
180}
182function fail(message: string): never {
183 console.error(message);
184 process.exit(1);
185}