@operad-io/dev 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,366 @@
1
+ /**
2
+ * Dev's side of "Set up git here" (ADR 0039 D8). The bot proposes: a
3
+ * `.gitignore` text, the list of files the first commit would hold, and the
4
+ * person's name and email when git has none. On approval the bot leaves a
5
+ * request file (`register-requests.ts`) and dev, which owns the git runs and the
6
+ * repository lock, does the work here.
7
+ *
8
+ * The list is made before anything exists: a scratch git directory outside the
9
+ * folder and the proposed `.gitignore` as an exclude file, so nothing is written
10
+ * into the folder until the person approves. Applying commits exactly the
11
+ * approved paths, never `git add -A`, so what a chat wrote after the list was
12
+ * shown is not in the commit.
13
+ */
14
+
15
+ import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
16
+ import { homedir, tmpdir } from "node:os";
17
+ import { basename, dirname, isAbsolute, join, resolve } from "node:path";
18
+ import { isRecord } from "@operad-io/engine";
19
+ import { git, type GitOptions } from "./git.ts";
20
+ import { gitStateOf, type GitStateOptions } from "./git-state.ts";
21
+ import { withRepositoryLock, type RepositoryLockOptions } from "./lock.ts";
22
+ import { DevRefusal } from "./model.ts";
23
+ import { ensureExcludes, writeSettings } from "./service.ts";
24
+ import { DEFAULT_DEV_SETTINGS } from "./settings.ts";
25
+
26
+ /** Above this many files the person is asked to check the `.gitignore` first. */
27
+ export const FIRST_COMMIT_FILE_LIMIT = 5000;
28
+
29
+ /** What git is asked to leave out of the first commit by default. */
30
+ export const DEFAULT_GITIGNORE = [
31
+ "# Dependencies",
32
+ "node_modules/",
33
+ ".venv/",
34
+ "target/",
35
+ "vendor/",
36
+ "",
37
+ "# Build output",
38
+ "dist/",
39
+ "build/",
40
+ ".next/",
41
+ "",
42
+ "# Secrets",
43
+ ".env*",
44
+ "*.pem",
45
+ "*.key",
46
+ "id_rsa*",
47
+ "",
48
+ "# System files",
49
+ ".DS_Store",
50
+ "",
51
+ ].join("\n");
52
+
53
+ /** Names that must stay ignored whatever else the text says; the text check probes them. */
54
+ const SECRET_PROBES: readonly string[] = [".env", ".env.local", "server.pem", "api.key", "id_rsa", "id_rsa.pub"];
55
+
56
+ /** The folders dev makes itself; never part of a first commit. */
57
+ const OWN_FOLDERS: readonly string[] = [".operad-worktrees/", ".radian-sandbox/"];
58
+
59
+ const GITIGNORE_MAX_BYTES = 100_000;
60
+
61
+ export interface SetupGitOptions {
62
+ /** The environment of every git run; the default is this process's. */
63
+ readonly env?: NodeJS.ProcessEnv;
64
+ /** The machine the git program is looked up on; a test injects one. */
65
+ readonly state?: GitStateOptions;
66
+ /** The home folder that is refused; the default is the computer account's. */
67
+ readonly home?: string;
68
+ /** Where the repository lock is kept. */
69
+ readonly lock?: RepositoryLockOptions;
70
+ }
71
+
72
+ export interface FirstCommitList {
73
+ /** The folder's own `.gitignore` text, when it has one: a proposal builds on it and must keep every line. */
74
+ readonly existingGitignore: string | undefined;
75
+ /** Files `git add` would take, relative to the folder, sorted; `.gitignore` is the first when the text is not empty. */
76
+ readonly files: readonly string[];
77
+ /** Folders that are git repositories of their own; they are not committed. */
78
+ readonly nested: readonly string[];
79
+ readonly count: number;
80
+ /** True above `FIRST_COMMIT_FILE_LIMIT`. */
81
+ readonly large: boolean;
82
+ /** The sentence that asks the person to check the `.gitignore`, when `large`. */
83
+ readonly note: string | undefined;
84
+ }
85
+
86
+ export interface SetupGitRequest {
87
+ readonly path: string;
88
+ /** The text of the `.gitignore` to write. */
89
+ readonly gitignore: string;
90
+ /** The files to commit, as the person approved them. */
91
+ readonly paths: readonly string[];
92
+ /** Written to the repository's own git configuration, for this commit and later ones. */
93
+ readonly identity?: { readonly name: string; readonly email: string };
94
+ }
95
+
96
+ export interface SetupGitResult {
97
+ /** `already` when the folder had a commit and only the repository setup was completed. */
98
+ readonly outcome: "set up" | "already";
99
+ readonly branch: string;
100
+ readonly committed: number;
101
+ }
102
+
103
+ /** Test-only: runs between `git init` and the commit, so a test can stop the process there. */
104
+ export const setupGitTestHooks: { beforeCommit?: (() => void) | undefined } = {};
105
+
106
+ function realpathOr(path: string): string {
107
+ try {
108
+ return realpathSync.native(path);
109
+ } catch {
110
+ return resolve(path);
111
+ }
112
+ }
113
+
114
+ /** Refuses a folder that must never become one repository: the home folder or a disk root. */
115
+ export function refuseUnsafeFolder(folder: string, home: string = homedir()): void {
116
+ const real = realpathOr(folder);
117
+ if (dirname(real) === real) {
118
+ throw new DevRefusal(`"${folder}" is the top of a disk; git is not set up there. Choose a project folder.`);
119
+ }
120
+ if (real === realpathOr(home)) {
121
+ throw new DevRefusal(
122
+ `"${folder}" is your home folder; everything in it would go into one repository. Choose a project folder inside it.`,
123
+ );
124
+ }
125
+ }
126
+
127
+ function scratchGit<T>(work: (scratch: string, run: (cwd: string, args: readonly string[], options?: GitOptions) => ReturnType<typeof git>) => T): T {
128
+ const scratch = mkdtempSync(join(tmpdir(), "operad-setup-git-"));
129
+ try {
130
+ return work(scratch, (cwd, args, options = {}) => git(cwd, args, options));
131
+ } finally {
132
+ rmSync(scratch, { recursive: true, force: true });
133
+ }
134
+ }
135
+
136
+ /**
137
+ * Why `text` is not a `.gitignore` to write, or `undefined`: it must be text,
138
+ * not too long, and must keep the secret names (`.env*`, keys) out of the commit.
139
+ */
140
+ export function gitignoreProblem(text: string, options: SetupGitOptions = {}): string | undefined {
141
+ if (text.includes("\0")) return "the .gitignore text holds a null byte; it must be plain text";
142
+ if (new TextEncoder().encode(text).length > GITIGNORE_MAX_BYTES) {
143
+ return `the .gitignore text is longer than ${GITIGNORE_MAX_BYTES} bytes`;
144
+ }
145
+ return scratchGit((scratch, run) => {
146
+ const probes = join(scratch, "probes");
147
+ const gitDirectory = join(scratch, "git");
148
+ const exclude = join(scratch, "exclude");
149
+ const env = options.env ?? { ...process.env };
150
+ run(scratch, ["init", "-q", "--bare", gitDirectory], { env });
151
+ writeFileSync(exclude, text);
152
+ // Each probe is a file of the secret's name in a scratch work tree.
153
+ mkdirSync(probes);
154
+ for (const name of SECRET_PROBES) writeFileSync(join(probes, name), "");
155
+ const listed = run(scratch, ["--git-dir", gitDirectory, "--work-tree", probes, "ls-files", "-z", "-o", "--exclude-from", exclude], { env, raw: true });
156
+ if (!listed.ok) return `git could not read the .gitignore text: ${listed.err}`;
157
+ const shown = listed.out.split("\0").filter((name) => name !== "");
158
+ if (shown.length > 0) {
159
+ return `the .gitignore text does not keep ${shown.join(", ")} out of the commit; secret files must stay ignored`;
160
+ }
161
+ return undefined;
162
+ });
163
+ }
164
+
165
+ /**
166
+ * The files the first commit of `folder` would hold with `gitignore` as its
167
+ * `.gitignore`, found without writing anything into the folder.
168
+ */
169
+ export function firstCommitList(folder: string, gitignore: string, options: SetupGitOptions = {}): FirstCommitList {
170
+ refuseUnsafeFolder(folder, options.home);
171
+ const problem = gitignoreProblem(gitignore, options);
172
+ if (problem !== undefined) throw new DevRefusal(problem);
173
+ const dropped = droppedLines(folder, gitignore);
174
+ if (dropped !== undefined) throw new DevRefusal(dropped);
175
+ const env = options.env ?? { ...process.env };
176
+ const listed = scratchGit((scratch, run) => {
177
+ const gitDirectory = join(scratch, "git");
178
+ const exclude = join(scratch, "exclude");
179
+ run(scratch, ["init", "-q", "--bare", gitDirectory], { env });
180
+ writeFileSync(exclude, `${gitignore}\n${OWN_FOLDERS.join("\n")}\n`);
181
+ return run(
182
+ scratch,
183
+ ["--git-dir", gitDirectory, "--work-tree", resolve(folder), "ls-files", "-z", "-o", "--exclude-from", exclude, "--exclude-standard"],
184
+ { env, raw: true, timeoutMs: 120_000 },
185
+ );
186
+ });
187
+ if (!listed.ok) throw new DevRefusal(`git could not list the files in "${folder}": ${listed.err}`);
188
+ const entries = listed.out.split("\0").filter((entry) => entry !== "");
189
+ const nested = entries.filter((entry) => entry.endsWith("/")).sort();
190
+ const files = new Set(entries.filter((entry) => !entry.endsWith("/")));
191
+ if (gitignore.length > 0) files.add(".gitignore");
192
+ const sorted = [...files].sort();
193
+ const large = sorted.length > FIRST_COMMIT_FILE_LIMIT;
194
+ return {
195
+ existingGitignore: existingGitignore(folder),
196
+ files: sorted,
197
+ nested,
198
+ count: sorted.length,
199
+ large,
200
+ note: large
201
+ ? `This folder has ${sorted.length} files for the first commit, more than ${FIRST_COMMIT_FILE_LIMIT}. Check the .gitignore: build output and dependencies are usually not part of it.`
202
+ : undefined,
203
+ };
204
+ }
205
+
206
+ /** The text of the folder's own `.gitignore`, or `undefined` when it has none. */
207
+ export function existingGitignore(folder: string): string | undefined {
208
+ try {
209
+ return readFileSync(join(folder, ".gitignore"), "utf8");
210
+ } catch {
211
+ return undefined;
212
+ }
213
+ }
214
+
215
+ const linesOf = (text: string): string[] =>
216
+ text
217
+ .replace(/\r\n/g, "\n")
218
+ .split("\n")
219
+ .map((line) => line.trim())
220
+ .filter((line) => line !== "");
221
+
222
+ /** A sentence when `proposed` would drop a line of the folder's own `.gitignore`, else `undefined`. */
223
+ function droppedLines(folder: string, proposed: string): string | undefined {
224
+ const existing = existingGitignore(folder);
225
+ if (existing === undefined) return undefined;
226
+ const kept = new Set(linesOf(proposed));
227
+ const missing = linesOf(existing).filter((line) => !kept.has(line));
228
+ if (missing.length === 0) return undefined;
229
+ return `This folder already has a .gitignore, and the new text would drop ${missing.length === 1 ? "this line" : "these lines"}: ${missing.join(", ")}. Keep every line of the existing file and add to it.`;
230
+ }
231
+
232
+ function validPaths(folder: string, paths: readonly string[]): string[] {
233
+ const kept: string[] = [];
234
+ for (const path of paths) {
235
+ if (path === "" || isAbsolute(path) || path.includes("\0")) {
236
+ throw new DevRefusal(`"${path}" is not a path inside the folder`);
237
+ }
238
+ const parts = path.split(/[\\/]/);
239
+ if (parts.includes("..") || parts[0] === ".git") {
240
+ throw new DevRefusal(`"${path}" is not a path git may commit`);
241
+ }
242
+ let stat;
243
+ try {
244
+ stat = lstatSync(join(folder, path));
245
+ } catch {
246
+ continue; // gone since the list was made
247
+ }
248
+ if (stat.isDirectory()) continue; // a nested repository, or a folder: files are listed one by one
249
+ kept.push(path);
250
+ }
251
+ return kept;
252
+ }
253
+
254
+ function updateSettings(folder: string, branch: string): void {
255
+ const file = join(folder, ".operad", "dev.json");
256
+ if (!existsSync(file)) {
257
+ writeSettings(folder, basename(folder), false, true);
258
+ }
259
+ const parsed: unknown = JSON.parse(readFileSync(file, "utf8"));
260
+ if (!isRecord(parsed)) {
261
+ throw new DevRefusal(`${file} is not a JSON object`);
262
+ }
263
+ const settings: Record<string, unknown> = { ...parsed };
264
+ settings.workIn = "branch";
265
+ settings.mainBranch = branch;
266
+ delete settings.remote;
267
+ writeFileSync(file, `${JSON.stringify(settings, null, 2)}\n`);
268
+ }
269
+
270
+ function must(result: ReturnType<typeof git>, what: string): void {
271
+ if (!result.ok) throw new DevRefusal(`${what}: ${result.err.length > 0 ? result.err : result.out}`);
272
+ }
273
+
274
+ /**
275
+ * Makes `request.path` a repository with its first commit: `git init` when
276
+ * there is none, the `.gitignore`, exactly the approved paths, the commit, and
277
+ * a repository that works in a branch and has no remote. Safe to run again
278
+ * after it was stopped anywhere: an unborn repository goes on from where it is,
279
+ * and a repository with a commit only has its exclude file completed.
280
+ */
281
+ export function applySetupGit(request: SetupGitRequest, options: SetupGitOptions = {}): Promise<SetupGitResult> {
282
+ const folder = realpathOr(resolve(request.path));
283
+ return withRepositoryLock(folder, () => applyLocked(folder, request, options), options.lock);
284
+ }
285
+
286
+ function applyLocked(folder: string, request: SetupGitRequest, options: SetupGitOptions): SetupGitResult {
287
+ if (!existsSync(folder)) throw new DevRefusal(`no directory "${folder}"`);
288
+ refuseUnsafeFolder(folder, options.home);
289
+ const env = options.env ?? { ...process.env };
290
+ const run: GitOptions = { env };
291
+ let state = gitStateOf(folder, { ...options.state, env });
292
+ if (state.state === "no program") {
293
+ throw new DevRefusal("Git is not installed on this machine, so git cannot be set up here. Ask the bot to help you install it.");
294
+ }
295
+ if (state.state === "subfolder") {
296
+ throw new DevRefusal(
297
+ `This folder is inside the git repository at ${state.root}. Add ${state.root} as the project instead (operad dev repo add ${state.root}).`,
298
+ );
299
+ }
300
+ if (state.state === "ready") {
301
+ ensureExcludes(folder);
302
+ return { outcome: "already", branch: state.branch ?? "", committed: 0 };
303
+ }
304
+ const problem = gitignoreProblem(request.gitignore, options);
305
+ if (problem !== undefined) throw new DevRefusal(problem);
306
+ const dropped = droppedLines(folder, request.gitignore);
307
+ if (dropped !== undefined) throw new DevRefusal(dropped);
308
+ const identity = request.identity;
309
+ if (identity !== undefined) {
310
+ if (identity.name.trim() === "" || !/^\S+@\S+$/.test(identity.email.trim()) || /[\r\n]/.test(identity.name + identity.email)) {
311
+ throw new DevRefusal("The name must not be empty and the email must look like name@host.");
312
+ }
313
+ } else if (!state.identity.set) {
314
+ throw new DevRefusal("Git has no name and email for the first commit. Give them in the request: the bot asks the person.");
315
+ }
316
+ const paths = validPaths(folder, request.paths);
317
+
318
+ const wanted = readMainBranch(folder);
319
+ if (state.state === "no repository") {
320
+ must(git(folder, ["-c", `init.defaultBranch=${wanted}`, "init", "-q"], run), "git init failed");
321
+ // `init.defaultBranch` needs git 2.28; the symbolic ref works on every version while the branch is unborn.
322
+ must(git(folder, ["symbolic-ref", "HEAD", `refs/heads/${wanted}`], run), "could not name the branch");
323
+ state = gitStateOf(folder, { ...options.state, env });
324
+ }
325
+ const unborn = git(folder, ["symbolic-ref", "--short", "-q", "HEAD"], run);
326
+ const branch = unborn.ok && unborn.out !== "" ? unborn.out : wanted;
327
+
328
+ if (identity !== undefined) {
329
+ must(git(folder, ["config", "user.name", identity.name.trim()], run), "could not store the name");
330
+ must(git(folder, ["config", "user.email", identity.email.trim()], run), "could not store the email");
331
+ }
332
+ writeFileSync(join(folder, ".gitignore"), request.gitignore);
333
+ updateSettings(folder, branch);
334
+
335
+ // An exact index: whatever was staged before is dropped, then only the approved paths are added.
336
+ must(git(folder, ["read-tree", "--empty"], run), "could not reset the index");
337
+ const owned = [".gitignore", ".operad/dev.json"];
338
+ const all = [...new Set([...owned, ...paths])].filter((path) => existsSync(join(folder, path)));
339
+ setupGitTestHooks.beforeCommit?.();
340
+ must(
341
+ git(folder, ["--literal-pathspecs", "add", "--pathspec-from-file=-", "--pathspec-file-nul"], {
342
+ env,
343
+ input: `${all.join("\0")}\0`,
344
+ }),
345
+ "git add failed",
346
+ );
347
+ must(
348
+ git(folder, ["commit", "-q", "--allow-empty", "--no-verify", "--no-gpg-sign", "-m", "Initial commit"], run),
349
+ "the first commit failed",
350
+ );
351
+ ensureExcludes(folder);
352
+ return { outcome: "set up", branch, committed: all.length };
353
+ }
354
+
355
+ /** The `mainBranch` of the folder's `dev.json`, or the default. */
356
+ function readMainBranch(folder: string): string {
357
+ try {
358
+ const parsed: unknown = JSON.parse(readFileSync(join(folder, ".operad", "dev.json"), "utf8"));
359
+ if (isRecord(parsed) && typeof parsed.mainBranch === "string" && parsed.mainBranch !== "") {
360
+ return parsed.mainBranch;
361
+ }
362
+ } catch {
363
+ // No readable settings: the default.
364
+ }
365
+ return DEFAULT_DEV_SETTINGS.mainBranch;
366
+ }