@joberthel/worktree 1.3.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.
@@ -7,8 +7,9 @@ import { git, refExists, repositoryInfo, resolveExistingBranch, resolveWorktreeD
7
7
  import { StateStore } from '../state/store.js';
8
8
  import { copyConfiguredPaths } from './copy-paths.js';
9
9
  import { startWithHooks, validateSourceHooks, validateWorktreeHooks } from './hooks.js';
10
+ import { sourceLock, withLocks, worktreeLock } from './locks.js';
10
11
  import { checkInterrupted, withoutOperationSignal } from './process.js';
11
- import { runStep } from './progress.js';
12
+ import { cloneLabel, runStep } from './progress.js';
12
13
  const namePattern = /^\w[\w.-]*(?:\/\w[\w.-]*)*$/;
13
14
  export function validateCreateInput(name, options) {
14
15
  if (!namePattern.test(name))
@@ -19,23 +20,16 @@ export function validateCreateInput(name, options) {
19
20
  throw new UsageError('--branch and --from cannot be used together.');
20
21
  }
21
22
  export async function createEnvironment(name, options, cwd, progress) {
22
- return withCreateContext(name, options, cwd, progress, async (repository, store, loaded) => createEnvironmentLocked(name, options, repository, store, { ...loaded, progress }));
23
+ return withCreateContext(name, options, cwd, progress, async (repository, store, loaded) => createManagedEnvironment(name, options, repository, store, { ...loaded, progress }));
23
24
  }
24
25
  /**
25
- * Validates the input, locks the repository that contains `cwd`, loads its
26
- * configuration, and runs `create` while the lock is held.
26
+ * Validates the input, locates the repository that contains `cwd`, loads its
27
+ * configuration, and runs `create` with them.
27
28
  */
28
29
  export async function withCreateContext(name, options, cwd, progress, create) {
29
30
  validateCreateInput(name, options);
30
31
  const repository = await runStep(progress, 'Locating Git repository', async () => repositoryInfo(cwd));
31
- const store = new StateStore(repository.gitCommonDir);
32
- const unlock = await store.lock('repository');
33
- try {
34
- return await create(repository, store, await loadCreateConfig(repository, progress));
35
- }
36
- finally {
37
- await unlock();
38
- }
32
+ return create(repository, new StateStore(repository.gitCommonDir), await loadCreateConfig(repository, progress));
39
33
  }
40
34
  export async function loadCreateConfig({ root, repositoryRoot }, progress) {
41
35
  const configurationPath = (await configPath(root, repositoryRoot)) ?? null;
@@ -45,73 +39,84 @@ export async function loadCreateConfig({ root, repositoryRoot }, progress) {
45
39
  return { config, configurationPath };
46
40
  }
47
41
  /**
48
- * Creates the worktree and its Docker environment while the repository lock
49
- * is held. A detached environment checks out `options.from` without creating
50
- * a branch. A nested checkout is added inside it before its hooks run.
42
+ * Creates the worktree and its Docker environment. It locks the new worktree
43
+ * and a managed source worktree for the whole setup, and the repository only
44
+ * while it checks the target and registers the worktree, so commands on other
45
+ * worktrees can run meanwhile. A detached environment checks out
46
+ * `options.from` without creating a branch. A nested checkout is added
47
+ * inside it before its hooks run.
51
48
  */
52
- export async function createEnvironmentLocked(name, options, { root, gitCommonDir, repositoryRoot }, store, { config, configurationPath, nested, progress }) {
53
- const source = await runStep(progress, 'Inspecting running Docker Compose project', async () => discoverComposeSource(root));
49
+ export async function createManagedEnvironment(name, options, repository, store, settings) {
50
+ const { root } = repository;
51
+ const source = await runStep(settings.progress, 'Inspecting running Docker Compose project', async () => discoverComposeSource(root));
52
+ return withLocks([
53
+ worktreeLock(store, name),
54
+ sourceLock(store, source.project, name),
55
+ ], async () => createLocked(name, options, repository, store, { ...settings, source }));
56
+ }
57
+ async function createLocked(name, options, { root, gitCommonDir, repositoryRoot }, store, { config, configurationPath, nested, progress, source }) {
54
58
  const { directory, target, repoId, projectName } = await planTarget(name, config, gitCommonDir, repositoryRoot);
55
- await validateTarget(gitCommonDir, target, name, projectName, await store.list());
56
59
  for (const path of config.copy)
57
60
  await access(resolve(root, path));
58
61
  await validateSourceHooks(config.hooks, root);
59
- const { branch, revision, args: add } = await worktreeAdd(name, options, root, target, progress);
60
- const attachment = await nested?.planned(target);
61
- await validateHookRevision(config, root, revision);
62
62
  const sources = await resolveSourceVolumes(source.project, root, source.files, source.sourceVolumes);
63
63
  const image = Object.keys(sources).length
64
64
  ? await prepareVolumeCopy(root)
65
65
  : '';
66
- await mkdir(directory, { recursive: true });
67
- const state = {
68
- schemaVersion: 1,
69
- repositoryId: repoId,
70
- repositoryRoot,
71
- name,
72
- path: target,
73
- branch,
74
- sourceWorktreePath: root,
75
- sourceProject: source.project,
76
- configurationPath,
77
- composeFiles: source.files,
78
- overridePath: overridePath(gitCommonDir, name),
79
- projectName,
80
- volumes: {},
81
- attachment,
82
- status: 'creating',
83
- };
66
+ let state;
84
67
  let worktreeMade = false;
85
68
  try {
86
- await runStep(progress, `Creating Git worktree ${name}`, async () => git(add, root));
87
- worktreeMade = true;
88
- await store.save(state);
69
+ const created = await store.withRepositoryLock(async () => {
70
+ await validateTarget(gitCommonDir, target, name, projectName, await store.list());
71
+ const { branch, revision, args: add } = await worktreeAdd(name, options, root, target, progress);
72
+ await validateHookRevision(config, root, revision);
73
+ const attachment = await nested?.planned(target);
74
+ await mkdir(directory, { recursive: true });
75
+ state = {
76
+ schemaVersion: 1,
77
+ repositoryId: repoId,
78
+ repositoryRoot,
79
+ name,
80
+ path: target,
81
+ branch,
82
+ sourceWorktreePath: root,
83
+ sourceProject: source.project,
84
+ configurationPath,
85
+ composeFiles: source.files,
86
+ overridePath: overridePath(gitCommonDir, name),
87
+ projectName,
88
+ volumes: {},
89
+ attachment,
90
+ status: 'creating',
91
+ };
92
+ const planned = state;
93
+ await runStep(progress, `Creating Git worktree ${name}`, async () => git(add, root));
94
+ worktreeMade = true;
95
+ await store.save(planned);
96
+ return planned;
97
+ });
89
98
  if (config.copy.length > 0)
90
99
  await runStep(progress, 'Copying configured files', async () => copyConfiguredPaths(root, target, config.copy));
91
100
  await nested?.checkedOut(target);
92
101
  const targetComposeFiles = await composeFilesForWorktree(source.files, source.workingDir, target);
93
102
  await validateWorktreeHooks(config.hooks, target);
94
- state.volumes = await runStep(progress, 'Cloning named Docker volumes (live writes may cause inconsistent data)', async () => cloneNamedVolumes(sources, state, root, image, async (_volume, volumes) => {
95
- state.volumes = volumes;
96
- await store.save(state);
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) => {
105
+ created.volumes = volumes;
106
+ await store.save(created);
97
107
  }));
98
- await writeVolumeOverride(state.overridePath, state.volumes);
108
+ await writeVolumeOverride(created.overridePath, created.volumes);
99
109
  const environment = {
100
- ...state,
110
+ ...created,
101
111
  targetComposeFiles,
102
- sourceComposeFiles: [
103
- ...source.files,
104
- ...(source.sourceOverride !== undefined
105
- ? [source.sourceOverride]
106
- : []),
107
- ],
112
+ sourceComposeFiles: sourceComposeFiles(source),
108
113
  };
109
114
  await startWithHooks(config.hooks, environment, progress, nested?.layers(environment));
110
- await store.save({ ...state, status: 'ready' });
115
+ await store.save({ ...created, status: 'ready' });
111
116
  return { path: target, projectName };
112
117
  }
113
118
  catch (error) {
114
- if (worktreeMade || await isRegistered(target, root)) {
119
+ if (state !== undefined && (worktreeMade || await isRegistered(target, root))) {
115
120
  await store.save({ ...state, status: 'failed', error: error.message });
116
121
  const retry = nested?.retryName ?? name;
117
122
  throw new WtError('setup_failed', `${error.message}\nRun wt reset ${retry} to retry setup or wt rm ${retry} to discard the worktree.`, { cause: error });
@@ -119,6 +124,15 @@ export async function createEnvironmentLocked(name, options, { root, gitCommonDi
119
124
  throw error;
120
125
  }
121
126
  }
127
+ /** Compose files of the source project, with the override of a managed source worktree. */
128
+ function sourceComposeFiles(source) {
129
+ return source.sourceOverride === undefined
130
+ ? source.files
131
+ : [
132
+ ...source.files,
133
+ source.sourceOverride,
134
+ ];
135
+ }
122
136
  async function planTarget(name, config, gitCommonDir, repositoryRoot) {
123
137
  const resourceName = worktreeResourceName(name);
124
138
  if (!resourceName)
@@ -0,0 +1,36 @@
1
+ import { checkInterrupted } from './process.js';
2
+ /**
3
+ * Acquires the locks in order, runs `work` while they are held, and releases
4
+ * them in reverse order, also when `work` or a later lock fails.
5
+ */
6
+ export async function withLocks([lock, ...rest], work) {
7
+ if (lock === undefined) {
8
+ checkInterrupted();
9
+ return work();
10
+ }
11
+ const unlock = await lock();
12
+ try {
13
+ return await withLocks(rest, work);
14
+ }
15
+ finally {
16
+ await unlock?.();
17
+ }
18
+ }
19
+ /** Lock of the worktree `name`. */
20
+ export function worktreeLock(store, name) {
21
+ return async () => store.lockWorktree(name);
22
+ }
23
+ /**
24
+ * Lock of the managed worktree that runs the Compose project `sourceProject`,
25
+ * so it is not removed or reset while `name` copies its volumes and files.
26
+ * Nothing is locked when the source is not a managed worktree, such as the
27
+ * main checkout.
28
+ */
29
+ export function sourceLock(store, sourceProject, name) {
30
+ return async () => {
31
+ const source = (await store.list()).find(item => item.projectName === sourceProject);
32
+ return source === undefined || source.name.toLowerCase() === name.toLowerCase()
33
+ ? undefined
34
+ : store.lockWorktree(source.name);
35
+ };
36
+ }
@@ -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';
@@ -13,8 +14,9 @@ import { AttachedStore, StateStore } from '../state/store.js';
13
14
  import { formatConfirmation } from './confirmation.js';
14
15
  import { copyConfiguredPaths } from './copy-paths.js';
15
16
  import { startWithHooks, validateSourceHooks, validateWorktreeHooks } from './hooks.js';
17
+ import { sourceLock, withLocks, worktreeLock } from './locks.js';
16
18
  import { checkInterrupted, currentSignal } from './process.js';
17
- import { outputReporter, runStep } from './progress.js';
19
+ import { cloneLabel, outputReporter, runStep } from './progress.js';
18
20
  async function context(cwd) {
19
21
  const info = await repositoryInfo(cwd);
20
22
  return {
@@ -69,15 +71,20 @@ async function removeClonedVolumes(state, cwd, keep = []) {
69
71
  for (const volume of volumes)
70
72
  await removeOwnedVolume(volume, state.repositoryId, state.name, cwd);
71
73
  }
72
- 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) {
73
80
  const { store } = await context(cwd);
74
81
  const states = await store.list();
75
82
  if (states.length === 0)
76
83
  return [];
77
- const dockerStatus = await dockerStatuses(cwd);
84
+ const status = dockerStatus ?? await dockerStatuses(cwd);
78
85
  return states.map(state => ({
79
86
  ...state,
80
- dockerStatus: dockerStatus(state.projectName),
87
+ dockerStatus: status(state.projectName),
81
88
  }));
82
89
  }
83
90
  /** Reads all Compose containers once and returns a summary lookup by project name. */
@@ -158,7 +165,7 @@ export async function composeOperation(name, action, args, cwd, progress) {
158
165
  const { store } = await context(cwd);
159
166
  const unlock = action === 'docker'
160
167
  ? undefined
161
- : await store.lock('repository');
168
+ : await store.lockWorktree(name);
162
169
  try {
163
170
  const state = await store.get(name);
164
171
  return await runManagedCompose(state, action, args, progress);
@@ -232,41 +239,41 @@ export async function removeEnvironment(name, cwd, force = false, confirm, progr
232
239
  if (!await requestConfirmation(request, confirm))
233
240
  return false;
234
241
  }
235
- const unlock = await store.lock('repository');
236
- try {
237
- checkInterrupted();
242
+ return withLocks([
243
+ worktreeLock(store, name),
244
+ ], async () => {
238
245
  await checkUnchanged(store, state);
239
246
  await removeLocked(state, store, cwd, progress);
240
247
  return true;
241
- }
242
- finally {
243
- await unlock();
244
- }
248
+ });
245
249
  }
246
250
  /**
247
251
  * Removes the environment's containers, cloned volumes, Git worktree, and
248
- * state while the repository lock is held. `cwd` must be inside the
249
- * environment's repository. `retryName` is shown when the directory remains.
252
+ * state while the worktree's lock is held. It takes the repository lock only
253
+ * to remove the Git worktree. `cwd` must be inside the environment's
254
+ * repository. `retryName` is shown when the directory remains.
250
255
  */
251
256
  export async function removeLocked(state, store, cwd, progress, retryName = state.name) {
252
257
  const target = await realpath(state.path).catch(() => resolve(state.path));
253
258
  await store.save({ ...state, status: 'removing' });
254
259
  await runStep(progress, 'Stopping and removing Compose containers', async () => downEnvironment(state, cwd, true));
255
260
  await runStep(progress, 'Removing cloned Docker volumes', async () => removeClonedVolumes(state, cwd));
256
- const registeredWorktrees = await git([
257
- 'worktree',
258
- 'list',
259
- '--porcelain',
260
- '-z',
261
- ], cwd);
262
- if (registeredWorktrees.split('\0').includes(`worktree ${target}`)) {
263
- await runStep(progress, 'Removing Git worktree', async () => git([
261
+ await store.withRepositoryLock(async () => {
262
+ const registeredWorktrees = await git([
264
263
  'worktree',
265
- 'remove',
266
- '--force',
267
- state.path,
268
- ], cwd));
269
- }
264
+ 'list',
265
+ '--porcelain',
266
+ '-z',
267
+ ], cwd);
268
+ if (registeredWorktrees.split('\0').includes(`worktree ${target}`)) {
269
+ await runStep(progress, 'Removing Git worktree', async () => git([
270
+ 'worktree',
271
+ 'remove',
272
+ '--force',
273
+ state.path,
274
+ ], cwd));
275
+ }
276
+ });
270
277
  if (await exists(target))
271
278
  throw new Error(`Unregistered worktree directory still exists at ${target}. Move it out of the way and retry wt rm ${retryName}.`);
272
279
  if (await exists(state.overridePath))
@@ -293,18 +300,16 @@ export async function resetEnvironment(name, cwd, force = false, confirm, progre
293
300
  if (!await requestConfirmation(request, confirm))
294
301
  return false;
295
302
  }
296
- const unlock = await store.lock('repository');
297
- try {
298
- checkInterrupted();
303
+ return withLocks([
304
+ worktreeLock(store, name),
305
+ sourceLock(store, state.sourceProject, name),
306
+ ], async () => {
299
307
  await checkUnchanged(store, state);
300
308
  if (state.status === 'removing')
301
309
  throw new WtError('not_ready', `Removal of ${name} is incomplete. Retry wt rm ${name}.`);
302
310
  await resetLocked({ ...state, sourceWorktreePath: sourceRoot }, store, config, cwd, { progress });
303
311
  return true;
304
- }
305
- finally {
306
- await unlock();
307
- }
312
+ });
308
313
  }
309
314
  /**
310
315
  * Loads the configuration an environment was created with and checks that
@@ -336,8 +341,9 @@ export async function validateCopyAndHooks(config, sourceRoot, path) {
336
341
  }
337
342
  /**
338
343
  * Refreshes the environment's volumes and copied files and runs its hooks
339
- * again while the repository lock is held. `nested` adds hook layers for a
340
- * checkout of another repository inside the environment.
344
+ * again while the locks of the worktree and its managed source are held.
345
+ * `nested` adds hook layers for a checkout of another repository inside the
346
+ * environment.
341
347
  */
342
348
  export async function resetLocked(state, store, config, cwd, { progress, nested } = {}) {
343
349
  const { sourceWorktreePath: sourceRoot } = state;
@@ -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
+ };