@joberthel/worktree 1.4.0 → 1.5.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.
@@ -4,9 +4,10 @@ import { basename, isAbsolute, join, relative, resolve, sep } from 'node:path';
4
4
  import process from 'node:process';
5
5
  import { WtError } from '../errors.js';
6
6
  import { repositoryInfo } from '../git/repository.js';
7
- import { run } from '../operations/process.js';
7
+ import { checkInterrupted, run } from '../operations/process.js';
8
8
  import { writeAtomicFile } from '../state/atomic-file.js';
9
9
  import { StateStore } from '../state/store.js';
10
+ import { withPausedContainers } from './pause.js';
10
11
  export async function docker(args, cwd, { project, timeout } = {}) {
11
12
  return run('docker', args, cwd, {
12
13
  env: project !== undefined
@@ -152,9 +153,21 @@ export async function prepareVolumeCopy(cwd) {
152
153
  }
153
154
  return image;
154
155
  }
155
- export async function cloneNamedVolumes(sources, owner, cwd, image, onVolume) {
156
+ /** How many volumes are copied at the same time. */
157
+ const volumeCopyConcurrency = 3;
158
+ /**
159
+ * Clones the source volumes into new volumes of `owner` and returns them by
160
+ * logical name in the order of `sources`. Each new volume is passed to
161
+ * `onVolume` before it is created, one call at a time, so cleanup finds it
162
+ * after a failure. The volumes are created one after the other and then
163
+ * copied `volumeCopyConcurrency` at a time. With `pauseSource`, the
164
+ * containers that use the source volumes are paused before the first copy
165
+ * and unpaused once the last one has settled.
166
+ */
167
+ export async function cloneNamedVolumes(sources, owner, cwd, { image, pauseSource }, onVolume) {
156
168
  const { repositoryId: repoId, name } = owner;
157
169
  const mapping = new Map();
170
+ const copies = [];
158
171
  for (const [logicalName, source] of Object.entries(sources)) {
159
172
  const target = `wt-${repoId}-${worktreeResourceName(name)}-${randomUUID()}`;
160
173
  mapping.set(logicalName, target);
@@ -185,9 +198,16 @@ export async function cloneNamedVolumes(sources, owner, cwd, image, onVolume) {
185
198
  const targetLabels = JSON.parse(targetLabelsRaw || 'null');
186
199
  if (targetLabels?.['com.wt.repository'] !== repoId || targetLabels['com.wt.worktree'] !== name)
187
200
  throw new Error(`Refusing to clone data into volume ${target}: ownership labels do not match this repository and worktree.`);
201
+ copies.push({ source, target, sourceBefore });
202
+ }
203
+ const copyAll = async () => forEachLimited(copies, volumeCopyConcurrency, async ({ source, target, sourceBefore }) => {
188
204
  await docker([
189
205
  'run',
190
206
  '--rm',
207
+ // As PID 1, bash would ignore an interrupt; docker-init passes it on to the whole copy.
208
+ '--init',
209
+ '-e',
210
+ 'TINI_KILL_PROCESS_GROUP=1',
191
211
  '-v',
192
212
  `${source}:/src:ro`,
193
213
  '-v',
@@ -204,11 +224,40 @@ export async function cloneNamedVolumes(sources, owner, cwd, image, onVolume) {
204
224
  '{{json .}}',
205
225
  source,
206
226
  ], cwd);
227
+ // This metadata changes when the volume is removed or recreated, but not when data is written to it.
207
228
  if (sourceBefore !== sourceAfter)
208
- throw new Error(`Source volume ${source} changed during the copy. Retry once it is stable.`);
209
- }
229
+ throw new Error(`Source volume ${source} was removed or recreated while it was being cloned. Retry once the source project is stable.`);
230
+ });
231
+ await (pauseSource
232
+ ? withPausedContainers(Object.values(sources), cwd, copyAll)
233
+ : copyAll());
210
234
  return Object.fromEntries(mapping);
211
235
  }
236
+ /**
237
+ * Runs `task` for each item, at most `limit` at a time. After a task fails or
238
+ * the operation is interrupted, it starts no further tasks, waits for the
239
+ * running ones to settle, and throws the first error.
240
+ */
241
+ async function forEachLimited(items, limit, task) {
242
+ const errors = [];
243
+ const workers = Math.min(limit, items.length);
244
+ let next = 0;
245
+ const worker = async () => {
246
+ while (errors.length === 0 && next < items.length) {
247
+ const item = items[next++];
248
+ try {
249
+ checkInterrupted();
250
+ await task(item);
251
+ }
252
+ catch (error) {
253
+ errors.push(error);
254
+ }
255
+ }
256
+ };
257
+ await Promise.all(Array.from({ length: workers }, worker));
258
+ if (errors.length > 0)
259
+ throw errors[0];
260
+ }
212
261
  export function composeArgs(files, override, project, worktree, args) {
213
262
  return [
214
263
  'compose',
@@ -0,0 +1,36 @@
1
+ import { checkInterrupted, run, withoutOperationSignal } from '../operations/process.js';
2
+ /**
3
+ * Pauses the running containers that mount any of `volumes`, runs `work`, and
4
+ * unpauses them again, also when `work` fails or the operation is
5
+ * interrupted. Containers that do not run, such as ones that are paused
6
+ * already, are left alone.
7
+ */
8
+ export async function withPausedContainers(volumes, cwd, work) {
9
+ // Without a volume filter, docker ps would list every running container.
10
+ if (volumes.length === 0)
11
+ return work();
12
+ // Docker ORs the volume filters and ANDs them with the status filter.
13
+ const running = await run('docker', [
14
+ 'ps',
15
+ '--quiet',
16
+ '--no-trunc',
17
+ '--filter',
18
+ 'status=running',
19
+ ...volumes.flatMap(volume => ['--filter', `volume=${volume}`]),
20
+ ], cwd);
21
+ const paused = [];
22
+ try {
23
+ for (const container of running.split('\n').filter(Boolean)) {
24
+ checkInterrupted();
25
+ // An interrupt lets the pause finish, so the container is unpaused exactly when it was paused.
26
+ await withoutOperationSignal(async () => run('docker', ['pause', container], cwd));
27
+ paused.push(container);
28
+ }
29
+ return await work();
30
+ }
31
+ finally {
32
+ // run() refuses to start a command once the operation is interrupted.
33
+ if (paused.length > 0)
34
+ await withoutOperationSignal(async () => run('docker', ['unpause', ...paused], cwd));
35
+ }
36
+ }
package/dist/errors.js CHANGED
@@ -24,13 +24,15 @@ export const errorCodes = [
24
24
  'not_ready',
25
25
  /** `wt create` made the worktree but its setup failed; run `wt reset` or `wt rm`. */
26
26
  'setup_failed',
27
- /** `wt rm` or `wt reset` needs `--force` without a terminal. */
27
+ /** `wt rm`, `wt reset` or `wt unlock` needs `--force` without a terminal. */
28
28
  'confirmation_required',
29
29
  /** The current directory is inside the worktree that would be removed. */
30
30
  'inside_worktree',
31
31
  /** Another wt command holds the lock of the worktree, its source, or the repository. */
32
32
  'locked',
33
- /** The worktree changed while the command waited; retry it. */
33
+ /** `wt unlock` found no lock to remove. */
34
+ 'not_locked',
35
+ /** The worktree or its lock changed while the command waited; retry it. */
34
36
  'changed',
35
37
  /** No single running Compose project belongs to the source checkout. */
36
38
  'no_compose_project',
@@ -1,9 +1,12 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
1
2
  import { realpath } from 'node:fs/promises';
2
3
  import { dirname, isAbsolute, resolve } from 'node:path';
3
4
  import process from 'node:process';
4
5
  import { WtError } from '../errors.js';
5
6
  import { checkInterrupted, run } from '../operations/process.js';
6
7
  import { StateStore } from '../state/store.js';
8
+ /** Lookups of repositoryInfo by directory, kept while withRepositoryCache runs. */
9
+ const repositoryCache = new AsyncLocalStorage();
7
10
  const gitLocalVariables = [
8
11
  'GIT_ALTERNATE_OBJECT_DIRECTORIES',
9
12
  'GIT_CONFIG',
@@ -29,9 +32,16 @@ export function gitEnvironment() {
29
32
  return env;
30
33
  }
31
34
  export async function git(args, cwd) {
32
- return run('git', args, cwd, {
33
- env: gitEnvironment(),
34
- });
35
+ try {
36
+ return await run('git', args, cwd, {
37
+ env: gitEnvironment(),
38
+ });
39
+ }
40
+ finally {
41
+ // Lookups from before a worktree was added or removed may be out of date.
42
+ if (args[0] === 'worktree' && args[1] !== 'list')
43
+ repositoryCache.getStore()?.clear();
44
+ }
35
45
  }
36
46
  /** Local branches and remote-tracking branches, without the `<remote>/HEAD` aliases. */
37
47
  export async function listBranches(cwd) {
@@ -45,7 +55,34 @@ export async function listBranches(cwd) {
45
55
  .filter(ref => ref !== '' && !ref.endsWith('/HEAD'))
46
56
  .map(ref => ref.replace(/^refs\/(?:heads|remotes)\//, ''));
47
57
  }
58
+ /**
59
+ * Runs `operation` with its own cache of repositoryInfo, so that a command
60
+ * asks Git about each directory once. Git commands that add or remove
61
+ * worktrees clear the cache.
62
+ */
63
+ export async function withRepositoryCache(operation) {
64
+ return repositoryCache.run(new Map(), operation);
65
+ }
66
+ /**
67
+ * The checkout that contains `cwd`, the Git directory its worktrees share,
68
+ * and the main checkout. Inside withRepositoryCache, callers share one
69
+ * lookup per directory; a failed lookup is not kept.
70
+ */
48
71
  export async function repositoryInfo(cwd) {
72
+ const cache = repositoryCache.getStore();
73
+ if (cache === undefined)
74
+ return locateRepository(cwd);
75
+ let lookup = cache.get(cwd);
76
+ if (lookup === undefined) {
77
+ lookup = locateRepository(cwd).catch((error) => {
78
+ cache.delete(cwd);
79
+ throw error;
80
+ });
81
+ cache.set(cwd, lookup);
82
+ }
83
+ return lookup;
84
+ }
85
+ async function locateRepository(cwd) {
49
86
  const common = await git(['rev-parse', '--git-common-dir'], cwd).catch((error) => {
50
87
  if (error instanceof Error && /not a git repository/i.test(error.message))
51
88
  throw new WtError('not_a_repository', 'Run wt from a Git checkout or its repository directory.', { cause: error });
package/dist/help.js ADDED
@@ -0,0 +1,111 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { commandOptions, commands, printsScript } from './cli-spec.js';
3
+ /*
4
+ * Help for people and, with `--format json`, for scripts and coding agents.
5
+ * Both are read from the command table in cli-spec.ts.
6
+ */
7
+ const description = 'Manage isolated Git worktrees with Docker Compose.';
8
+ const workingDirOption = {
9
+ name: '--working-dir',
10
+ alias: '-w',
11
+ value: '<dir>',
12
+ description: 'Run as if wt was started in <dir>',
13
+ repeatable: false,
14
+ };
15
+ const formatOption = {
16
+ name: '--format',
17
+ alias: null,
18
+ value: '<text|json>',
19
+ description: 'Output format (default: text, or WT_FORMAT)',
20
+ repeatable: false,
21
+ };
22
+ /** The commands without JSON output, as help names them. */
23
+ const textOnlyCommands = new Intl.ListFormat('en').format(Object.entries(commands).filter(([, spec]) => !spec.shared).map(([name]) => name));
24
+ function optionHelp(command) {
25
+ return [
26
+ ...commandOptions(command).map(([name, { type, value, description }]) => ({
27
+ name: `--${name}`,
28
+ alias: null,
29
+ value: value ?? null,
30
+ description,
31
+ repeatable: type === 'strings',
32
+ })),
33
+ ...(printsScript(command)
34
+ ? []
35
+ : [workingDirOption]),
36
+ ...(commands[command].shared
37
+ ? [formatOption]
38
+ : []),
39
+ ];
40
+ }
41
+ function optionFlags({ name, alias, value }) {
42
+ return `${alias === null
43
+ ? ''
44
+ : `${alias}, `}${name}${value === null
45
+ ? ''
46
+ : ` ${value}`}`;
47
+ }
48
+ function commandUsage(command) {
49
+ return `wt ${command} ${commands[command].usage}`.trimEnd();
50
+ }
51
+ export function usage(command) {
52
+ if (command !== undefined) {
53
+ const options = optionHelp(command).map(option => [
54
+ optionFlags(option),
55
+ option.description,
56
+ ]);
57
+ const width = Math.max(...options.map(([flags]) => flags.length));
58
+ const optionList = options.length
59
+ ? `\n\nOptions:\n${options.map(([flags, text]) => ` ${flags.padEnd(width)} ${text}`).join('\n')}`
60
+ : '';
61
+ return `Usage: ${commandUsage(command)}\n\n${commands[command].summary}${optionList}`;
62
+ }
63
+ const width = Math.max(...Object.keys(commands).map(name => name.length));
64
+ const list = Object.entries(commands).map(([name, spec]) => ` ${name.padEnd(width)} ${spec.usage.padEnd(43)} ${spec.summary}`).join('\n');
65
+ return `${description}\n\nUsage: wt [-w <dir>] <command>\n\n${list}\n\n -w, --working-dir <dir> Run as if wt was started in <dir>\n --format <text|json> Output format, for all commands except ${textOnlyCommands}\n -h, --help Show help\n -v, --version Show the version`;
66
+ }
67
+ function commandHelpJson(command) {
68
+ return {
69
+ name: command,
70
+ usage: commandUsage(command),
71
+ summary: commands[command].summary,
72
+ options: optionHelp(command),
73
+ formats: commands[command].shared
74
+ ? ['text', 'json']
75
+ : ['text'],
76
+ };
77
+ }
78
+ /** `--help --format json`: the commands and options, read from the same table as the text help. */
79
+ export function helpJson(command) {
80
+ if (command !== undefined)
81
+ return commandHelpJson(command);
82
+ return {
83
+ name: 'wt',
84
+ description,
85
+ version: version(),
86
+ usage: 'wt [-w <dir>] <command>',
87
+ commands: Object.keys(commands).map(name => commandHelpJson(name)),
88
+ options: [
89
+ workingDirOption,
90
+ { ...formatOption, description: `Output format, for all commands except ${textOnlyCommands} (default: text, or WT_FORMAT)` },
91
+ {
92
+ name: '--help',
93
+ alias: '-h',
94
+ value: null,
95
+ description: 'Show help',
96
+ repeatable: false,
97
+ },
98
+ {
99
+ name: '--version',
100
+ alias: '-v',
101
+ value: null,
102
+ description: 'Show the version',
103
+ repeatable: false,
104
+ },
105
+ ],
106
+ };
107
+ }
108
+ export function version() {
109
+ const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
110
+ return pkg.version;
111
+ }
@@ -7,6 +7,7 @@ import { AttachedStore, StateStore } from '../state/store.js';
7
7
  import { attachedHost, createAttached, removeAttached, resetAttached } from './attached.js';
8
8
  import { createManagedEnvironment, withCreateContext } from './create.js';
9
9
  import * as manage from './manage.js';
10
+ export { unlockEnvironment } from './unlock.js';
10
11
  /*
11
12
  * Entry points of the CLI. A name refers to an environment of the current
12
13
  * repository or to a worktree attached to an environment of a host
@@ -49,12 +50,13 @@ export async function listEnvironments(cwd) {
49
50
  }));
50
51
  }
51
52
  async function listedEnvironments(cwd) {
52
- const own = await manage.listEnvironments(cwd);
53
53
  const { gitCommonDir } = await repositoryInfo(cwd);
54
54
  const states = await new AttachedStore(gitCommonDir).list();
55
55
  if (states.length === 0)
56
- return own;
56
+ return manage.listEnvironments(cwd);
57
+ // One docker ps serves the own and the attached worktrees.
57
58
  const dockerStatus = await manage.dockerStatuses(cwd);
59
+ const own = await manage.listEnvironments(cwd, dockerStatus);
58
60
  const rows = await Promise.all(states.map(async (state) => {
59
61
  const host = await attachedHost(state);
60
62
  return {
@@ -92,6 +94,15 @@ export async function listEnvironmentNames(cwd) {
92
94
  .map(({ name, branch }) => ({ name, branch }))
93
95
  .sort((a, b) => a.name.localeCompare(b.name));
94
96
  }
97
+ /**
98
+ * The path of an environment's worktree, read from the state files only. It
99
+ * never asks Docker, so `wt path` and `wt cd` stay fast.
100
+ */
101
+ export async function environmentPath(name, cwd) {
102
+ const { gitCommonDir } = await repositoryInfo(cwd);
103
+ const state = await new AttachedStore(gitCommonDir).find(name) ?? await new StateStore(gitCommonDir).get(name);
104
+ return state.path;
105
+ }
95
106
  /**
96
107
  * Names of the environments whose Compose services run. It asks Docker once
97
108
  * and gives up after `timeout` milliseconds, so it suits shell completion.
@@ -25,3 +25,14 @@ export function formatDryRun(request) {
25
25
  'Dry run: nothing was changed.',
26
26
  ].join('\n');
27
27
  }
28
+ /** Runs an operation up to its confirmation, declines it, and returns what it asked. */
29
+ export async function preview(operation) {
30
+ let request;
31
+ await operation(async (asked) => {
32
+ request = asked;
33
+ return false;
34
+ });
35
+ if (request === undefined)
36
+ throw new Error('The operation finished without asking for confirmation.');
37
+ return request;
38
+ }
@@ -9,7 +9,7 @@ import { copyConfiguredPaths } from './copy-paths.js';
9
9
  import { startWithHooks, validateSourceHooks, validateWorktreeHooks } from './hooks.js';
10
10
  import { sourceLock, withLocks, worktreeLock } from './locks.js';
11
11
  import { checkInterrupted, withoutOperationSignal } from './process.js';
12
- import { runStep } from './progress.js';
12
+ import { cloneLabel, runStep } from './progress.js';
13
13
  const namePattern = /^\w[\w.-]*(?:\/\w[\w.-]*)*$/;
14
14
  export function validateCreateInput(name, options) {
15
15
  if (!namePattern.test(name))
@@ -100,7 +100,8 @@ async function createLocked(name, options, { root, gitCommonDir, repositoryRoot
100
100
  await nested?.checkedOut(target);
101
101
  const targetComposeFiles = await composeFilesForWorktree(source.files, source.workingDir, target);
102
102
  await validateWorktreeHooks(config.hooks, target);
103
- created.volumes = await runStep(progress, 'Cloning named Docker volumes (live writes may cause inconsistent data)', async () => cloneNamedVolumes(sources, created, root, image, async (_volume, volumes) => {
103
+ const { pause_source: pauseSource } = config.volumes;
104
+ created.volumes = await runStep(progress, cloneLabel('Cloning named Docker volumes', pauseSource), async () => cloneNamedVolumes(sources, created, root, { image, pauseSource }, async (_volume, volumes) => {
104
105
  created.volumes = volumes;
105
106
  await store.save(created);
106
107
  }));
@@ -3,6 +3,7 @@ import { access, realpath, unlink } from 'node:fs/promises';
3
3
  import { isAbsolute, relative, resolve, sep } from 'node:path';
4
4
  import process from 'node:process';
5
5
  import { createInterface } from 'node:readline/promises';
6
+ import { isDeepStrictEqual } from 'node:util';
6
7
  import { configPath, loadConfig } from '../config/load.js';
7
8
  import { cloneNamedVolumes, composeFilesForWorktree, docker, prepareVolumeCopy, resolveSourceVolumes, runCompose, writeVolumeOverride } from '../docker/compose.js';
8
9
  import { containerAddresses, domainsLabel, orbstackNetwork, parseDomains } from '../docker/orbstack.js';
@@ -15,7 +16,7 @@ import { copyConfiguredPaths } from './copy-paths.js';
15
16
  import { startWithHooks, validateSourceHooks, validateWorktreeHooks } from './hooks.js';
16
17
  import { sourceLock, withLocks, worktreeLock } from './locks.js';
17
18
  import { checkInterrupted, currentSignal } from './process.js';
18
- import { outputReporter, runStep } from './progress.js';
19
+ import { cloneLabel, outputReporter, runStep } from './progress.js';
19
20
  async function context(cwd) {
20
21
  const info = await repositoryInfo(cwd);
21
22
  return {
@@ -70,15 +71,20 @@ async function removeClonedVolumes(state, cwd, keep = []) {
70
71
  for (const volume of volumes)
71
72
  await removeOwnedVolume(volume, state.repositoryId, state.name, cwd);
72
73
  }
73
- export async function listEnvironments(cwd) {
74
+ /**
75
+ * Lists the managed environments with the status of their Compose project.
76
+ * It asks Docker only when there are environments and no `dockerStatus`
77
+ * lookup is given.
78
+ */
79
+ export async function listEnvironments(cwd, dockerStatus) {
74
80
  const { store } = await context(cwd);
75
81
  const states = await store.list();
76
82
  if (states.length === 0)
77
83
  return [];
78
- const dockerStatus = await dockerStatuses(cwd);
84
+ const status = dockerStatus ?? await dockerStatuses(cwd);
79
85
  return states.map(state => ({
80
86
  ...state,
81
- dockerStatus: dockerStatus(state.projectName),
87
+ dockerStatus: status(state.projectName),
82
88
  }));
83
89
  }
84
90
  /** Reads all Compose containers once and returns a summary lookup by project name. */
@@ -354,7 +360,7 @@ export async function resetLocked(state, store, config, cwd, { progress, nested
354
360
  : '';
355
361
  await store.save({ ...current, status: 'resetting' });
356
362
  try {
357
- const volumes = await runStep(progress, 'Cloning fresh Docker volumes', async () => cloneNamedVolumes(sources, state, sourceRoot, image, async (volume) => {
363
+ const volumes = await runStep(progress, cloneLabel('Cloning fresh Docker volumes', config.volumes.pause_source), async () => cloneNamedVolumes(sources, state, sourceRoot, { image, pauseSource: config.volumes.pause_source }, async (volume) => {
358
364
  current.retiredVolumes.push(volume);
359
365
  await store.save({ ...current, status: 'resetting' });
360
366
  }));
@@ -402,8 +408,14 @@ export async function exists(path) {
402
408
  throw error;
403
409
  }
404
410
  }
411
+ /**
412
+ * Throws `changed` when the saved state differs from `state`, which was read
413
+ * before the command waited for its locks. Key order does not matter, and a
414
+ * property set to `undefined` counts as absent, as `save` leaves it out.
415
+ */
405
416
  export async function checkUnchanged(store, state) {
406
- if (JSON.stringify(await store.get(state.name)) !== JSON.stringify(state))
417
+ const asSaved = (value) => JSON.parse(JSON.stringify(value));
418
+ if (!isDeepStrictEqual(asSaved(await store.get(state.name)), asSaved(state)))
407
419
  throw new WtError('changed', `Worktree ${state.name} changed while waiting. Retry the command.`);
408
420
  }
409
421
  async function downEnvironment(state, cwd, removeImages) {
@@ -1,4 +1,25 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+ import process from 'node:process';
1
3
  import { checkInterrupted } from './process.js';
4
+ const operationProgress = new AsyncLocalStorage();
5
+ /** Runs `operation` with `progress` as the reporter of its notes. */
6
+ export async function withProgress(progress, operation) {
7
+ return operationProgress.run(progress, operation);
8
+ }
9
+ /**
10
+ * Shows a note as a finished step of the current operation, for code that is
11
+ * not passed a reporter, such as the lock store. Outside an operation the
12
+ * note goes to stderr.
13
+ */
14
+ export function reportNote(label) {
15
+ const progress = operationProgress.getStore();
16
+ if (progress === undefined) {
17
+ process.stderr.write(`${label}\n`);
18
+ return;
19
+ }
20
+ progress({ label, status: 'started' });
21
+ progress({ label, status: 'completed' });
22
+ }
2
23
  export async function runStep(progress, label, operation) {
3
24
  checkInterrupted();
4
25
  progress?.({ label, status: 'started' });
@@ -21,6 +42,12 @@ export function hookLabel(name, hook, scope) {
21
42
  ? ''
22
43
  : `${scope} `}${name} hook (${detail})`;
23
44
  }
45
+ /** Label of a step that clones volumes, with whether the source containers can write meanwhile. */
46
+ export function cloneLabel(step, pauseSource) {
47
+ return `${step} (${pauseSource
48
+ ? 'source containers paused'
49
+ : 'live writes may cause inconsistent data'})`;
50
+ }
24
51
  export function outputReporter(progress, label) {
25
52
  if (progress === undefined)
26
53
  return undefined;
@@ -0,0 +1,111 @@
1
+ import process from 'node:process';
2
+ import { WtError } from '../errors.js';
3
+ import { repositoryInfo } from '../git/repository.js';
4
+ import { describeOwner, removeLock } from '../state/lock-file.js';
5
+ import { AttachedStore, StateStore } from '../state/store.js';
6
+ import { requestConfirmation } from './manage.js';
7
+ /**
8
+ * The locks that commands on worktree `name` take, or the repository locks
9
+ * when `name` is `undefined`. Commands on a worktree of a nested repository
10
+ * also lock its host worktree in the host repository, so it is found by
11
+ * either name.
12
+ */
13
+ async function heldLocks(name, cwd) {
14
+ const { gitCommonDir } = await repositoryInfo(cwd);
15
+ const store = new StateStore(gitCommonDir);
16
+ const attached = await new AttachedStore(gitCommonDir).list();
17
+ let locks;
18
+ if (name === undefined) {
19
+ const hosts = new Set(attached.map(state => state.host.gitCommonDir));
20
+ locks = [
21
+ store,
22
+ ...[...hosts].map(host => new StateStore(host)),
23
+ ].map(async (repository) => repository.inspectRepositoryLock());
24
+ }
25
+ else {
26
+ const lower = name.toLowerCase();
27
+ const nested = attached.find(state => state.name.toLowerCase() === lower || state.host.name.toLowerCase() === lower);
28
+ locks = nested === undefined
29
+ ? [
30
+ store.inspectWorktreeLock(name),
31
+ ]
32
+ : [
33
+ store.inspectWorktreeLock(nested.name),
34
+ new StateStore(nested.host.gitCommonDir).inspectWorktreeLock(nested.host.name),
35
+ ];
36
+ }
37
+ return (await Promise.all(locks)).filter(held => held !== undefined);
38
+ }
39
+ function statusText(held) {
40
+ if (held.status === 'exited' || held.status === 'replaced')
41
+ return 'No longer runs';
42
+ if (held.owner === undefined)
43
+ return 'Unknown: the lock file does not name its owner';
44
+ return held.owner.host === undefined
45
+ ? 'Unknown: an older wt version took the lock'
46
+ : `Unknown: wt cannot check whether it still runs on ${held.owner.host}`;
47
+ }
48
+ function lockDetails(held) {
49
+ const { owner, takeover } = held;
50
+ const takeoverOwner = takeover?.owner === undefined
51
+ ? ''
52
+ : ` by ${describeOwner(takeover.owner)}`;
53
+ return [
54
+ { label: 'Lock', value: held.path },
55
+ ...(owner === undefined
56
+ ? []
57
+ : [
58
+ {
59
+ label: 'Owner',
60
+ value: describeOwner(owner),
61
+ },
62
+ ]),
63
+ {
64
+ label: 'Status',
65
+ value: statusText(held),
66
+ },
67
+ ...(takeover === undefined
68
+ ? []
69
+ : [
70
+ { label: 'Takeover', value: `${takeover.path}${takeoverOwner}` },
71
+ ]),
72
+ ];
73
+ }
74
+ function unlockRequest(name, locks) {
75
+ const plural = locks.length > 1
76
+ ? 's'
77
+ : '';
78
+ return {
79
+ title: name === undefined
80
+ ? `Remove the repository lock${plural}?`
81
+ : `Remove the lock${plural} of worktree ${name}?`,
82
+ details: locks.flatMap(lockDetails),
83
+ note: 'Remove a lock only when its command no longer runs: two wt commands that change the same worktrees at once can break them.',
84
+ action: 'Remove',
85
+ };
86
+ }
87
+ /**
88
+ * Removes the lock of worktree `name`, or the repository lock when `name` is
89
+ * `undefined`, that a command left behind when it was killed. Asks first,
90
+ * unless `force` is set, and refuses while the command that holds a lock
91
+ * still runs. Returns whether the locks were removed.
92
+ */
93
+ export async function unlockEnvironment(name, cwd, force = false, confirm) {
94
+ const locks = await heldLocks(name, cwd);
95
+ if (locks.length === 0) {
96
+ throw new WtError('not_locked', name === undefined
97
+ ? 'Worktree operations are not locked.'
98
+ : `Worktree ${name} is not locked.`);
99
+ }
100
+ for (const held of locks.flatMap(lock => [lock, lock.takeover])) {
101
+ if (held?.status === 'running')
102
+ throw new WtError('locked', `The lock at ${held.path} is held by ${describeOwner(held.owner)}, which still runs. Retry when it exits.`);
103
+ }
104
+ if (!force && confirm === undefined && !process.stdin.isTTY)
105
+ throw new WtError('confirmation_required', 'wt unlock requires an interactive terminal or --force. Run it with --dry-run to see what it removes.');
106
+ if (!force && !await requestConfirmation(unlockRequest(name, locks), confirm))
107
+ return false;
108
+ for (const held of locks)
109
+ await removeLock(held);
110
+ return true;
111
+ }
@@ -0,0 +1,46 @@
1
+ /*
2
+ * The shell function behind `wt cd`. A program cannot change the directory of
3
+ * the shell that runs it, so `wt shell-init` prints a function named `wt` for
4
+ * the shell's startup file. It runs `wt cd [name]` as `cd "$(wt path [name])"`
5
+ * and passes every other command to the wt program.
6
+ *
7
+ * It is not part of the completion script, because that script may be
8
+ * installed as a file that the shell only loads when it completes `wt`.
9
+ *
10
+ * The same function works in zsh and bash. It finds the command after any
11
+ * `-w` options, so `wt -w <dir> cd` works too, and passes `wt cd --help` on.
12
+ * It never expands an empty array, which bash 3.2 rejects under `set -u`, and
13
+ * never indexes an array, which zsh's KSH_ARRAYS option changes.
14
+ */
15
+ function shellFunction(shell) {
16
+ return `# wt shell function for ${shell}. Load it with: eval "$(wt shell-init ${shell})"
17
+ # It runs wt cd [name] as cd "$(wt path [name])" and passes everything else to wt.
18
+ wt() {
19
+ local -a prefix
20
+ local arg dir
21
+ prefix=(wt)
22
+ while (( $# )); do
23
+ case $1 in
24
+ -w | --working-dir) (( $# > 1 )) || break; prefix+=("$1" "$2"); shift 2 ;;
25
+ -w?* | --working-dir=*) prefix+=("$1"); shift ;;
26
+ *) break ;;
27
+ esac
28
+ done
29
+ if [[ \${1-} != cd ]]; then
30
+ command "\${prefix[@]}" "$@"
31
+ return
32
+ fi
33
+ shift
34
+ for arg; do
35
+ case $arg in
36
+ -h | --help) command "\${prefix[@]}" cd "$@"; return ;;
37
+ esac
38
+ done
39
+ dir=$(WT_FORMAT=text command "\${prefix[@]}" path "$@") && builtin cd -- "$dir"
40
+ }
41
+ `;
42
+ }
43
+ export const shellInitScripts = {
44
+ zsh: shellFunction('zsh'),
45
+ bash: shellFunction('bash'),
46
+ };