@inventarch/cli 3.5.0 → 3.6.0
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.
- package/NOTICE +2 -0
- package/README.md +2 -1
- package/SPEC.md +13 -4
- package/THIRD_PARTY_NOTICES.txt +49 -0
- package/assets/host/44dc1fa77e0235df35e1dd05d5a5ce8c2b19d4545caf0b8579f2f4e1b9efbbc6.tgz +0 -0
- package/assets/host.json +4 -4
- package/dist/args.d.ts +9 -0
- package/dist/args.d.ts.map +1 -1
- package/dist/args.js.map +1 -1
- package/dist/bin.d.ts +3 -0
- package/dist/bin.d.ts.map +1 -0
- package/dist/bin.js +53 -0
- package/dist/bin.js.map +1 -0
- package/dist/claude-cli.d.ts +13 -1
- package/dist/claude-cli.d.ts.map +1 -1
- package/dist/claude-cli.js +31 -1
- package/dist/claude-cli.js.map +1 -1
- package/dist/commands.d.ts +17 -0
- package/dist/commands.d.ts.map +1 -1
- package/dist/commands.js +66 -3
- package/dist/commands.js.map +1 -1
- package/dist/committed-host.d.ts.map +1 -1
- package/dist/committed-host.js +14 -2
- package/dist/committed-host.js.map +1 -1
- package/dist/console/app.d.ts +47 -0
- package/dist/console/app.d.ts.map +1 -0
- package/dist/console/app.js +921 -0
- package/dist/console/app.js.map +1 -0
- package/dist/console/batch-next.d.ts +54 -0
- package/dist/console/batch-next.d.ts.map +1 -0
- package/dist/console/batch-next.js +260 -0
- package/dist/console/batch-next.js.map +1 -0
- package/dist/console/batch-plan.d.ts +109 -0
- package/dist/console/batch-plan.d.ts.map +1 -0
- package/dist/console/batch-plan.js +308 -0
- package/dist/console/batch-plan.js.map +1 -0
- package/dist/console/batch-run.d.ts +195 -0
- package/dist/console/batch-run.d.ts.map +1 -0
- package/dist/console/batch-run.js +868 -0
- package/dist/console/batch-run.js.map +1 -0
- package/dist/console/batch-screen.d.ts +36 -0
- package/dist/console/batch-screen.d.ts.map +1 -0
- package/dist/console/batch-screen.js +113 -0
- package/dist/console/batch-screen.js.map +1 -0
- package/dist/console/grid.d.ts +30 -0
- package/dist/console/grid.d.ts.map +1 -0
- package/dist/console/grid.js +87 -0
- package/dist/console/grid.js.map +1 -0
- package/dist/console/keys.d.ts +54 -0
- package/dist/console/keys.d.ts.map +1 -0
- package/dist/console/keys.js +204 -0
- package/dist/console/keys.js.map +1 -0
- package/dist/console/layout-all.d.ts +70 -0
- package/dist/console/layout-all.d.ts.map +1 -0
- package/dist/console/layout-all.js +401 -0
- package/dist/console/layout-all.js.map +1 -0
- package/dist/console/layout-repo.d.ts +65 -0
- package/dist/console/layout-repo.d.ts.map +1 -0
- package/dist/console/layout-repo.js +275 -0
- package/dist/console/layout-repo.js.map +1 -0
- package/dist/console/load.d.ts +33 -0
- package/dist/console/load.d.ts.map +1 -0
- package/dist/console/load.js +166 -0
- package/dist/console/load.js.map +1 -0
- package/dist/console/offers.d.ts +39 -0
- package/dist/console/offers.d.ts.map +1 -0
- package/dist/console/offers.js +285 -0
- package/dist/console/offers.js.map +1 -0
- package/dist/console/run.d.ts +56 -0
- package/dist/console/run.d.ts.map +1 -0
- package/dist/console/run.js +210 -0
- package/dist/console/run.js.map +1 -0
- package/dist/console/state.d.ts +127 -0
- package/dist/console/state.d.ts.map +1 -0
- package/dist/console/state.js +273 -0
- package/dist/console/state.js.map +1 -0
- package/dist/console/terminal.d.ts +60 -0
- package/dist/console/terminal.d.ts.map +1 -0
- package/dist/console/terminal.js +114 -0
- package/dist/console/terminal.js.map +1 -0
- package/dist/console/width-table.d.ts +10 -0
- package/dist/console/width-table.d.ts.map +1 -0
- package/dist/console/width-table.js +753 -0
- package/dist/console/width-table.js.map +1 -0
- package/dist/console/width.d.ts +18 -0
- package/dist/console/width.d.ts.map +1 -0
- package/dist/console/width.js +114 -0
- package/dist/console/width.js.map +1 -0
- package/dist/console/workspaces-state.d.ts +93 -0
- package/dist/console/workspaces-state.d.ts.map +1 -0
- package/dist/console/workspaces-state.js +192 -0
- package/dist/console/workspaces-state.js.map +1 -0
- package/dist/consumer.d.ts +13 -8
- package/dist/consumer.d.ts.map +1 -1
- package/dist/consumer.js +22 -34
- package/dist/consumer.js.map +1 -1
- package/dist/discovery.d.ts +8 -0
- package/dist/discovery.d.ts.map +1 -0
- package/dist/discovery.js +36 -0
- package/dist/discovery.js.map +1 -0
- package/dist/distribute.d.ts +9 -0
- package/dist/distribute.d.ts.map +1 -1
- package/dist/distribute.js +70 -13
- package/dist/distribute.js.map +1 -1
- package/dist/doctor-authority.d.ts.map +1 -1
- package/dist/doctor-authority.js +7 -4
- package/dist/doctor-authority.js.map +1 -1
- package/dist/doctor-extensions.d.ts +36 -0
- package/dist/doctor-extensions.d.ts.map +1 -0
- package/dist/doctor-extensions.js +118 -0
- package/dist/doctor-extensions.js.map +1 -0
- package/dist/doctor-mounts.d.ts.map +1 -1
- package/dist/doctor-mounts.js +3 -2
- package/dist/doctor-mounts.js.map +1 -1
- package/dist/doctor-user.d.ts +64 -0
- package/dist/doctor-user.d.ts.map +1 -1
- package/dist/doctor-user.js +309 -34
- package/dist/doctor-user.js.map +1 -1
- package/dist/doctor.d.ts +22 -1
- package/dist/doctor.d.ts.map +1 -1
- package/dist/doctor.js +81 -32
- package/dist/doctor.js.map +1 -1
- package/dist/fix.d.ts +67 -0
- package/dist/fix.d.ts.map +1 -0
- package/dist/fix.js +136 -0
- package/dist/fix.js.map +1 -0
- package/dist/handoff.d.ts +65 -0
- package/dist/handoff.d.ts.map +1 -0
- package/dist/handoff.js +264 -0
- package/dist/handoff.js.map +1 -0
- package/dist/host-projection.d.ts.map +1 -1
- package/dist/host-projection.js +1 -8
- package/dist/host-projection.js.map +1 -1
- package/dist/host.d.ts +9 -3
- package/dist/host.d.ts.map +1 -1
- package/dist/host.js +23 -7
- package/dist/host.js.map +1 -1
- package/dist/init.d.ts +4 -6
- package/dist/init.d.ts.map +1 -1
- package/dist/init.js +85 -10
- package/dist/init.js.map +1 -1
- package/dist/local-cli.d.ts +67 -0
- package/dist/local-cli.d.ts.map +1 -0
- package/dist/local-cli.js +269 -0
- package/dist/local-cli.js.map +1 -0
- package/dist/main.d.ts +47 -3
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +121 -26
- package/dist/main.js.map +1 -1
- package/dist/marketplace-record.d.ts +7 -1
- package/dist/marketplace-record.d.ts.map +1 -1
- package/dist/marketplace-record.js +6 -3
- package/dist/marketplace-record.js.map +1 -1
- package/dist/package-manager.d.ts +43 -0
- package/dist/package-manager.d.ts.map +1 -0
- package/dist/package-manager.js +164 -0
- package/dist/package-manager.js.map +1 -0
- package/dist/position.d.ts.map +1 -1
- package/dist/position.js +16 -2
- package/dist/position.js.map +1 -1
- package/dist/preview.d.ts.map +1 -1
- package/dist/preview.js +11 -3
- package/dist/preview.js.map +1 -1
- package/dist/profile.d.ts +1 -1
- package/dist/profile.d.ts.map +1 -1
- package/dist/profile.js +3 -4
- package/dist/profile.js.map +1 -1
- package/dist/program.d.ts +10 -0
- package/dist/program.d.ts.map +1 -1
- package/dist/program.js +38 -1
- package/dist/program.js.map +1 -1
- package/dist/project.js +2 -2
- package/dist/project.js.map +1 -1
- package/dist/render.d.ts +7 -2
- package/dist/render.d.ts.map +1 -1
- package/dist/render.js +42 -3
- package/dist/render.js.map +1 -1
- package/dist/self.d.ts +6 -0
- package/dist/self.d.ts.map +1 -0
- package/dist/self.js +20 -0
- package/dist/self.js.map +1 -0
- package/dist/tracked-lock.d.ts +15 -0
- package/dist/tracked-lock.d.ts.map +1 -0
- package/dist/tracked-lock.js +37 -0
- package/dist/tracked-lock.js.map +1 -0
- package/dist/tracked.d.ts +125 -0
- package/dist/tracked.d.ts.map +1 -0
- package/dist/tracked.js +436 -0
- package/dist/tracked.js.map +1 -0
- package/dist/user-host.d.ts +7 -3
- package/dist/user-host.d.ts.map +1 -1
- package/dist/user-host.js +24 -11
- package/dist/user-host.js.map +1 -1
- package/dist/workspace-state.d.ts +15 -0
- package/dist/workspace-state.d.ts.map +1 -0
- package/dist/workspace-state.js +35 -0
- package/dist/workspace-state.js.map +1 -0
- package/dist/workspaces.d.ts +37 -0
- package/dist/workspaces.d.ts.map +1 -0
- package/dist/workspaces.js +319 -0
- package/dist/workspaces.js.map +1 -0
- package/package.json +9 -8
- package/assets/host/0f17774a928b0ed422d4eaae433d379df6df70a94ee2ba47501ed7b7bbbe73e4.tgz +0 -0
|
@@ -0,0 +1,868 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Running a batch (consumer CLI contract §1.2): each planned repository in turn, in a new git worktree on a new branch,
|
|
3
|
+
* one at a time, a failure stopping only that repository. Nothing here reads or writes the user's own checkout but the
|
|
4
|
+
* git metadata operations `METADATA_OPS` names, each run as `git -C <original top level> …`: they read refs or add a
|
|
5
|
+
* worktree and a branch, never the working tree. Everything else (the install, every step) runs with its `cwd` in the
|
|
6
|
+
* worktree, on arguments planning rebuilt for it (batch-plan.ts).
|
|
7
|
+
*
|
|
8
|
+
* Per repository: refuse when planning did; `git fetch origin` and the base (`origin/HEAD`, then `origin/main`, then
|
|
9
|
+
* `origin/master`); refuse a workspace whose `.ia/src` the base does not hold; refuse an existing worktree path or branch; `git worktree add --no-track -b <branch> <path> <base>`
|
|
10
|
+
* (no upstream, ever), and when that fails, remove what it made (`undoAdd`); the package manager's install when the worktree holds a `package.json`, built for the worktree,
|
|
11
|
+
* with no lifecycle script and frozen to a tracked lockfile (`batchInstallArgv`);
|
|
12
|
+
* then each step. Before the install and before every step the real filesystem is checked (`containedStep`): the
|
|
13
|
+
* step's `cwd` and each path it names must lead, through any link, into the worktree. An `ia` step runs on the copy
|
|
14
|
+
* the worktree has at that step, found again before each one, or on the running copy when there is none; the batch
|
|
15
|
+
* preview was the confirmation, so it runs in its confirmed form.
|
|
16
|
+
*/
|
|
17
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
18
|
+
import { existsSync, lstatSync, realpathSync, statSync } from 'node:fs';
|
|
19
|
+
import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
20
|
+
import { fileURLToPath } from 'node:url';
|
|
21
|
+
import { confirmedArgv, displayFix } from '../fix.js';
|
|
22
|
+
import { NO_HANDOFF } from '../handoff.js';
|
|
23
|
+
import { batchInstallArgv, detectPackageManager, lockTracked } from '../package-manager.js';
|
|
24
|
+
import { withoutGitRouting } from '../program.js';
|
|
25
|
+
import { findProgram, programEnv, windowsShell, windowsShellArgs, windowsSystemProgram } from '../program.js';
|
|
26
|
+
import { BASE_FALLBACKS, installsFirst, pathArguments } from './batch-plan.js';
|
|
27
|
+
import { cmdArgument, runningEntry } from './run.js';
|
|
28
|
+
const programOf = (program) => (typeof program === 'string' ? { path: program } : program);
|
|
29
|
+
export { GIT_LOCAL_ENV } from '../program.js';
|
|
30
|
+
/**
|
|
31
|
+
* What every batch child gets set, whatever the console inherited: git never asks on the terminal for a credential
|
|
32
|
+
* (stdin is ignored, but git opens the terminal itself) and Git Credential Manager never opens a dialog, either of which
|
|
33
|
+
* would hold the sequential batch with no one answering. A remote that needs a credential then fails for its repository.
|
|
34
|
+
*/
|
|
35
|
+
export const NO_PROMPT = {
|
|
36
|
+
GIT_TERMINAL_PROMPT: '0',
|
|
37
|
+
GCM_INTERACTIVE: 'never',
|
|
38
|
+
// ssh never starts an askpass program, whatever the console inherited or the user's own ssh would otherwise choose.
|
|
39
|
+
SSH_ASKPASS_REQUIRE: 'never',
|
|
40
|
+
// `core.askPass` set empty, as `-c core.askPass=` would, but for every git a child starts too (git 2.31 and later):
|
|
41
|
+
// git asks an askpass program before it looks at GIT_TERMINAL_PROMPT, and an empty one is no program. The console's
|
|
42
|
+
// own GIT_CONFIG_COUNT and its keys are never passed on (`withoutGitRouting`), so this is the only entry.
|
|
43
|
+
GIT_CONFIG_COUNT: '1',
|
|
44
|
+
GIT_CONFIG_KEY_0: 'core.askPass',
|
|
45
|
+
GIT_CONFIG_VALUE_0: '',
|
|
46
|
+
};
|
|
47
|
+
/**
|
|
48
|
+
* The askpass programs no batch child inherits: git and ssh would start one (a terminal's credential dialog, such as
|
|
49
|
+
* an editor's) and the sequential batch would wait on it until the command's timeout.
|
|
50
|
+
*/
|
|
51
|
+
export const ASKPASS_ENV = ['GIT_ASKPASS', 'SSH_ASKPASS'];
|
|
52
|
+
/** What keeps ssh from asking, for a password, a passphrase or a host key, or opening an askpass dialog. */
|
|
53
|
+
export const SSH_NO_PROMPT = 'ssh -o BatchMode=yes';
|
|
54
|
+
/**
|
|
55
|
+
* `env` for the commands of the repository at `directory`, with ssh that never asks (`SSH_NO_PROMPT`), unless the user
|
|
56
|
+
* names their own ssh: `GIT_SSH_COMMAND` or `GIT_SSH` in the environment, or `core.sshCommand`, which the variable
|
|
57
|
+
* would otherwise override and so lose the key or the program they chose. An ssh of their own is theirs; elsewhere than
|
|
58
|
+
* Windows it still has no terminal to ask on (`defaultRunner`), and everywhere it is bounded by the command's timeout.
|
|
59
|
+
*/
|
|
60
|
+
export function withoutSshPrompt(env, git, directory) {
|
|
61
|
+
const names = Object.keys(env).map((name) => (process.platform === 'win32' ? name.toUpperCase() : name));
|
|
62
|
+
if (names.includes('GIT_SSH_COMMAND') || names.includes('GIT_SSH'))
|
|
63
|
+
return env;
|
|
64
|
+
if (git(directory, ['config', '--get', 'core.sshCommand']) !== null)
|
|
65
|
+
return env;
|
|
66
|
+
return { ...env, GIT_SSH_COMMAND: SSH_NO_PROMPT };
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* `env` without git's repository-local variables or an askpass program (`ASKPASS_ENV`), and with `NO_PROMPT` set;
|
|
70
|
+
* Windows compares names without case, as its environment does.
|
|
71
|
+
*/
|
|
72
|
+
export function batchEnv(env, platform = process.platform) {
|
|
73
|
+
const out = {};
|
|
74
|
+
for (const [name, value] of Object.entries(withoutGitRouting(env, platform))) {
|
|
75
|
+
const key = platform === 'win32' ? name.toUpperCase() : name;
|
|
76
|
+
if (key in NO_PROMPT || ASKPASS_ENV.includes(key))
|
|
77
|
+
continue;
|
|
78
|
+
out[name] = value;
|
|
79
|
+
}
|
|
80
|
+
return { ...out, ...NO_PROMPT };
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* How long one batch command may run before it is stopped and counted as failed: long enough for a cold install, short
|
|
84
|
+
* enough that a command waiting on something no one will give (a credential, a lock) never holds the batch for good.
|
|
85
|
+
*/
|
|
86
|
+
export const BATCH_COMMAND_TIMEOUT_MS = 10 * 60_000;
|
|
87
|
+
/**
|
|
88
|
+
* Whether a child gets a process group of its own. Node's `detached` makes it a session as well, with no controlling
|
|
89
|
+
* terminal: nothing in it can stop on the terminal or take the terminal's Ctrl-C, and opening `/dev/tty` fails, so
|
|
90
|
+
* whatever would ask there (ssh, git, a hook, a signing key's passphrase) fails at once instead of holding the batch.
|
|
91
|
+
* Windows has no such groups, and keeps `stopTree`'s taskkill.
|
|
92
|
+
*/
|
|
93
|
+
const OWN_GROUP = process.platform !== 'win32';
|
|
94
|
+
/** Sends `signal` to the child's whole group; one already gone is not an error. */
|
|
95
|
+
function signalGroup(child, signal) {
|
|
96
|
+
if (child.pid === undefined)
|
|
97
|
+
return;
|
|
98
|
+
try {
|
|
99
|
+
process.kill(-child.pid, signal);
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
// Every process of the group has ended.
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Ends `child` and every process it started that stayed in its group (on Windows, in its tree: a `.cmd` runs its
|
|
107
|
+
* program as cmd.exe's child), so a grandchild (an install's own scripts) cannot go on writing into the worktree while
|
|
108
|
+
* later steps run there, or as it is removed. A process that made a session of its own has left the tree, and stays.
|
|
109
|
+
*/
|
|
110
|
+
function stopTree(child, env) {
|
|
111
|
+
if (process.platform === 'win32' && child.pid !== undefined) {
|
|
112
|
+
const taskkill = windowsSystemProgram(env, 'taskkill.exe');
|
|
113
|
+
if (existsSync(taskkill))
|
|
114
|
+
spawnSync(taskkill, ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true });
|
|
115
|
+
}
|
|
116
|
+
if (OWN_GROUP)
|
|
117
|
+
signalGroup(child, 'SIGKILL');
|
|
118
|
+
child.kill('SIGKILL');
|
|
119
|
+
}
|
|
120
|
+
/** A synchronous `git -C <cwd> …` by the checked `git`, through the guarded spawn, for the lockfile probe. */
|
|
121
|
+
export const gitWith = (env, git, guard) => (cwd, args) => {
|
|
122
|
+
const result = spawnGuardedSync(git, ['--no-optional-locks', '-C', cwd, ...args], { cwd, env }, guard);
|
|
123
|
+
return result.status === 0 ? result.stdout.trim() : null;
|
|
124
|
+
};
|
|
125
|
+
/**
|
|
126
|
+
* The real runner: an absolute file as given; any other name by the absolute path `findProgram` finds on a qualified
|
|
127
|
+
* PATH entry, with `programEnv`, and a Windows `.cmd` through cmd.exe named by its path, each argument quoted for it
|
|
128
|
+
* (`cmdArgument`; one it cannot pass refuses the call).
|
|
129
|
+
*/
|
|
130
|
+
export function defaultRunner(env, limits = {}) {
|
|
131
|
+
const timeoutMs = limits.timeoutMs ?? BATCH_COMMAND_TIMEOUT_MS;
|
|
132
|
+
return (file, args, options) => new Promise((resolved) => {
|
|
133
|
+
let settled = false;
|
|
134
|
+
let timer;
|
|
135
|
+
let unwatch = () => { };
|
|
136
|
+
const settle = (result) => {
|
|
137
|
+
if (settled)
|
|
138
|
+
return;
|
|
139
|
+
settled = true;
|
|
140
|
+
if (timer !== undefined)
|
|
141
|
+
clearTimeout(timer);
|
|
142
|
+
unwatch();
|
|
143
|
+
resolved(result);
|
|
144
|
+
};
|
|
145
|
+
const fail = (why) => settle({ status: null, stdout: '', stderr: why });
|
|
146
|
+
const childEnv = batchEnv(options.env);
|
|
147
|
+
let target;
|
|
148
|
+
const script = (path) => process.platform === 'win32' && /\.(?:cmd|bat)$/i.test(path);
|
|
149
|
+
if (isAbsolute(file) && !script(file))
|
|
150
|
+
target = {
|
|
151
|
+
file,
|
|
152
|
+
args,
|
|
153
|
+
env: programEnv(childEnv),
|
|
154
|
+
verbatim: false,
|
|
155
|
+
...(options.argv0 === undefined ? {} : { argv0: options.argv0 }),
|
|
156
|
+
};
|
|
157
|
+
else {
|
|
158
|
+
const program = isAbsolute(file) ? null : findProgram(file, env, 'program');
|
|
159
|
+
if (program !== null)
|
|
160
|
+
target = { file: program, args, env: programEnv(childEnv), verbatim: false };
|
|
161
|
+
else {
|
|
162
|
+
const script = isAbsolute(file) ? file : findProgram(file, env, 'script');
|
|
163
|
+
if (script === null)
|
|
164
|
+
return fail(`${file} was not found on a qualified PATH entry`);
|
|
165
|
+
const quoted = args.map(cmdArgument);
|
|
166
|
+
if (quoted.some((value) => value === null))
|
|
167
|
+
return fail(`cmd.exe cannot pass an argument of ${file} unchanged`);
|
|
168
|
+
target = {
|
|
169
|
+
file: windowsShell(env),
|
|
170
|
+
args: windowsShellArgs(script, quoted),
|
|
171
|
+
env: programEnv(childEnv),
|
|
172
|
+
verbatim: true,
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
let stdout = '', stderr = '';
|
|
177
|
+
const child = spawn(target.file, [...target.args], {
|
|
178
|
+
cwd: options.cwd,
|
|
179
|
+
env: target.env,
|
|
180
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
181
|
+
windowsHide: true,
|
|
182
|
+
windowsVerbatimArguments: target.verbatim,
|
|
183
|
+
detached: OWN_GROUP,
|
|
184
|
+
...(target.argv0 === undefined ? {} : { argv0: target.argv0 }),
|
|
185
|
+
});
|
|
186
|
+
if (OWN_GROUP) {
|
|
187
|
+
// The child is out of the terminal's reach, so the batch's stop (the console's Ctrl-C) is passed on to it, and
|
|
188
|
+
// a console that exits with a command still running does not leave the tree behind. A console killed outright
|
|
189
|
+
// (SIGKILL, a hard crash) runs no `exit` listener, and the child, in a session of its own, gets no SIGHUP: that
|
|
190
|
+
// command then runs on to its end.
|
|
191
|
+
const interrupt = () => signalGroup(child, 'SIGINT');
|
|
192
|
+
const ending = () => signalGroup(child, 'SIGKILL');
|
|
193
|
+
// Only a stop that comes while it runs: a command started after the stop (the clean-up of a failed add) runs.
|
|
194
|
+
const signal = options.signal;
|
|
195
|
+
signal?.addEventListener('abort', interrupt, { once: true });
|
|
196
|
+
process.on('exit', ending);
|
|
197
|
+
unwatch = () => {
|
|
198
|
+
signal?.removeEventListener('abort', interrupt);
|
|
199
|
+
process.off('exit', ending);
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
child.stdout.setEncoding('utf8').on('data', (chunk) => {
|
|
203
|
+
stdout += chunk;
|
|
204
|
+
});
|
|
205
|
+
child.stderr.setEncoding('utf8').on('data', (chunk) => {
|
|
206
|
+
stderr += chunk;
|
|
207
|
+
});
|
|
208
|
+
child.once('error', (error) => settle({ status: null, stdout, stderr: `${stderr}${error.message}` }));
|
|
209
|
+
child.once('close', (code) => settle({ status: code, stdout, stderr }));
|
|
210
|
+
// A command with no end is stopped and settles at once as a failure: a grandchild still holding the pipes would
|
|
211
|
+
// otherwise keep `close` from ever coming.
|
|
212
|
+
timer = setTimeout(() => {
|
|
213
|
+
stopTree(child, target.env);
|
|
214
|
+
child.stdout.destroy();
|
|
215
|
+
child.stderr.destroy();
|
|
216
|
+
const end = stderr === '' || stderr.endsWith('\n') ? '' : '\n';
|
|
217
|
+
settle({
|
|
218
|
+
status: null,
|
|
219
|
+
stdout,
|
|
220
|
+
stderr: `${stderr}${end}timed out after ${Math.round(timeoutMs / 1000)} s and was stopped`,
|
|
221
|
+
});
|
|
222
|
+
}, timeoutMs);
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* The git commands that may run against the user's own repository, each as `git -C <its top level> <command> …`. They
|
|
227
|
+
* read refs or change metadata (a remote-tracking update, a worktree and a branch added, and afterwards, when chosen,
|
|
228
|
+
* the batch's own worktree removed, batch-next.ts, or what a failed `worktree add` made, `undoAdd`); none reads or
|
|
229
|
+
* writes the user's working tree.
|
|
230
|
+
*/
|
|
231
|
+
export const METADATA_OPS = [
|
|
232
|
+
'rev-parse --show-toplevel',
|
|
233
|
+
'fetch origin',
|
|
234
|
+
'symbolic-ref --quiet refs/remotes/origin/HEAD',
|
|
235
|
+
'rev-parse --verify --quiet',
|
|
236
|
+
'worktree add --no-track -b',
|
|
237
|
+
'ls-tree',
|
|
238
|
+
'worktree remove',
|
|
239
|
+
'worktree list --porcelain',
|
|
240
|
+
'update-ref -d',
|
|
241
|
+
'config --get core.sshCommand',
|
|
242
|
+
];
|
|
243
|
+
/**
|
|
244
|
+
* The top level of the git repository holding `root`, by its real path; null when it is in none; a refusal when the
|
|
245
|
+
* `git` on PATH lies inside the repository (judged against `root` and the nearest folder above it that holds a `.git`,
|
|
246
|
+
* before it runs, and against the top level it reports).
|
|
247
|
+
*/
|
|
248
|
+
export function gitTop(root, env) {
|
|
249
|
+
let holder = resolve(root);
|
|
250
|
+
while (!existsSync(join(holder, '.git')) && dirname(holder) !== holder)
|
|
251
|
+
holder = dirname(holder);
|
|
252
|
+
const checked = programIn('git', env, [root, holder]);
|
|
253
|
+
if ('refused' in checked)
|
|
254
|
+
return checked.path === null ? null : { refused: checked.refused };
|
|
255
|
+
const result = spawnGuardedSync(checked, ['-C', root, 'rev-parse', '--show-toplevel'], { cwd: root, env }, { checkouts: [root, holder] });
|
|
256
|
+
if (result.refused !== undefined)
|
|
257
|
+
return { refused: result.refused };
|
|
258
|
+
const top = result.status === 0 ? result.stdout.trim() : '';
|
|
259
|
+
if (top === '')
|
|
260
|
+
return null;
|
|
261
|
+
let real;
|
|
262
|
+
try {
|
|
263
|
+
real = realpathSync.native(resolve(top));
|
|
264
|
+
}
|
|
265
|
+
catch {
|
|
266
|
+
return null;
|
|
267
|
+
}
|
|
268
|
+
const again = programIn('git', env, [real]);
|
|
269
|
+
return 'refused' in again ? { refused: again.refused } : real;
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* The top level of the work tree holding `path`, a folder above a repository, by its real path; null only when git
|
|
273
|
+
* says plainly that `path` is in no work tree; a refusal whenever git cannot say (it may not run, it fails for another
|
|
274
|
+
* reason, such as an enclosing repository of dubious ownership, or the top level it names cannot be resolved), since
|
|
275
|
+
* a worktree there could be inside a work tree no one checked. `git` was already judged against the repository
|
|
276
|
+
* (`gitTop`); that it lies under this folder is no refusal. git runs as a batch child does (`batchEnv`), in English, so
|
|
277
|
+
* its "not a git repository" is read the same in every locale.
|
|
278
|
+
*/
|
|
279
|
+
export function enclosingTop(path, env) {
|
|
280
|
+
const scoped = { ...batchEnv(env), LC_ALL: 'C', LANGUAGE: 'C' };
|
|
281
|
+
const cannot = (why) => ({ refused: `git cannot say whether ${path} is in another work tree: ${why}` });
|
|
282
|
+
const git = programIn('git', scoped, []);
|
|
283
|
+
if ('refused' in git)
|
|
284
|
+
return cannot(git.refused);
|
|
285
|
+
const result = spawnGuardedSync(git, ['-C', path, 'rev-parse', '--show-toplevel'], { cwd: path, env: scoped }, { checkouts: [] });
|
|
286
|
+
if (result.refused !== undefined)
|
|
287
|
+
return cannot(result.refused);
|
|
288
|
+
if (result.status !== 0)
|
|
289
|
+
return /not a git repository|must be run in a work tree/.test(result.stderr)
|
|
290
|
+
? null
|
|
291
|
+
: cannot(lastLine(result.stderr) || `git rev-parse exited ${result.status ?? 'on a signal'}`);
|
|
292
|
+
const top = result.stdout.trim();
|
|
293
|
+
// An older git run inside a git directory prints no top level: that folder is in no work tree.
|
|
294
|
+
if (top === '')
|
|
295
|
+
return null;
|
|
296
|
+
// git writes the top level with forward slashes, and Windows may spell it with a short name; `gitTop` names its
|
|
297
|
+
// repository by real path, so the folder around it is named the same way.
|
|
298
|
+
try {
|
|
299
|
+
return realpathSync.native(resolve(top));
|
|
300
|
+
}
|
|
301
|
+
catch {
|
|
302
|
+
return cannot(`its top level ${top} cannot be resolved`);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
const lastLine = (text) => text
|
|
306
|
+
.split(/\r?\n/)
|
|
307
|
+
.map((line) => line.trim())
|
|
308
|
+
.filter((line) => line !== '')
|
|
309
|
+
.at(-1) ?? '';
|
|
310
|
+
/** The base after `git fetch origin`: `origin/HEAD`'s branch, then `origin/main`, then `origin/master`; or why none. */
|
|
311
|
+
async function findBase(top, run, env, gitPath, guard = { checkouts: [top] }) {
|
|
312
|
+
const git = (args) => spawnGuarded(run, gitPath, ['-C', top, ...args], { cwd: top, env }, guard);
|
|
313
|
+
const fetched = await git(['fetch', 'origin']);
|
|
314
|
+
if (fetched.refused !== undefined)
|
|
315
|
+
return { why: fetched.refused };
|
|
316
|
+
if (fetched.status !== 0)
|
|
317
|
+
return { why: `git fetch origin failed: ${lastLine(fetched.stderr)}` };
|
|
318
|
+
const head = await git(['symbolic-ref', '--quiet', 'refs/remotes/origin/HEAD']);
|
|
319
|
+
if (head.refused !== undefined)
|
|
320
|
+
return { why: head.refused };
|
|
321
|
+
const candidates = [
|
|
322
|
+
...(head.status === 0 && head.stdout.trim().startsWith('refs/remotes/')
|
|
323
|
+
? [head.stdout.trim().slice('refs/remotes/'.length)]
|
|
324
|
+
: []),
|
|
325
|
+
...BASE_FALLBACKS,
|
|
326
|
+
];
|
|
327
|
+
for (const candidate of candidates) {
|
|
328
|
+
const found = await git(['rev-parse', '--verify', '--quiet', `refs/remotes/${candidate}^{commit}`]);
|
|
329
|
+
if (found.refused !== undefined)
|
|
330
|
+
return { why: found.refused };
|
|
331
|
+
if (found.status === 0)
|
|
332
|
+
return { base: candidate };
|
|
333
|
+
}
|
|
334
|
+
return { why: 'origin has no HEAD, main or master' };
|
|
335
|
+
}
|
|
336
|
+
/** `git fetch origin`, then the first of `origin/HEAD`, `origin/main` and `origin/master` that resolves; null otherwise. */
|
|
337
|
+
export async function chooseBase(top, run, env = process.env) {
|
|
338
|
+
const git = programIn('git', batchEnv(env), [top]);
|
|
339
|
+
if ('refused' in git)
|
|
340
|
+
return null;
|
|
341
|
+
const scoped = batchEnv(env);
|
|
342
|
+
const found = await findBase(top, run, withoutSshPrompt(scoped, gitWith(scoped, git, { checkouts: [top] }), top), git);
|
|
343
|
+
return 'base' in found ? found.base : null;
|
|
344
|
+
}
|
|
345
|
+
const fold = (path) => (process.platform === 'win32' ? path.toLowerCase() : path);
|
|
346
|
+
/** `child` is `parent` or inside it; both are real paths. */
|
|
347
|
+
function within(parent, child) {
|
|
348
|
+
const rel = relative(fold(parent), fold(child));
|
|
349
|
+
return rel === '' || (!isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`));
|
|
350
|
+
}
|
|
351
|
+
/** Where `path` really leads: the real path of its nearest existing ancestor, joined with the rest; null for a dead link. */
|
|
352
|
+
function leadsTo(path) {
|
|
353
|
+
let existing = resolve(path);
|
|
354
|
+
const rest = [];
|
|
355
|
+
for (;;) {
|
|
356
|
+
let entry;
|
|
357
|
+
try {
|
|
358
|
+
entry = lstatSync(existing, { throwIfNoEntry: false });
|
|
359
|
+
}
|
|
360
|
+
catch {
|
|
361
|
+
entry = undefined;
|
|
362
|
+
}
|
|
363
|
+
if (entry !== undefined)
|
|
364
|
+
try {
|
|
365
|
+
return join(realpathSync.native(existing), ...rest.reverse());
|
|
366
|
+
}
|
|
367
|
+
catch {
|
|
368
|
+
// An entry that exists but whose real path cannot be read is a link that leads nowhere.
|
|
369
|
+
return null;
|
|
370
|
+
}
|
|
371
|
+
const up = dirname(existing);
|
|
372
|
+
if (up === existing)
|
|
373
|
+
return join(existing, ...rest.reverse());
|
|
374
|
+
rest.push(basename(existing));
|
|
375
|
+
existing = up;
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
/**
|
|
379
|
+
* The one rule for every program a batch starts (git, gh, the package manager, a step's program): found as `findProgram`
|
|
380
|
+
* finds it (or as given when absolute), its real path must not lie inside any of `checkouts`, so a program the user's
|
|
381
|
+
* repository holds is never run. `path` is what to spawn; null with a refusal when nothing was found.
|
|
382
|
+
*/
|
|
383
|
+
export function programIn(name, env, checkouts) {
|
|
384
|
+
const found = isAbsolute(name) ? name : (findProgram(name, env, 'program') ?? findProgram(name, env, 'script'));
|
|
385
|
+
if (found === null)
|
|
386
|
+
return { path: null, refused: `${name} was not found on a qualified PATH entry` };
|
|
387
|
+
// The canonical real path, never a link's spelling: it is what runs, and what every spawn checks again.
|
|
388
|
+
const real = leadsTo(found);
|
|
389
|
+
if (real === null)
|
|
390
|
+
return { path: null, refused: `${name} at ${found} is a link that leads nowhere` };
|
|
391
|
+
for (const checkout of checkouts)
|
|
392
|
+
if (within(leadsTo(checkout) ?? checkout, real))
|
|
393
|
+
return { path: real, refused: `${name} resolves to ${real}, inside the repository` };
|
|
394
|
+
// Windows does not dispatch on `argv[0]`, and a `.cmd` found by its path has no use for another.
|
|
395
|
+
return process.platform !== 'win32' && fold(found) !== fold(real) ? { path: real, argv0: found } : { path: real };
|
|
396
|
+
}
|
|
397
|
+
const nameOf = (program) => basename(program).replace(/\.(?:exe|cmd|bat|com)$/i, '');
|
|
398
|
+
/** Why `program` may not start now with these arguments, or null. The running node is not judged. */
|
|
399
|
+
function admit(program, args, cwd, guard) {
|
|
400
|
+
if (program !== process.execPath) {
|
|
401
|
+
let real;
|
|
402
|
+
try {
|
|
403
|
+
real = realpathSync.native(program);
|
|
404
|
+
}
|
|
405
|
+
catch {
|
|
406
|
+
return `${nameOf(program)} at ${program} cannot be read`;
|
|
407
|
+
}
|
|
408
|
+
if (fold(real) !== fold(program))
|
|
409
|
+
return `${nameOf(program)} now leads to ${real}, not to ${program}`;
|
|
410
|
+
// cmd.exe expands %NAME% even inside quotes, so a script at such a path would run from another path than the one
|
|
411
|
+
// checked. Refused on every platform, so the rule reads the same wherever a script path is judged.
|
|
412
|
+
if (/\.(?:cmd|bat)$/i.test(real) && real.includes('%'))
|
|
413
|
+
return `${nameOf(program)} at ${real} holds %, which cmd.exe would expand into another path`;
|
|
414
|
+
for (const checkout of guard.checkouts)
|
|
415
|
+
if (within(leadsTo(checkout) ?? checkout, real))
|
|
416
|
+
return `${nameOf(program)} resolves to ${real}, inside the repository`;
|
|
417
|
+
}
|
|
418
|
+
const tree = guard.worktree;
|
|
419
|
+
if (tree !== undefined) {
|
|
420
|
+
const values = [
|
|
421
|
+
cwd,
|
|
422
|
+
...args.flatMap((arg) => (arg.includes('=') ? [arg, arg.slice(arg.indexOf('=') + 1)] : [arg])),
|
|
423
|
+
];
|
|
424
|
+
const inTree = values.some((value) => isAbsolute(value) && within(resolve(tree.path), resolve(value)));
|
|
425
|
+
if (inTree)
|
|
426
|
+
return checkPinned(tree.path, tree.pinned);
|
|
427
|
+
}
|
|
428
|
+
return null;
|
|
429
|
+
}
|
|
430
|
+
/**
|
|
431
|
+
* A child's environment: no git routing variable, only qualified PATH entries, and none that leads into a checkout. The
|
|
432
|
+
* batch judges the programs it starts by itself (`programIn`), but one of those starting another by name would look on
|
|
433
|
+
* this PATH: an npm whose launcher runs `env node` would otherwise run a `node` a repository holds.
|
|
434
|
+
*/
|
|
435
|
+
function childEnv(env, checkouts) {
|
|
436
|
+
const out = programEnv(batchEnv(env));
|
|
437
|
+
const roots = checkouts.map((checkout) => leadsTo(checkout) ?? checkout);
|
|
438
|
+
const kept = (out['PATH'] ?? '').split(delimiter).filter((entry) => {
|
|
439
|
+
const real = leadsTo(entry) ?? entry;
|
|
440
|
+
return !roots.some((root) => within(root, real));
|
|
441
|
+
});
|
|
442
|
+
out['PATH'] = kept.length > 0 || process.platform === 'win32' ? kept.join(delimiter) : '/usr/bin:/bin';
|
|
443
|
+
return out;
|
|
444
|
+
}
|
|
445
|
+
/**
|
|
446
|
+
* The one way a batch starts a child: `admit` checks it immediately before, and the child gets `env` without git's
|
|
447
|
+
* routing variables and with only qualified PATH entries, none inside a checkout (`childEnv`). A refused spawn starts
|
|
448
|
+
* nothing and settles with `refused` set.
|
|
449
|
+
*/
|
|
450
|
+
export async function spawnGuarded(run, program, args, options, guard) {
|
|
451
|
+
const { path, argv0 } = programOf(program);
|
|
452
|
+
const why = admit(path, args, options.cwd, guard);
|
|
453
|
+
if (why !== null)
|
|
454
|
+
return { status: null, stdout: '', stderr: why, refused: why };
|
|
455
|
+
return run(path, args, {
|
|
456
|
+
cwd: options.cwd,
|
|
457
|
+
env: childEnv(options.env, guard.checkouts),
|
|
458
|
+
...(argv0 === undefined ? {} : { argv0 }),
|
|
459
|
+
});
|
|
460
|
+
}
|
|
461
|
+
/**
|
|
462
|
+
* `spawnGuarded` for the synchronous probes: the same check and environment; a Windows `.cmd` or `.bat` runs through
|
|
463
|
+
* cmd.exe named by its path, each argument quoted by `cmdArgument`, and one it cannot pass refuses the probe.
|
|
464
|
+
*/
|
|
465
|
+
export function spawnGuardedSync(started, args, options, guard) {
|
|
466
|
+
const { path: program, argv0 } = programOf(started);
|
|
467
|
+
const why = admit(program, args, options.cwd, guard);
|
|
468
|
+
if (why !== null)
|
|
469
|
+
return { status: null, stdout: '', stderr: why, refused: why };
|
|
470
|
+
const env = childEnv(options.env, guard.checkouts);
|
|
471
|
+
const common = {
|
|
472
|
+
cwd: options.cwd,
|
|
473
|
+
env,
|
|
474
|
+
encoding: 'utf8',
|
|
475
|
+
windowsHide: true,
|
|
476
|
+
timeout: BATCH_COMMAND_TIMEOUT_MS,
|
|
477
|
+
killSignal: 'SIGKILL',
|
|
478
|
+
...(argv0 === undefined ? {} : { argv0 }),
|
|
479
|
+
};
|
|
480
|
+
let result;
|
|
481
|
+
if (process.platform === 'win32' && /\.(?:cmd|bat)$/i.test(program)) {
|
|
482
|
+
const quoted = args.map(cmdArgument);
|
|
483
|
+
if (quoted.some((value) => value === null)) {
|
|
484
|
+
const refused = `cmd.exe cannot pass an argument of ${nameOf(program)} unchanged`;
|
|
485
|
+
return { status: null, stdout: '', stderr: refused, refused };
|
|
486
|
+
}
|
|
487
|
+
result = spawnSync(windowsShell(options.env), windowsShellArgs(program, quoted), {
|
|
488
|
+
...common,
|
|
489
|
+
windowsVerbatimArguments: true,
|
|
490
|
+
});
|
|
491
|
+
}
|
|
492
|
+
else
|
|
493
|
+
result = spawnSync(program, [...args], common);
|
|
494
|
+
return {
|
|
495
|
+
status: result.status,
|
|
496
|
+
stdout: typeof result.stdout === 'string' ? result.stdout : '',
|
|
497
|
+
stderr: typeof result.stderr === 'string' ? result.stderr : '',
|
|
498
|
+
};
|
|
499
|
+
}
|
|
500
|
+
const ALL_ONES = 2n ** 64n - 1n;
|
|
501
|
+
/** The worktree's identity now, or null when it cannot be read. */
|
|
502
|
+
export function pinWorktree(path) {
|
|
503
|
+
try {
|
|
504
|
+
const real = realpathSync.native(path);
|
|
505
|
+
const stat = statSync(real, { bigint: true });
|
|
506
|
+
return { real, dev: stat.dev, ino: stat.ino };
|
|
507
|
+
}
|
|
508
|
+
catch {
|
|
509
|
+
return null;
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
/**
|
|
513
|
+
* Null when the worktree is still the folder that was created: the same real path and, where the volume reports an
|
|
514
|
+
* identity (an inode that is neither 0 nor all ones), the same device and inode. A new real path is never adopted.
|
|
515
|
+
*/
|
|
516
|
+
export function checkPinned(path, pinned) {
|
|
517
|
+
const now = pinWorktree(path);
|
|
518
|
+
const unidentified = (id) => id === 0n || id === ALL_ONES;
|
|
519
|
+
const same = pinned !== undefined &&
|
|
520
|
+
pinned !== null &&
|
|
521
|
+
now !== null &&
|
|
522
|
+
fold(now.real) === fold(pinned.real) &&
|
|
523
|
+
(unidentified(pinned.ino) || unidentified(now.ino) || (now.dev === pinned.dev && now.ino === pinned.ino));
|
|
524
|
+
return same ? null : `the worktree ${path} was replaced or moved since the batch created it`;
|
|
525
|
+
}
|
|
526
|
+
/**
|
|
527
|
+
* The run-time check, on the real filesystem, immediately before a step runs: the step's `cwd`, each path-bearing value
|
|
528
|
+
* (resolved against `cwd`) and each mixed-domain value kept as a name that names an existing entry under `cwd` must
|
|
529
|
+
* lead, through any link, into the worktree's real path. Null when they do; otherwise why the repository is refused.
|
|
530
|
+
*/
|
|
531
|
+
export function containedStep(step, cwd, worktree, pinned) {
|
|
532
|
+
let tree;
|
|
533
|
+
try {
|
|
534
|
+
tree = pinned ?? realpathSync.native(worktree);
|
|
535
|
+
}
|
|
536
|
+
catch {
|
|
537
|
+
return `the worktree ${worktree} cannot be read`;
|
|
538
|
+
}
|
|
539
|
+
const check = (value, path) => {
|
|
540
|
+
const real = leadsTo(path);
|
|
541
|
+
if (real === null)
|
|
542
|
+
return `${value} is a link that leads nowhere`;
|
|
543
|
+
return within(tree, real) ? null : `${value} leads outside the worktree, to ${real}`;
|
|
544
|
+
};
|
|
545
|
+
const here = check(cwd, cwd);
|
|
546
|
+
if (here !== null)
|
|
547
|
+
return here;
|
|
548
|
+
for (const entry of pathArguments(step)) {
|
|
549
|
+
let path;
|
|
550
|
+
try {
|
|
551
|
+
path = resolve(cwd, entry.kind === 'file-url' ? fileURLToPath(entry.value) : entry.value);
|
|
552
|
+
}
|
|
553
|
+
catch {
|
|
554
|
+
return `${entry.value} is not a file URL this platform reads`;
|
|
555
|
+
}
|
|
556
|
+
if (entry.kind === 'name') {
|
|
557
|
+
let present = false;
|
|
558
|
+
try {
|
|
559
|
+
present = lstatSync(path, { throwIfNoEntry: false }) !== undefined;
|
|
560
|
+
}
|
|
561
|
+
catch {
|
|
562
|
+
present = false;
|
|
563
|
+
}
|
|
564
|
+
if (!present)
|
|
565
|
+
continue;
|
|
566
|
+
}
|
|
567
|
+
const why = check(entry.value, path);
|
|
568
|
+
if (why !== null)
|
|
569
|
+
return why;
|
|
570
|
+
}
|
|
571
|
+
return null;
|
|
572
|
+
}
|
|
573
|
+
const repoResult = (repo) => ({
|
|
574
|
+
root: repo.root,
|
|
575
|
+
top: repo.top,
|
|
576
|
+
worktree: repo.worktree,
|
|
577
|
+
workspace: repo.workspace,
|
|
578
|
+
branch: repo.branch,
|
|
579
|
+
});
|
|
580
|
+
/** The `package.json` nearest the workspace, at or above it and inside the worktree, or null. */
|
|
581
|
+
function manifestDirectory(workspace, worktree) {
|
|
582
|
+
for (let current = workspace;; current = dirname(current)) {
|
|
583
|
+
if (existsSync(join(current, 'package.json')))
|
|
584
|
+
return current;
|
|
585
|
+
if (resolve(current) === resolve(worktree) || dirname(current) === current)
|
|
586
|
+
return null;
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
/** The last line of a repository a stopped batch never started. */
|
|
590
|
+
export const NOT_RUN = 'not run: batch stopped';
|
|
591
|
+
/** The last line of a repository the batch was stopped in. */
|
|
592
|
+
export const STOPPED = 'stopped: the batch was stopped';
|
|
593
|
+
/**
|
|
594
|
+
* What a failed `git worktree add -b` left: a hook or a checkout that failed leaves the branch and sometimes the
|
|
595
|
+
* worktree, and a killed one leaves both, locked. Neither is `created`, so no later choice could reach them, and the
|
|
596
|
+
* same batch would be refused on them next time. Removed only when they are this run's: the path was free and the branch
|
|
597
|
+
* absent just before the add, and now the worktree on that path has that branch, still at the base, whose commit it was
|
|
598
|
+
* made from. Anything else (a branch that moved, a folder that is no worktree) is left and named; returns what is left.
|
|
599
|
+
*/
|
|
600
|
+
async function undoAdd(git, worktree, destination, branch, sha) {
|
|
601
|
+
const ref = `refs/heads/${branch}`;
|
|
602
|
+
/** The worktrees git lists, each as its lines; none when it cannot say, so nothing is taken for this run's. */
|
|
603
|
+
const worktrees = async () => {
|
|
604
|
+
const listed = await git(['worktree', 'list', '--porcelain']);
|
|
605
|
+
return listed.status === 0 ? listed.stdout.split(/\r?\n\r?\n/).map((block) => block.split(/\r?\n/)) : null;
|
|
606
|
+
};
|
|
607
|
+
const made = (await worktrees())?.find((lines) => {
|
|
608
|
+
const path = lines.find((line) => line.startsWith('worktree '))?.slice('worktree '.length);
|
|
609
|
+
return (path !== undefined &&
|
|
610
|
+
fold(leadsTo(path) ?? path) === fold(destination) &&
|
|
611
|
+
lines.includes(`branch ${ref}`) &&
|
|
612
|
+
lines.includes(`HEAD ${sha}`));
|
|
613
|
+
});
|
|
614
|
+
// Twice forced: it holds what its failed checkout or hook wrote, and a killed add leaves it locked.
|
|
615
|
+
if (made !== undefined)
|
|
616
|
+
await git(['worktree', 'remove', '--force', '--force', worktree]);
|
|
617
|
+
const after = await worktrees();
|
|
618
|
+
const free = after !== null && !after.some((lines) => lines.includes(`branch ${ref}`));
|
|
619
|
+
const head = await git(['rev-parse', '--verify', '--quiet', ref]);
|
|
620
|
+
// Only at the base, compared and deleted in one step by git.
|
|
621
|
+
if (free && head.status === 0 && head.stdout.trim() === sha)
|
|
622
|
+
await git(['update-ref', '-d', ref, sha]);
|
|
623
|
+
const left = [];
|
|
624
|
+
if (existsSync(worktree))
|
|
625
|
+
left.push(`worktree ${worktree}`);
|
|
626
|
+
if ((await git(['rev-parse', '--verify', '--quiet', ref])).status === 0)
|
|
627
|
+
left.push(`branch ${branch}`);
|
|
628
|
+
return left;
|
|
629
|
+
}
|
|
630
|
+
export async function runBatch(plan, state, io) {
|
|
631
|
+
const results = [];
|
|
632
|
+
// Every child of the batch, on the original or in a worktree, runs without git's routing variables.
|
|
633
|
+
const scoped = { ...io, env: batchEnv(io.env) };
|
|
634
|
+
// git is found once and judged against every repository of the batch, then always run by that absolute path.
|
|
635
|
+
const tops = plan.repos.map((repo) => repo.top);
|
|
636
|
+
const git = programIn('git', scoped.env, tops);
|
|
637
|
+
// Where each worktree really leads, fixed now, before anything is awaited.
|
|
638
|
+
const destinations = plan.repos.map((repo) => leadsTo(repo.worktree));
|
|
639
|
+
for (const [index, repo] of plan.repos.entries()) {
|
|
640
|
+
const say = (line) => io.progress(index, line);
|
|
641
|
+
// A stopped batch still lists every repository it did not run, so none drops out of the results.
|
|
642
|
+
if (io.signal.aborted) {
|
|
643
|
+
say(NOT_RUN);
|
|
644
|
+
results.push({ ...repoResult(repo), ok: false, last: NOT_RUN, refused: null, created: false, stopped: true });
|
|
645
|
+
continue;
|
|
646
|
+
}
|
|
647
|
+
if ('refused' in git) {
|
|
648
|
+
say(`refused: ${git.refused}`);
|
|
649
|
+
results.push({ ...repoResult(repo), ok: false, last: git.refused, refused: git.refused, created: false });
|
|
650
|
+
continue;
|
|
651
|
+
}
|
|
652
|
+
results.push(await runRepo(repo, state, scoped, say, git, destinations[index] ?? null, tops));
|
|
653
|
+
}
|
|
654
|
+
return results;
|
|
655
|
+
}
|
|
656
|
+
async function runRepo(repo, state, io, say, gitPath, destination,
|
|
657
|
+
/** Every repository of the batch: none is a place to run a program from, or to look for one. */
|
|
658
|
+
tops) {
|
|
659
|
+
const { top, worktree, workspace, branch } = repo;
|
|
660
|
+
let created = false;
|
|
661
|
+
let pinned = null;
|
|
662
|
+
let from;
|
|
663
|
+
const done = (ok, last, refused = null) => {
|
|
664
|
+
say(refused === null ? last : `refused: ${refused}`);
|
|
665
|
+
return {
|
|
666
|
+
...repoResult(repo),
|
|
667
|
+
ok,
|
|
668
|
+
last: refused ?? last,
|
|
669
|
+
refused,
|
|
670
|
+
created,
|
|
671
|
+
pinned,
|
|
672
|
+
...(from === undefined ? {} : { base: from }),
|
|
673
|
+
};
|
|
674
|
+
};
|
|
675
|
+
const refuse = (why) => done(false, why, why);
|
|
676
|
+
const stop = () => ({ ...done(false, STOPPED), stopped: true });
|
|
677
|
+
if (repo.refused !== null)
|
|
678
|
+
return refuse(repo.refused);
|
|
679
|
+
let guard = { checkouts: tops };
|
|
680
|
+
const env = withoutSshPrompt(io.env, gitWith(io.env, gitPath, guard), top);
|
|
681
|
+
const git = (args) => spawnGuarded(io.run, gitPath, ['-C', top, ...args], { cwd: top, env }, guard);
|
|
682
|
+
// Planning judged the path by its spelling; a link on the way (a configured root, or `.ia-worktrees` itself) could
|
|
683
|
+
// still lead it into the checkout or the IA home, where git would then write. Judged by where it really leads.
|
|
684
|
+
const checkout = leadsTo(top) ?? top;
|
|
685
|
+
// Every other repository of the batch, by where it really leads: git would write a worktree there into its tree.
|
|
686
|
+
const others = tops
|
|
687
|
+
.filter((entry) => fold(entry) !== fold(top))
|
|
688
|
+
.map((entry) => ({ entry, real: leadsTo(entry) ?? entry }))
|
|
689
|
+
.filter(({ real }) => fold(real) !== fold(checkout));
|
|
690
|
+
const home = repo.iaHome === undefined ? null : leadsTo(repo.iaHome);
|
|
691
|
+
const judge = (real) => {
|
|
692
|
+
if (real === null)
|
|
693
|
+
return `the worktree path ${worktree} passes through a link that leads nowhere`;
|
|
694
|
+
if (within(checkout, real))
|
|
695
|
+
return `the worktree path ${worktree} leads inside the repository, to ${real}`;
|
|
696
|
+
const other = others.find((entry) => within(entry.real, real));
|
|
697
|
+
if (other !== undefined)
|
|
698
|
+
return `the worktree path ${worktree} leads inside ${other.entry}, another repository of this batch, to ${real}`;
|
|
699
|
+
if (home !== null && within(home, real))
|
|
700
|
+
return `the worktree path ${worktree} leads inside the IA home, to ${real}`;
|
|
701
|
+
return null;
|
|
702
|
+
};
|
|
703
|
+
const first = judge(destination);
|
|
704
|
+
if (first !== null)
|
|
705
|
+
return refuse(first);
|
|
706
|
+
say('fetching origin');
|
|
707
|
+
const base = await findBase(top, io.run, env, gitPath, guard);
|
|
708
|
+
if ('why' in base)
|
|
709
|
+
return refuse(base.why);
|
|
710
|
+
from = base.base;
|
|
711
|
+
// The offers were read from the local checkout, but the worktree starts from the base: a workspace the base does not
|
|
712
|
+
// hold (added on a local branch, or not pushed) would leave the steps nothing to act on, so it is refused here.
|
|
713
|
+
const inRepo = relative(top, repo.root).split(sep).join('/');
|
|
714
|
+
const held = await git([
|
|
715
|
+
'rev-parse',
|
|
716
|
+
'--verify',
|
|
717
|
+
'--quiet',
|
|
718
|
+
`${base.base}:${inRepo === '' ? '' : `${inRepo}/`}.ia/src`,
|
|
719
|
+
]);
|
|
720
|
+
if (held.refused !== undefined)
|
|
721
|
+
return refuse(held.refused);
|
|
722
|
+
// git does not follow a link inside a tree path, so a workspace reached through a committed link (`notes -> real`)
|
|
723
|
+
// is not found that way: one whose path has a link on it is left to the worktree-time check, which accepts a link
|
|
724
|
+
// that stays inside the worktree and refuses one that leads out, with that reason.
|
|
725
|
+
const prefixes = `${inRepo === '' ? '' : `${inRepo}/`}.ia/src`
|
|
726
|
+
.split('/')
|
|
727
|
+
.map((_, index, parts) => parts.slice(0, index + 1).join('/'));
|
|
728
|
+
const linked = held.status === 0 ? null : await git(['ls-tree', base.base, '--', ...prefixes.slice(0, -1)]);
|
|
729
|
+
if (linked?.refused !== undefined)
|
|
730
|
+
return refuse(linked.refused);
|
|
731
|
+
const throughLink = linked !== null && linked.status === 0 && linked.stdout.split(/\r?\n/).some((line) => line.startsWith('120000 '));
|
|
732
|
+
if (held.status !== 0 && !throughLink)
|
|
733
|
+
return refuse(`the workspace ${inRepo === '' ? '.' : inRepo} has no .ia/src in ${base.base}, which the worktree would start from`);
|
|
734
|
+
if (existsSync(worktree))
|
|
735
|
+
return refuse(`the worktree path already exists: ${worktree}`);
|
|
736
|
+
const branchProbe = await git(['rev-parse', '--verify', '--quiet', `refs/heads/${branch}`]);
|
|
737
|
+
if (branchProbe.refused !== undefined)
|
|
738
|
+
return refuse(branchProbe.refused);
|
|
739
|
+
if (branchProbe.status === 0)
|
|
740
|
+
return refuse(`the branch already exists: ${branch}`);
|
|
741
|
+
// The awaits above leave time for a link on the way to be retargeted: judged again, it must lead where it did.
|
|
742
|
+
const now = leadsTo(worktree);
|
|
743
|
+
if (now === null || fold(now) !== fold(destination))
|
|
744
|
+
return refuse(`the worktree path ${worktree} changed while the batch ran: it now leads to ${now ?? 'nowhere'}`);
|
|
745
|
+
const again = judge(now);
|
|
746
|
+
if (again !== null)
|
|
747
|
+
return refuse(again);
|
|
748
|
+
if (io.signal.aborted)
|
|
749
|
+
return stop();
|
|
750
|
+
const baseSha = await git(['rev-parse', '--verify', '--quiet', `refs/remotes/${base.base}^{commit}`]);
|
|
751
|
+
if (baseSha.refused !== undefined)
|
|
752
|
+
return refuse(baseSha.refused);
|
|
753
|
+
say(`creating ${worktree} on ${branch} from ${base.base}`);
|
|
754
|
+
const added = await git(['worktree', 'add', '--no-track', '-b', branch, worktree, base.base]);
|
|
755
|
+
if (added.refused !== undefined)
|
|
756
|
+
return refuse(added.refused);
|
|
757
|
+
if (added.status !== 0) {
|
|
758
|
+
const why = `git worktree add failed: ${lastLine(added.stderr)}`;
|
|
759
|
+
// git said a path or branch already exists, so something else made it since the probes: nothing here is this run's.
|
|
760
|
+
if (/already exists/.test(added.stderr) || baseSha.status !== 0)
|
|
761
|
+
return done(false, why);
|
|
762
|
+
const left = await undoAdd(git, worktree, now, branch, baseSha.stdout.trim());
|
|
763
|
+
return done(false, left.length === 0 ? why : `${why}; left behind: ${left.join(', ')}`);
|
|
764
|
+
}
|
|
765
|
+
created = true;
|
|
766
|
+
// What was created is pinned: its real path must be the destination, and it is checked before every later command.
|
|
767
|
+
pinned = pinWorktree(worktree);
|
|
768
|
+
if (pinned === null || fold(pinned.real) !== fold(now))
|
|
769
|
+
return refuse(`the worktree ${worktree} was replaced or moved since the batch created it`);
|
|
770
|
+
const tree = pinned.real;
|
|
771
|
+
guard = { checkouts: tops, worktree: { path: worktree, pinned } };
|
|
772
|
+
const run = async (step, label) => {
|
|
773
|
+
const replaced = checkPinned(worktree, pinned);
|
|
774
|
+
if (replaced !== null)
|
|
775
|
+
return `refused:${label}: ${replaced}`;
|
|
776
|
+
const outside = containedStep(step, workspace, worktree, tree);
|
|
777
|
+
if (outside !== null)
|
|
778
|
+
return `refused:${label}: ${outside}`;
|
|
779
|
+
let file, args, stepEnv;
|
|
780
|
+
if (step.program === 'ia') {
|
|
781
|
+
// The copy is found again before every step, in the worktree only: an earlier step may have installed it.
|
|
782
|
+
const found = io.resolveRepo(workspace);
|
|
783
|
+
const copy = found !== null && within(tree, found.packageRoot) ? found : null;
|
|
784
|
+
if (copy === null && step.requires === 'repo-copy')
|
|
785
|
+
return `refused:${label}: the repo copy is not installed`;
|
|
786
|
+
// The file Node will run, by its real path, now: a package folder inside the worktree can still name an entry,
|
|
787
|
+
// or hold a link, that leads elsewhere. Only the running copy's own entry may lie outside the worktree.
|
|
788
|
+
if (copy !== null) {
|
|
789
|
+
const real = leadsTo(copy.entry);
|
|
790
|
+
if (real === null || !within(tree, real))
|
|
791
|
+
return `refused:${label}: the repo copy's entry ${copy.entry} leads outside the worktree, to ${real ?? 'nowhere'}`;
|
|
792
|
+
}
|
|
793
|
+
file = process.execPath;
|
|
794
|
+
args = [copy?.entry ?? runningEntry(state.running.packageRoot), ...confirmedArgv(step)];
|
|
795
|
+
stepEnv = { ...env, [NO_HANDOFF]: '1' };
|
|
796
|
+
}
|
|
797
|
+
else {
|
|
798
|
+
const [name, ...rest] = step.argv;
|
|
799
|
+
if (name === undefined)
|
|
800
|
+
return `refused:${label}: the step names no program`;
|
|
801
|
+
// The program the runner will start, judged by its real path and then run by it: never one the checkout holds.
|
|
802
|
+
const program = programIn(name, env, tops);
|
|
803
|
+
if ('refused' in program)
|
|
804
|
+
return `refused:${label}: ${program.refused}`;
|
|
805
|
+
file = program;
|
|
806
|
+
args = rest;
|
|
807
|
+
stepEnv = env;
|
|
808
|
+
}
|
|
809
|
+
const shown = step.program === 'ia' ? displayFix({ ...step, argv: confirmedArgv(step) }) : displayFix(step);
|
|
810
|
+
say(`$ ${shown}`);
|
|
811
|
+
const result = await spawnGuarded(io.run, file, args, { cwd: workspace, env: stepEnv }, guard);
|
|
812
|
+
if (result.refused !== undefined)
|
|
813
|
+
return `refused:${label}: ${result.refused}`;
|
|
814
|
+
if (result.status === 0)
|
|
815
|
+
return null;
|
|
816
|
+
const how = result.status === null ? 'did not finish' : `exited ${result.status}`;
|
|
817
|
+
const output = lastLine(result.stderr) || lastLine(result.stdout);
|
|
818
|
+
return `${shown} ${how}${output === '' ? '' : `: ${output}`}`;
|
|
819
|
+
};
|
|
820
|
+
const failed = (why) => why.startsWith('refused:') ? refuse(why.slice('refused:'.length).replace(/^install: /, '')) : done(false, why);
|
|
821
|
+
if (io.signal.aborted)
|
|
822
|
+
return stop();
|
|
823
|
+
const manifest = manifestDirectory(workspace, worktree);
|
|
824
|
+
if (manifest !== null) {
|
|
825
|
+
const probe = checkPinned(worktree, pinned);
|
|
826
|
+
if (probe !== null)
|
|
827
|
+
return refuse(probe);
|
|
828
|
+
const listing = gitWith(env, gitPath, guard);
|
|
829
|
+
const { manager, conflict } = detectPackageManager(manifest, listing);
|
|
830
|
+
if (conflict.length > 0)
|
|
831
|
+
return refuse(`package managers disagree: ${conflict.join(', ')}`);
|
|
832
|
+
if (manager === null)
|
|
833
|
+
return refuse(`no package manager is declared or locked in ${manifest}`);
|
|
834
|
+
// An offer that begins with an install or a pin installs by that step (checked and run like every step, below), as
|
|
835
|
+
// the preview says, only with the manager the base declares or locks; any other offer gets the batch's install.
|
|
836
|
+
const first = installsFirst(repo.steps);
|
|
837
|
+
if (first !== null && first !== manager)
|
|
838
|
+
return refuse(`the first step installs with ${first}, but the base is locked by ${manager}; run this offer from that workspace's own view instead`);
|
|
839
|
+
if (first === null) {
|
|
840
|
+
// No lifecycle script runs, and a tracked lockfile is never rewritten: the install is frozen to it.
|
|
841
|
+
const install = {
|
|
842
|
+
program: 'external',
|
|
843
|
+
argv: [...batchInstallArgv(manager, manifest, workspace, lockTracked(manifest, manager, listing))],
|
|
844
|
+
flow: 'confirm',
|
|
845
|
+
writesTo: 'repo',
|
|
846
|
+
};
|
|
847
|
+
const why = await run(install, 'install');
|
|
848
|
+
if (why !== null)
|
|
849
|
+
return failed(why);
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
else {
|
|
853
|
+
const outside = checkPinned(worktree, pinned) ??
|
|
854
|
+
containedStep({ program: 'external', argv: ['none'], flow: 'confirm', writesTo: 'none' }, workspace, worktree, tree);
|
|
855
|
+
if (outside !== null)
|
|
856
|
+
return refuse(outside);
|
|
857
|
+
}
|
|
858
|
+
for (const [index, step] of repo.steps.entries()) {
|
|
859
|
+
if (io.signal.aborted)
|
|
860
|
+
return stop();
|
|
861
|
+
const why = await run(step, `step ${index + 1}`);
|
|
862
|
+
if (why !== null)
|
|
863
|
+
return failed(why);
|
|
864
|
+
}
|
|
865
|
+
const count = repo.steps.length;
|
|
866
|
+
return done(true, count === 1 ? '1 step passed' : `${count} steps passed`);
|
|
867
|
+
}
|
|
868
|
+
//# sourceMappingURL=batch-run.js.map
|