@joberthel/worktree 0.0.0-stage → 1.0.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.
@@ -0,0 +1,446 @@
1
+ import { once } from 'node:events';
2
+ import { access, realpath, unlink } from 'node:fs/promises';
3
+ import { isAbsolute, relative, resolve, sep } from 'node:path';
4
+ import process from 'node:process';
5
+ import { createInterface } from 'node:readline/promises';
6
+ import { configPath, loadConfig } from '../config/load.js';
7
+ import { cloneNamedVolumes, composeFilesForWorktree, docker, prepareVolumeCopy, resolveSourceVolumes, runCompose, writeVolumeOverride } from '../docker/compose.js';
8
+ import { git, repositoryInfo } from '../git/repository.js';
9
+ import { AttachedStore, StateStore } from '../state/store.js';
10
+ import { formatConfirmation } from './confirmation.js';
11
+ import { copyConfiguredPaths } from './copy-paths.js';
12
+ import { startWithHooks, validateSourceHooks, validateWorktreeHooks } from './hooks.js';
13
+ import { checkInterrupted, currentSignal } from './process.js';
14
+ import { outputReporter, runStep } from './progress.js';
15
+ async function context(cwd) {
16
+ const info = await repositoryInfo(cwd);
17
+ return {
18
+ ...info,
19
+ store: new StateStore(info.gitCommonDir),
20
+ };
21
+ }
22
+ async function managed(name, cwd) {
23
+ const { store } = await context(cwd);
24
+ const state = await store.get(name);
25
+ return { store, state };
26
+ }
27
+ async function removeOwnedVolume(volume, repositoryId, name, cwd) {
28
+ let labels;
29
+ try {
30
+ const raw = await docker([
31
+ 'volume',
32
+ 'inspect',
33
+ '--format',
34
+ '{{json .Labels}}',
35
+ volume,
36
+ ], cwd);
37
+ labels = JSON.parse(raw || 'null');
38
+ }
39
+ catch (error) {
40
+ if (/no such volume/i.test(error.message))
41
+ return;
42
+ throw error;
43
+ }
44
+ if (labels?.['com.wt.repository'] !== repositoryId || labels['com.wt.worktree'] !== name)
45
+ throw new Error(`Refusing to remove volume ${volume}: ownership labels do not match this environment.`);
46
+ await docker(['volume', 'rm', volume], cwd);
47
+ }
48
+ async function removeClonedVolumes(state, cwd, keep = []) {
49
+ const discovered = await docker([
50
+ 'volume',
51
+ 'ls',
52
+ '--format',
53
+ '{{.Name}}',
54
+ '--filter',
55
+ `label=com.wt.repository=${state.repositoryId}`,
56
+ '--filter',
57
+ `label=com.wt.worktree=${state.name}`,
58
+ ], cwd);
59
+ const volumes = new Set([
60
+ ...Object.values(state.volumes),
61
+ ...state.retiredVolumes ?? [],
62
+ ...discovered.split('\n').filter(Boolean),
63
+ ]);
64
+ for (const volume of keep)
65
+ volumes.delete(volume);
66
+ for (const volume of volumes)
67
+ await removeOwnedVolume(volume, state.repositoryId, state.name, cwd);
68
+ }
69
+ export async function listEnvironments(cwd) {
70
+ const { store } = await context(cwd);
71
+ const states = await store.list();
72
+ if (states.length === 0)
73
+ return [];
74
+ const dockerStatus = await dockerStatuses(cwd);
75
+ return states.map(state => ({
76
+ ...state,
77
+ dockerStatus: dockerStatus(state.projectName),
78
+ }));
79
+ }
80
+ /** Reads all Compose containers once and returns a summary lookup by project name. */
81
+ export async function dockerStatuses(cwd, timeout) {
82
+ const output = await docker([
83
+ 'ps',
84
+ '-a',
85
+ '--filter',
86
+ 'label=com.docker.compose.project',
87
+ '--format',
88
+ '{{.Label "com.docker.compose.project"}}\t{{.State}}\t{{.Status}}',
89
+ ], cwd, { timeout });
90
+ const rows = output.split('\n').map(row => row.split('\t'));
91
+ return (projectName) => {
92
+ const statuses = rows.filter(([project]) => project === projectName);
93
+ const finished = statuses.filter(([, status, detail]) => status === 'exited' && detail?.startsWith('Exited (0)')).length;
94
+ const running = statuses.some(([, status]) => status === 'running');
95
+ return statuses.length === 0
96
+ ? 'missing'
97
+ : finished === statuses.length
98
+ ? 'finished'
99
+ : running && finished
100
+ ? `running (${finished} exited)`
101
+ : running ? 'running' : 'stopped';
102
+ };
103
+ }
104
+ export async function inspectEnvironment(name, cwd) {
105
+ const { state } = await managed(name, cwd);
106
+ return inspectState(state, cwd);
107
+ }
108
+ export function parseContainers(output) {
109
+ return output.split('\n').filter(Boolean).map((line) => {
110
+ const [name, service, state, ...status] = line.split('\t');
111
+ return {
112
+ name,
113
+ service: service || name,
114
+ state: state ?? '',
115
+ status: status.join('\t'),
116
+ };
117
+ }).sort((a, b) => a.service.localeCompare(b.service) || a.name.localeCompare(b.name));
118
+ }
119
+ export async function inspectState(state, cwd) {
120
+ const containers = await docker([
121
+ 'ps',
122
+ '-a',
123
+ '--filter',
124
+ `label=com.docker.compose.project=${state.projectName}`,
125
+ '--format',
126
+ '{{.Names}}\t{{.Label "com.docker.compose.service"}}\t{{.State}}\t{{.Status}}',
127
+ ], cwd);
128
+ return {
129
+ ...state,
130
+ containers: parseContainers(containers),
131
+ };
132
+ }
133
+ export async function resolveEnvironmentName(name, cwd) {
134
+ if (name !== undefined)
135
+ return name;
136
+ const { root, store } = await context(cwd);
137
+ const here = await realpath(root);
138
+ for (const state of await store.list()) {
139
+ const path = await realpath(state.path).catch(() => resolve(state.path));
140
+ if (path === here)
141
+ return state.name;
142
+ }
143
+ throw new Error('Current directory is not inside a managed worktree; pass a worktree name.');
144
+ }
145
+ export async function composeOperation(name, action, args, cwd, progress) {
146
+ const { store } = await context(cwd);
147
+ const unlock = action === 'docker'
148
+ ? undefined
149
+ : await store.lock('repository');
150
+ try {
151
+ const state = await store.get(name);
152
+ return await runManagedCompose(state, action, args, progress);
153
+ }
154
+ finally {
155
+ await unlock?.();
156
+ }
157
+ }
158
+ export async function runManagedCompose(state, action, args, progress) {
159
+ const { name } = state;
160
+ if (!await exists(state.path))
161
+ throw new Error(`Worktree directory is missing: ${state.path}`);
162
+ const incomplete = state.status !== 'ready' && (state.status !== 'failed' || !await exists(state.overridePath));
163
+ if (incomplete && action !== 'docker')
164
+ throw new Error(`Worktree ${name} is ${state.status}. Run wt reset ${name} to retry setup or wt rm ${name} to remove it.`);
165
+ const files = await composeFilesForWorktree(state.composeFiles, state.sourceWorktreePath, state.path);
166
+ const command = action === 'docker'
167
+ ? args
168
+ : action === 'start'
169
+ ? ['up', '-d']
170
+ : action === 'stop'
171
+ ? ['stop']
172
+ : ['restart'];
173
+ const labels = {
174
+ start: 'Starting Docker Compose services',
175
+ stop: 'Stopping Docker Compose services',
176
+ restart: 'Restarting Docker Compose services',
177
+ docker: `Running docker compose ${args.join(' ')}`,
178
+ };
179
+ return runStep(progress, labels[action], async () => runCompose(state, files, command, {
180
+ inherit: action === 'docker',
181
+ onOutput: outputReporter(progress, labels[action]),
182
+ }));
183
+ }
184
+ /**
185
+ * Refuses to change an environment that hosts a worktree of another
186
+ * repository. That worktree is removed or reset from its own repository so its
187
+ * changes are checked and its hooks run.
188
+ */
189
+ export async function checkNotHosting(state, command) {
190
+ const { attachment } = state;
191
+ if (attachment === undefined || await new AttachedStore(attachment.gitCommonDir).find(attachment.name) === undefined)
192
+ return;
193
+ throw new Error(`Worktree ${state.name} hosts ${attachment.path}. Run wt ${command} ${attachment.name} from that repository instead.`);
194
+ }
195
+ export async function removeEnvironment(name, cwd, force = false, confirm, progress) {
196
+ const { store, state } = await managed(name, cwd);
197
+ await checkNotHosting(state, 'rm');
198
+ const here = await realpath(cwd);
199
+ const target = await realpath(state.path).catch(() => resolve(state.path));
200
+ const rel = relative(target, here);
201
+ if (rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel))
202
+ throw new Error(`Current directory is inside ${target}; change directory before removing it.`);
203
+ if (!force && !process.stdin.isTTY)
204
+ throw new Error('wt rm requires an interactive terminal or --force.');
205
+ const dependents = (await store.list()).filter(item => item.sourceProject === state.projectName);
206
+ if (!force) {
207
+ const request = {
208
+ title: `Remove worktree ${name}?`,
209
+ details: [
210
+ { label: 'Directory', value: target },
211
+ { label: 'Compose project', value: state.projectName },
212
+ { label: 'Volumes', value: Object.values(state.volumes).join(', ') || 'none' },
213
+ ...dependents.map(item => ({ label: 'Dependent worktree (reset will fail)', value: item.name })),
214
+ ],
215
+ note: `Uncommitted changes in the worktree and all data in its volumes will be lost.${state.branch === ''
216
+ ? ''
217
+ : ` The branch ${state.branch} is kept.`}`,
218
+ action: 'Remove',
219
+ };
220
+ if (!await requestConfirmation(request, confirm))
221
+ return false;
222
+ }
223
+ const unlock = await store.lock('repository');
224
+ try {
225
+ checkInterrupted();
226
+ await checkUnchanged(store, state);
227
+ await removeLocked(state, store, cwd, progress);
228
+ return true;
229
+ }
230
+ finally {
231
+ await unlock();
232
+ }
233
+ }
234
+ /**
235
+ * Removes the environment's containers, cloned volumes, Git worktree, and
236
+ * state while the repository lock is held. `cwd` must be inside the
237
+ * environment's repository. `retryName` is shown when the directory remains.
238
+ */
239
+ export async function removeLocked(state, store, cwd, progress, retryName = state.name) {
240
+ const target = await realpath(state.path).catch(() => resolve(state.path));
241
+ await store.save({ ...state, status: 'removing' });
242
+ await runStep(progress, 'Stopping and removing Compose containers', async () => downEnvironment(state, cwd, true));
243
+ await runStep(progress, 'Removing cloned Docker volumes', async () => removeClonedVolumes(state, cwd));
244
+ const registeredWorktrees = await git([
245
+ 'worktree',
246
+ 'list',
247
+ '--porcelain',
248
+ '-z',
249
+ ], cwd);
250
+ if (registeredWorktrees.split('\0').includes(`worktree ${target}`)) {
251
+ await runStep(progress, 'Removing Git worktree', async () => git([
252
+ 'worktree',
253
+ 'remove',
254
+ '--force',
255
+ state.path,
256
+ ], cwd));
257
+ }
258
+ if (await exists(target))
259
+ throw new Error(`Unregistered worktree directory still exists at ${target}. Move it out of the way and retry wt rm ${retryName}.`);
260
+ if (await exists(state.overridePath))
261
+ await unlink(state.overridePath);
262
+ await store.remove(state.name);
263
+ }
264
+ export async function resetEnvironment(name, cwd, force = false, confirm, progress) {
265
+ const { store, state } = await managed(name, cwd);
266
+ await checkNotHosting(state, 'reset');
267
+ const { sourceRoot, config } = await prepareReset(state, cwd);
268
+ if (!force && !process.stdin.isTTY)
269
+ throw new Error('wt reset requires an interactive terminal or --force.');
270
+ if (!force) {
271
+ const request = {
272
+ title: `Reset worktree ${name}?`,
273
+ details: [
274
+ { label: 'Directory', value: state.path },
275
+ { label: 'Replaced paths', value: config.copy.join(', ') || 'none' },
276
+ { label: 'Recreated volumes', value: Object.values(state.volumes).join(', ') || 'none' },
277
+ ],
278
+ note: `These paths and volumes are overwritten with fresh copies from ${sourceRoot}. Other files in the worktree are left alone.`,
279
+ action: 'Reset',
280
+ };
281
+ if (!await requestConfirmation(request, confirm))
282
+ return false;
283
+ }
284
+ const unlock = await store.lock('repository');
285
+ try {
286
+ checkInterrupted();
287
+ await checkUnchanged(store, state);
288
+ if (state.status === 'removing')
289
+ throw new Error(`Removal of ${name} is incomplete. Retry wt rm ${name}.`);
290
+ await resetLocked({ ...state, sourceWorktreePath: sourceRoot }, store, config, cwd, { progress });
291
+ return true;
292
+ }
293
+ finally {
294
+ await unlock();
295
+ }
296
+ }
297
+ /**
298
+ * Loads the configuration an environment was created with and checks that
299
+ * its copy paths and hooks are available before a reset.
300
+ */
301
+ export async function prepareReset(state, cwd, retryName = state.name) {
302
+ if (!await exists(state.path))
303
+ throw new Error(`Worktree directory is missing: ${state.path}. Run wt rm ${retryName} to clean up its resources.`);
304
+ const sourceRoot = await realpath(state.sourceWorktreePath).catch((error) => {
305
+ throw new Error(`Source worktree ${state.sourceWorktreePath} is unavailable. Restore it before resetting ${retryName}.`, { cause: error });
306
+ });
307
+ const fallback = state.configurationPath === undefined
308
+ ? (await context(cwd)).repositoryRoot
309
+ : sourceRoot;
310
+ const config = await loadConfig(sourceRoot, state.configurationPath === undefined
311
+ ? await configPath(sourceRoot, fallback)
312
+ : state.configurationPath);
313
+ await validateCopyAndHooks(config, sourceRoot, state.path);
314
+ return { sourceRoot, config };
315
+ }
316
+ /** Checks a configuration's copy paths and executable hooks for a reset. */
317
+ export async function validateCopyAndHooks(config, sourceRoot, path) {
318
+ for (const entry of config.copy)
319
+ await access(resolve(sourceRoot, entry));
320
+ await validateWorktreeHooks(config.hooks, path, hook => config.copy.some(entry => hook === entry || hook.startsWith(`${entry}/`))
321
+ ? sourceRoot
322
+ : path);
323
+ await validateSourceHooks(config.hooks, sourceRoot);
324
+ }
325
+ /**
326
+ * Refreshes the environment's volumes and copied files and runs its hooks
327
+ * again while the repository lock is held. `nested` adds hook layers for a
328
+ * checkout of another repository inside the environment.
329
+ */
330
+ export async function resetLocked(state, store, config, cwd, { progress, nested } = {}) {
331
+ const { sourceWorktreePath: sourceRoot } = state;
332
+ const current = {
333
+ ...state,
334
+ retiredVolumes: [
335
+ ...state.retiredVolumes ?? [],
336
+ ],
337
+ };
338
+ const source = (await store.list()).find(item => item.projectName === state.sourceProject);
339
+ const sources = await resolveSourceVolumes(state.sourceProject, sourceRoot, state.composeFiles, source?.volumes, state.volumes);
340
+ const image = Object.keys(sources).length
341
+ ? await prepareVolumeCopy(sourceRoot)
342
+ : '';
343
+ await store.save({ ...current, status: 'resetting' });
344
+ try {
345
+ const volumes = await runStep(progress, 'Cloning fresh Docker volumes', async () => cloneNamedVolumes(sources, state, sourceRoot, image, async (volume) => {
346
+ current.retiredVolumes.push(volume);
347
+ await store.save({ ...current, status: 'resetting' });
348
+ }));
349
+ await runStep(progress, 'Stopping Docker Compose services', async () => downEnvironment(state, cwd, false));
350
+ if (config.copy.length > 0)
351
+ await runStep(progress, 'Refreshing configured files', async () => copyConfiguredPaths(sourceRoot, state.path, config.copy));
352
+ await validateWorktreeHooks(config.hooks, state.path);
353
+ await writeVolumeOverride(state.overridePath, volumes);
354
+ const refreshed = new Set(Object.values(volumes));
355
+ current.retiredVolumes = [
356
+ ...current.retiredVolumes.filter(volume => !refreshed.has(volume)),
357
+ ...Object.values(state.volumes),
358
+ ];
359
+ current.volumes = volumes;
360
+ await store.save({ ...current, status: 'resetting' });
361
+ const targetComposeFiles = await composeFilesForWorktree(state.composeFiles, sourceRoot, state.path);
362
+ const environment = {
363
+ ...current,
364
+ targetComposeFiles,
365
+ sourceComposeFiles: [
366
+ ...state.composeFiles,
367
+ ...(source
368
+ ? [source.overridePath]
369
+ : []),
370
+ ],
371
+ };
372
+ await startWithHooks(config.hooks, environment, progress, nested?.(environment));
373
+ await runStep(progress, 'Removing old cloned Docker volumes', async () => removeClonedVolumes(current, cwd, Object.values(volumes)));
374
+ const { error: _error, retiredVolumes: _retired, ...ready } = current;
375
+ await store.save({ ...ready, status: 'ready' });
376
+ }
377
+ catch (error) {
378
+ await store.save({ ...current, status: 'failed', error: error.message });
379
+ throw error;
380
+ }
381
+ }
382
+ export async function exists(path) {
383
+ try {
384
+ await access(path);
385
+ return true;
386
+ }
387
+ catch (error) {
388
+ if (error.code === 'ENOENT')
389
+ return false;
390
+ throw error;
391
+ }
392
+ }
393
+ export async function checkUnchanged(store, state) {
394
+ if (JSON.stringify(await store.get(state.name)) !== JSON.stringify(state))
395
+ throw new Error(`Worktree ${state.name} changed while waiting. Retry the command.`);
396
+ }
397
+ async function downEnvironment(state, cwd, removeImages) {
398
+ const filter = `label=com.docker.compose.project=${state.projectName}`;
399
+ const containers = (await docker(['ps', '-aq', '--filter', filter], cwd)).split(/\s+/).filter(Boolean);
400
+ if (containers.length) {
401
+ await docker(['stop', ...containers], cwd);
402
+ await docker(['rm', '--volumes', ...containers], cwd);
403
+ }
404
+ for (const resource of ['network', 'volume']) {
405
+ const names = (await docker([
406
+ resource,
407
+ 'ls',
408
+ '--filter',
409
+ filter,
410
+ '--format',
411
+ '{{.Name}}',
412
+ ], cwd)).split(/\s+/).filter(Boolean);
413
+ if (names.length)
414
+ await docker([resource, 'rm', ...names], cwd);
415
+ }
416
+ if (removeImages) {
417
+ const images = (await docker([
418
+ 'image',
419
+ 'ls',
420
+ '--filter',
421
+ filter,
422
+ '--format',
423
+ '{{.Repository}}:{{.Tag}}',
424
+ ], cwd)).split(/\s+/).filter(image => image.startsWith(`${state.projectName}-`) && !image.endsWith(':<none>'));
425
+ if (images.length)
426
+ await docker(['image', 'rm', ...images], cwd);
427
+ }
428
+ }
429
+ export async function requestConfirmation(request, confirm) {
430
+ checkInterrupted();
431
+ if (confirm)
432
+ return confirm(request);
433
+ process.stderr.write(formatConfirmation(request));
434
+ const input = createInterface({ input: process.stdin, terminal: false });
435
+ try {
436
+ const signal = currentSignal();
437
+ const answer = await Promise.race([
438
+ input.question('', { signal }),
439
+ once(input, 'close', { signal }).then(() => ''),
440
+ ]);
441
+ return /^y(?:es)?$/i.test(answer.trim());
442
+ }
443
+ finally {
444
+ input.close();
445
+ }
446
+ }
@@ -0,0 +1,67 @@
1
+ import { mkdir, mkdtemp, realpath, rm } from 'node:fs/promises';
2
+ import { tmpdir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import process from 'node:process';
5
+ import { vi } from 'vitest';
6
+ import { StateStore } from '../../state/store.js';
7
+ /**
8
+ * Creates a source checkout and a saved, ready `feature` environment in a
9
+ * temporary directory, and gives the mocks working defaults.
10
+ */
11
+ export async function createFixture(mocks) {
12
+ vi.resetAllMocks();
13
+ const base = await realpath(await mkdtemp(join(tmpdir(), 'wt-manage-')));
14
+ const source = join(base, 'source');
15
+ const common = join(source, '.git');
16
+ const store = new StateStore(common);
17
+ const state = {
18
+ schemaVersion: 1,
19
+ repositoryId: 'repo',
20
+ name: 'feature',
21
+ path: join(base, 'feature'),
22
+ branch: 'feature',
23
+ sourceWorktreePath: source,
24
+ sourceProject: 'parent',
25
+ composeFiles: [
26
+ join(source, 'compose.yml'),
27
+ ],
28
+ overridePath: join(store.directory, 'feature.compose.yml'),
29
+ projectName: 'wt-repo-feature',
30
+ volumes: { db: 'old' },
31
+ status: 'ready',
32
+ };
33
+ await mkdir(state.path);
34
+ await store.save(state);
35
+ mocks.repositoryInfo.mockResolvedValue({ root: source, repositoryRoot: source, gitCommonDir: common });
36
+ mocks.git.mockResolvedValue('');
37
+ mocks.docker.mockImplementation(async (args) => {
38
+ if (args[0] === 'volume' && args[1] === 'inspect')
39
+ return '{"com.wt.repository":"repo","com.wt.worktree":"feature"}';
40
+ return '';
41
+ });
42
+ mocks.resolveSourceVolumes.mockResolvedValue({ db: 'source-volume' });
43
+ mocks.prepareVolumeCopy.mockResolvedValue('image');
44
+ mocks.cloneNamedVolumes.mockImplementation(async (_sources, _owner, _cwd, _image, record) => {
45
+ await record('fresh', { db: 'fresh' });
46
+ return { db: 'fresh' };
47
+ });
48
+ return { base, source, common, state, store };
49
+ }
50
+ export async function removeFixture(fixture) {
51
+ vi.restoreAllMocks();
52
+ await rm(fixture.base, { recursive: true, force: true });
53
+ }
54
+ /** Runs `operation` while `process.stdin.isTTY` reports `isTTY`. */
55
+ export async function withTTY(isTTY, operation) {
56
+ const previous = Object.getOwnPropertyDescriptor(process.stdin, 'isTTY');
57
+ Object.defineProperty(process.stdin, 'isTTY', { configurable: true, value: isTTY });
58
+ try {
59
+ return await operation();
60
+ }
61
+ finally {
62
+ if (previous)
63
+ Object.defineProperty(process.stdin, 'isTTY', previous);
64
+ else
65
+ Reflect.deleteProperty(process.stdin, 'isTTY');
66
+ }
67
+ }
@@ -0,0 +1,122 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+ import { spawn } from 'node:child_process';
3
+ import { constants } from 'node:os';
4
+ import process from 'node:process';
5
+ const operationSignal = new AsyncLocalStorage();
6
+ export async function withOperationSignal(signal, operation) {
7
+ return operationSignal.run(signal, operation);
8
+ }
9
+ export async function withoutOperationSignal(operation) {
10
+ return operationSignal.exit(operation);
11
+ }
12
+ export function currentSignal() {
13
+ return operationSignal.getStore();
14
+ }
15
+ export function checkInterrupted() {
16
+ operationSignal.getStore()?.throwIfAborted();
17
+ }
18
+ export class ProcessFailure extends Error {
19
+ exitCode;
20
+ constructor(command, operation, code, signal, stderr) {
21
+ super(`${command} ${operation} failed (${signal ?? code})${stderr
22
+ ? `: ${stderr}`
23
+ : ''}`);
24
+ this.exitCode = signal
25
+ ? 128 + constants.signals[signal]
26
+ : code ?? 1;
27
+ }
28
+ }
29
+ export async function run(command, args, cwd, options = {}) {
30
+ const { env = process.env, inherit = false, onOutput, timeout } = options;
31
+ const signal = operationSignal.getStore();
32
+ signal?.throwIfAborted();
33
+ return new Promise((resolve, reject) => {
34
+ const child = spawn(command, args, {
35
+ cwd,
36
+ env,
37
+ detached: !inherit,
38
+ stdio: inherit
39
+ ? 'inherit'
40
+ : ['ignore', 'pipe', 'pipe'],
41
+ });
42
+ let stdout = '';
43
+ let stderr = '';
44
+ let drain;
45
+ let timedOut = false;
46
+ const { stop, cancel: cancelKill } = processStopper(child, inherit);
47
+ const abort = () => {
48
+ const reason = signal?.reason;
49
+ // An inherited terminal delivers SIGINT directly to the foreground group.
50
+ if (!inherit || !process.stdin.isTTY || reason?.signal !== 'SIGINT')
51
+ stop(reason?.signal ?? 'SIGTERM');
52
+ };
53
+ const deadline = timeout === undefined
54
+ ? undefined
55
+ : setTimeout(() => {
56
+ timedOut = true;
57
+ stop('SIGTERM');
58
+ }, timeout);
59
+ signal?.addEventListener('abort', abort, { once: true });
60
+ const cleanup = () => {
61
+ signal?.removeEventListener('abort', abort);
62
+ clearTimeout(deadline);
63
+ cancelKill();
64
+ clearTimeout(drain);
65
+ };
66
+ child.stdout?.setEncoding('utf8').on('data', (chunk) => {
67
+ stdout += chunk;
68
+ onOutput?.(chunk, 'stdout');
69
+ });
70
+ child.stderr?.setEncoding('utf8').on('data', (chunk) => {
71
+ stderr += chunk;
72
+ onOutput?.(chunk, 'stderr');
73
+ });
74
+ child.once('exit', () => {
75
+ // Background jobs can inherit these pipes after the command itself exits.
76
+ if (!inherit) {
77
+ drain = setTimeout(() => {
78
+ child.stdout?.destroy();
79
+ child.stderr?.destroy();
80
+ }, 100);
81
+ }
82
+ });
83
+ child.once('error', (error) => {
84
+ cleanup();
85
+ reject(error);
86
+ });
87
+ child.once('close', (code, killedBy) => {
88
+ cleanup();
89
+ if (signal?.aborted)
90
+ reject(signal.reason);
91
+ else if (timedOut)
92
+ reject(new Error(`${command} ${args[0] ?? ''} timed out after ${timeout} ms.`));
93
+ else if (code === 0)
94
+ resolve(stdout.trim());
95
+ else
96
+ reject(new ProcessFailure(command, args[0] ?? '', code, killedBy, stderr.trim()));
97
+ });
98
+ });
99
+ }
100
+ function processStopper(child, inherit) {
101
+ let killTimer;
102
+ const kill = (reason) => {
103
+ if (child.pid === undefined)
104
+ return;
105
+ try {
106
+ process.kill(inherit
107
+ ? child.pid
108
+ : -child.pid, reason);
109
+ }
110
+ catch (error) {
111
+ if (error.code !== 'ESRCH')
112
+ throw error;
113
+ }
114
+ };
115
+ return {
116
+ stop: (reason) => {
117
+ kill(reason);
118
+ killTimer ??= setTimeout(kill, 3000, 'SIGKILL');
119
+ },
120
+ cancel: () => clearTimeout(killTimer),
121
+ };
122
+ }
@@ -0,0 +1,28 @@
1
+ import { checkInterrupted } from './process.js';
2
+ export async function runStep(progress, label, operation) {
3
+ checkInterrupted();
4
+ progress?.({ label, status: 'started' });
5
+ try {
6
+ const result = await operation();
7
+ checkInterrupted();
8
+ progress?.({ label, status: 'completed' });
9
+ return result;
10
+ }
11
+ catch (error) {
12
+ progress?.({ label, status: 'failed' });
13
+ throw error;
14
+ }
15
+ }
16
+ export function hookLabel(name, hook, scope) {
17
+ const detail = typeof hook === 'string'
18
+ ? hook
19
+ : 'inline script';
20
+ return `Running ${scope === undefined
21
+ ? ''
22
+ : `${scope} `}${name} hook (${detail})`;
23
+ }
24
+ export function outputReporter(progress, label) {
25
+ if (progress === undefined)
26
+ return undefined;
27
+ return (text, stream) => progress({ label, status: 'log', text, stream });
28
+ }
@@ -0,0 +1,14 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { rename, unlink, writeFile } from 'node:fs/promises';
3
+ import { dirname, join } from 'node:path';
4
+ export async function writeAtomicFile(path, contents) {
5
+ const staging = join(dirname(path), `.wt-${randomUUID()}.tmp`);
6
+ try {
7
+ await writeFile(staging, contents, { mode: 0o600, flag: 'wx' });
8
+ await rename(staging, path);
9
+ }
10
+ catch (error) {
11
+ await unlink(staging).catch(() => undefined);
12
+ throw error;
13
+ }
14
+ }