@joberthel/worktree 1.3.0 → 1.4.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/README.md CHANGED
@@ -102,7 +102,7 @@ eval "$(wt completion bash)"
102
102
 
103
103
  ### Coding agents
104
104
 
105
- The repository ships an [agent skill](skills/wt/SKILL.md) that teaches coding agents such as Claude Code, Codex or Cursor when and how to use `wt`: create an isolated environment for a task, find its ports and URLs, run Compose commands in it, and remove it only after asking you. Install it with the [`skills`](https://github.com/vercel-labs/skills) CLI:
105
+ The repository ships an [agent skill](skills/wt/SKILL.md) that teaches coding agents such as Claude Code, Codex or Cursor when and how to use `wt`: create an isolated environment for a task, find its ports and URLs, run Compose commands in it, and remove it only after asking you. It also covers nested repositories and, when you ask for it, writing a `.wt.yml`. Install it with the [`skills`](https://github.com/vercel-labs/skills) CLI:
106
106
 
107
107
  ```sh
108
108
  npx skills add joberthel/worktree
package/dist/errors.js CHANGED
@@ -28,7 +28,7 @@ export const errorCodes = [
28
28
  'confirmation_required',
29
29
  /** The current directory is inside the worktree that would be removed. */
30
30
  'inside_worktree',
31
- /** Another wt command holds the repository lock. */
31
+ /** Another wt command holds the lock of the worktree, its source, or the repository. */
32
32
  'locked',
33
33
  /** The worktree changed while the command waited; retry it. */
34
34
  'changed',
@@ -7,10 +7,10 @@ import { WtError } from '../errors.js';
7
7
  import { git, repositoryInfo } from '../git/repository.js';
8
8
  import { AttachedStore, StateStore } from '../state/store.js';
9
9
  import { copyConfiguredPaths } from './copy-paths.js';
10
- import { createEnvironmentLocked, loadCreateConfig, planCheckout, validateHookRevision } from './create.js';
10
+ import { createManagedEnvironment, loadCreateConfig, planCheckout, validateHookRevision } from './create.js';
11
11
  import { validateSourceHooks, validateWorktreeHooks } from './hooks.js';
12
+ import { sourceLock, withLocks, worktreeLock } from './locks.js';
12
13
  import { checkUnchanged, exists, prepareReset, removeLocked, requestConfirmation, resetLocked, validateCopyAndHooks } from './manage.js';
13
- import { checkInterrupted } from './process.js';
14
14
  import { runStep } from './progress.js';
15
15
  function isInside(parent, child) {
16
16
  const path = relative(parent, child);
@@ -65,9 +65,16 @@ async function checkAbsent(path) {
65
65
  /**
66
66
  * Creates a worktree of this repository nested in a new detached worktree of
67
67
  * its host repository, with the host's Docker environment. The host checkout
68
- * gets no branch; the attached worktree gets the requested one.
68
+ * gets no branch; the attached worktree gets the requested one. The attached
69
+ * worktree stays locked while it is set up.
69
70
  */
70
- export async function createAttached(name, options, { repository, config, configurationPath }, progress) {
71
+ export async function createAttached(name, options, settings, progress) {
72
+ const store = new StateStore(settings.repository.gitCommonDir);
73
+ return withLocks([
74
+ worktreeLock(store, name),
75
+ ], async () => createAttachedLocked(name, options, store, settings, progress));
76
+ }
77
+ async function createAttachedLocked(name, options, store, { repository, config, configurationPath }, progress) {
71
78
  const { root, gitCommonDir } = repository;
72
79
  const { host, mountPath } = await locateHost(root, config.host.path, progress);
73
80
  const attached = new AttachedStore(gitCommonDir);
@@ -80,7 +87,6 @@ export async function createAttached(name, options, { repository, config, config
80
87
  await access(resolve(root, path));
81
88
  const hostName = `${worktreeResourceName(basename(mountPath)) || 'attached'}/${name}`;
82
89
  const hostStore = new StateStore(host.gitCommonDir);
83
- const unlock = await hostStore.lock('repository');
84
90
  let state;
85
91
  try {
86
92
  const hostConfig = await loadCreateConfig(host, progress);
@@ -107,7 +113,7 @@ export async function createAttached(name, options, { repository, config, config
107
113
  const { path } = state;
108
114
  await checkAbsent(path);
109
115
  await mkdir(dirname(path), { recursive: true });
110
- await runStep(progress, `Creating Git worktree ${name} at ${mountPath}`, async () => git(plan.args(path), root));
116
+ await store.withRepositoryLock(async () => runStep(progress, `Creating Git worktree ${name} at ${mountPath}`, async () => git(plan.args(path), root)));
111
117
  if (config.copy.length > 0)
112
118
  await runStep(progress, `Copying configured files into ${mountPath}`, async () => copyConfiguredPaths(root, path, config.copy));
113
119
  await validateWorktreeHooks(config.hooks, path);
@@ -116,7 +122,7 @@ export async function createAttached(name, options, { repository, config, config
116
122
  attachedLayer(config, state, environment),
117
123
  ],
118
124
  };
119
- const result = await createEnvironmentLocked(hostName, { detach: true, from: config.host.from }, host, hostStore, { ...hostConfig, nested, progress });
125
+ const result = await createManagedEnvironment(hostName, { detach: true, from: config.host.from }, host, hostStore, { ...hostConfig, nested, progress });
120
126
  await attached.save({ ...state, status: 'ready' });
121
127
  return { path: state.path, projectName: result.projectName };
122
128
  }
@@ -129,9 +135,6 @@ export async function createAttached(name, options, { repository, config, config
129
135
  }
130
136
  throw error;
131
137
  }
132
- finally {
133
- await unlock();
134
- }
135
138
  }
136
139
  async function hostOf(state) {
137
140
  const store = new StateStore(state.host.gitCommonDir);
@@ -152,22 +155,6 @@ async function isRegistered(path, cwd) {
152
155
  ], cwd);
153
156
  return listed.split('\0').includes(`worktree ${target}`);
154
157
  }
155
- async function withLocks(store, hostStore, work) {
156
- const unlock = await store.lock('repository');
157
- try {
158
- const unlockHost = await hostStore.lock('repository');
159
- try {
160
- checkInterrupted();
161
- return await work();
162
- }
163
- finally {
164
- await unlockHost();
165
- }
166
- }
167
- finally {
168
- await unlock();
169
- }
170
- }
171
158
  /**
172
159
  * Removes the attached worktree, then its host worktree and Docker
173
160
  * environment. The attached branch is kept.
@@ -208,20 +195,25 @@ export async function removeAttached({ state, attached, store }, cwd, force = fa
208
195
  if (!await requestConfirmation(request, confirm))
209
196
  return false;
210
197
  }
211
- await withLocks(store, hostStore, async () => {
198
+ await withLocks([
199
+ worktreeLock(store, name),
200
+ worktreeLock(hostStore, state.host.name),
201
+ ], async () => {
212
202
  await checkUnchanged(attached, state);
213
203
  await attached.save({ ...state, status: 'removing' });
214
- if (await isRegistered(state.path, state.sourceWorktreePath)) {
215
- await runStep(progress, `Removing Git worktree ${name}`, async () => git([
216
- 'worktree',
217
- 'remove',
218
- '--force',
219
- state.path,
220
- ], state.sourceWorktreePath));
221
- }
222
- else if (await exists(state.path)) {
223
- throw new Error(`Unregistered directory still exists at ${state.path}. Move it out of the way and retry wt rm ${name}.`);
224
- }
204
+ await store.withRepositoryLock(async () => {
205
+ if (await isRegistered(state.path, state.sourceWorktreePath)) {
206
+ await runStep(progress, `Removing Git worktree ${name}`, async () => git([
207
+ 'worktree',
208
+ 'remove',
209
+ '--force',
210
+ state.path,
211
+ ], state.sourceWorktreePath));
212
+ }
213
+ else if (await exists(state.path)) {
214
+ throw new Error(`Unregistered directory still exists at ${state.path}. Move it out of the way and retry wt rm ${name}.`);
215
+ }
216
+ });
225
217
  const current = await hostStore.find(state.host.name);
226
218
  if (current !== undefined)
227
219
  await removeLocked(current, hostStore, state.host.repositoryRoot, progress, name);
@@ -264,7 +256,11 @@ export async function resetAttached({ state, attached, store }, force = false, c
264
256
  if (!await requestConfirmation(request, confirm))
265
257
  return false;
266
258
  }
267
- await withLocks(store, hostStore, async () => {
259
+ await withLocks([
260
+ worktreeLock(store, name),
261
+ worktreeLock(hostStore, state.host.name),
262
+ sourceLock(hostStore, host.sourceProject, state.host.name),
263
+ ], async () => {
268
264
  await checkUnchanged(attached, state);
269
265
  await checkUnchanged(hostStore, host);
270
266
  if (host.status === 'removing' || state.status === 'removing')
@@ -5,7 +5,7 @@ import { WtError } from '../errors.js';
5
5
  import { repositoryInfo } from '../git/repository.js';
6
6
  import { AttachedStore, StateStore } from '../state/store.js';
7
7
  import { attachedHost, createAttached, removeAttached, resetAttached } from './attached.js';
8
- import { createEnvironmentLocked, withCreateContext } from './create.js';
8
+ import { createManagedEnvironment, withCreateContext } from './create.js';
9
9
  import * as manage from './manage.js';
10
10
  /*
11
11
  * Entry points of the CLI. A name refers to an environment of the current
@@ -14,7 +14,7 @@ import * as manage from './manage.js';
14
14
  */
15
15
  export async function createEnvironment(name, options, cwd, progress) {
16
16
  return withCreateContext(name, options, cwd, progress, async (repository, store, loaded) => loaded.config.host === undefined
17
- ? createEnvironmentLocked(name, options, repository, store, { ...loaded, progress })
17
+ ? createManagedEnvironment(name, options, repository, store, { ...loaded, progress })
18
18
  : createAttached(name, options, { repository, ...loaded }, progress));
19
19
  }
20
20
  async function findAttached(name, cwd) {
@@ -148,7 +148,7 @@ export async function composeOperation(name, action, args, cwd, progress) {
148
148
  const hostStore = new StateStore(state.host.gitCommonDir);
149
149
  const unlock = action === 'docker'
150
150
  ? undefined
151
- : await hostStore.lock('repository');
151
+ : await hostStore.lockWorktree(state.host.name);
152
152
  try {
153
153
  return await manage.runManagedCompose(await hostStore.get(state.host.name), action, args, progress);
154
154
  }
@@ -7,6 +7,7 @@ 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
12
  import { runStep } from './progress.js';
12
13
  const namePattern = /^\w[\w.-]*(?:\/\w[\w.-]*)*$/;
@@ -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,83 @@ 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
+ created.volumes = await runStep(progress, 'Cloning named Docker volumes (live writes may cause inconsistent data)', async () => cloneNamedVolumes(sources, created, root, image, async (_volume, volumes) => {
104
+ created.volumes = volumes;
105
+ await store.save(created);
97
106
  }));
98
- await writeVolumeOverride(state.overridePath, state.volumes);
107
+ await writeVolumeOverride(created.overridePath, created.volumes);
99
108
  const environment = {
100
- ...state,
109
+ ...created,
101
110
  targetComposeFiles,
102
- sourceComposeFiles: [
103
- ...source.files,
104
- ...(source.sourceOverride !== undefined
105
- ? [source.sourceOverride]
106
- : []),
107
- ],
111
+ sourceComposeFiles: sourceComposeFiles(source),
108
112
  };
109
113
  await startWithHooks(config.hooks, environment, progress, nested?.layers(environment));
110
- await store.save({ ...state, status: 'ready' });
114
+ await store.save({ ...created, status: 'ready' });
111
115
  return { path: target, projectName };
112
116
  }
113
117
  catch (error) {
114
- if (worktreeMade || await isRegistered(target, root)) {
118
+ if (state !== undefined && (worktreeMade || await isRegistered(target, root))) {
115
119
  await store.save({ ...state, status: 'failed', error: error.message });
116
120
  const retry = nested?.retryName ?? name;
117
121
  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 +123,15 @@ export async function createEnvironmentLocked(name, options, { root, gitCommonDi
119
123
  throw error;
120
124
  }
121
125
  }
126
+ /** Compose files of the source project, with the override of a managed source worktree. */
127
+ function sourceComposeFiles(source) {
128
+ return source.sourceOverride === undefined
129
+ ? source.files
130
+ : [
131
+ ...source.files,
132
+ source.sourceOverride,
133
+ ];
134
+ }
122
135
  async function planTarget(name, config, gitCommonDir, repositoryRoot) {
123
136
  const resourceName = worktreeResourceName(name);
124
137
  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
+ }
@@ -13,6 +13,7 @@ import { AttachedStore, StateStore } from '../state/store.js';
13
13
  import { formatConfirmation } from './confirmation.js';
14
14
  import { copyConfiguredPaths } from './copy-paths.js';
15
15
  import { startWithHooks, validateSourceHooks, validateWorktreeHooks } from './hooks.js';
16
+ import { sourceLock, withLocks, worktreeLock } from './locks.js';
16
17
  import { checkInterrupted, currentSignal } from './process.js';
17
18
  import { outputReporter, runStep } from './progress.js';
18
19
  async function context(cwd) {
@@ -158,7 +159,7 @@ export async function composeOperation(name, action, args, cwd, progress) {
158
159
  const { store } = await context(cwd);
159
160
  const unlock = action === 'docker'
160
161
  ? undefined
161
- : await store.lock('repository');
162
+ : await store.lockWorktree(name);
162
163
  try {
163
164
  const state = await store.get(name);
164
165
  return await runManagedCompose(state, action, args, progress);
@@ -232,41 +233,41 @@ export async function removeEnvironment(name, cwd, force = false, confirm, progr
232
233
  if (!await requestConfirmation(request, confirm))
233
234
  return false;
234
235
  }
235
- const unlock = await store.lock('repository');
236
- try {
237
- checkInterrupted();
236
+ return withLocks([
237
+ worktreeLock(store, name),
238
+ ], async () => {
238
239
  await checkUnchanged(store, state);
239
240
  await removeLocked(state, store, cwd, progress);
240
241
  return true;
241
- }
242
- finally {
243
- await unlock();
244
- }
242
+ });
245
243
  }
246
244
  /**
247
245
  * 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.
246
+ * state while the worktree's lock is held. It takes the repository lock only
247
+ * to remove the Git worktree. `cwd` must be inside the environment's
248
+ * repository. `retryName` is shown when the directory remains.
250
249
  */
251
250
  export async function removeLocked(state, store, cwd, progress, retryName = state.name) {
252
251
  const target = await realpath(state.path).catch(() => resolve(state.path));
253
252
  await store.save({ ...state, status: 'removing' });
254
253
  await runStep(progress, 'Stopping and removing Compose containers', async () => downEnvironment(state, cwd, true));
255
254
  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([
255
+ await store.withRepositoryLock(async () => {
256
+ const registeredWorktrees = await git([
264
257
  'worktree',
265
- 'remove',
266
- '--force',
267
- state.path,
268
- ], cwd));
269
- }
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([
264
+ 'worktree',
265
+ 'remove',
266
+ '--force',
267
+ state.path,
268
+ ], cwd));
269
+ }
270
+ });
270
271
  if (await exists(target))
271
272
  throw new Error(`Unregistered worktree directory still exists at ${target}. Move it out of the way and retry wt rm ${retryName}.`);
272
273
  if (await exists(state.overridePath))
@@ -293,18 +294,16 @@ export async function resetEnvironment(name, cwd, force = false, confirm, progre
293
294
  if (!await requestConfirmation(request, confirm))
294
295
  return false;
295
296
  }
296
- const unlock = await store.lock('repository');
297
- try {
298
- checkInterrupted();
297
+ return withLocks([
298
+ worktreeLock(store, name),
299
+ sourceLock(store, state.sourceProject, name),
300
+ ], async () => {
299
301
  await checkUnchanged(store, state);
300
302
  if (state.status === 'removing')
301
303
  throw new WtError('not_ready', `Removal of ${name} is incomplete. Retry wt rm ${name}.`);
302
304
  await resetLocked({ ...state, sourceWorktreePath: sourceRoot }, store, config, cwd, { progress });
303
305
  return true;
304
- }
305
- finally {
306
- await unlock();
307
- }
306
+ });
308
307
  }
309
308
  /**
310
309
  * Loads the configuration an environment was created with and checks that
@@ -336,8 +335,9 @@ export async function validateCopyAndHooks(config, sourceRoot, path) {
336
335
  }
337
336
  /**
338
337
  * 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.
338
+ * again while the locks of the worktree and its managed source are held.
339
+ * `nested` adds hook layers for a checkout of another repository inside the
340
+ * environment.
341
341
  */
342
342
  export async function resetLocked(state, store, config, cwd, { progress, nested } = {}) {
343
343
  const { sourceWorktreePath: sourceRoot } = state;
@@ -1,9 +1,11 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { link, mkdir, readdir, readFile, unlink, writeFile } from 'node:fs/promises';
3
- import { join } from 'node:path';
3
+ import { dirname, join } from 'node:path';
4
4
  import process from 'node:process';
5
+ import { setTimeout as sleep } from 'node:timers/promises';
5
6
  import { z } from 'zod';
6
7
  import { WtError } from '../errors.js';
8
+ import { currentSignal } from '../operations/process.js';
7
9
  import { writeAtomicFile } from './atomic-file.js';
8
10
  const status = z.enum([
9
11
  'creating',
@@ -57,6 +59,40 @@ const attachedSchema = z.object({
57
59
  function isMissing(error) {
58
60
  return error.code === 'ENOENT';
59
61
  }
62
+ const repositoryLockTimeout = 60_000;
63
+ const lockPollInterval = 100;
64
+ /** What a lock file records about the command that holds it. */
65
+ function lockOwner() {
66
+ const started = new Date(Date.now() - process.uptime() * 1000).toISOString();
67
+ const command = [
68
+ 'wt',
69
+ ...process.argv.slice(2),
70
+ ].join(' ');
71
+ return `${process.pid} (started ${started}): ${command}`;
72
+ }
73
+ /**
74
+ * Creates the lock file at `path` atomically with the owner's details. A lock
75
+ * file is never removed by another command, because its owner may still run.
76
+ */
77
+ async function acquire(path, locked) {
78
+ const temporary = join(dirname(path), `${randomUUID()}.tmp`);
79
+ await writeFile(temporary, `${lockOwner()}\n`, { mode: 0o600, flag: 'wx' });
80
+ try {
81
+ await link(temporary, path);
82
+ }
83
+ catch (error) {
84
+ if (error.code !== 'EEXIST')
85
+ throw error;
86
+ const owner = await readFile(path, 'utf8').catch(() => '');
87
+ throw new WtError('locked', `${locked} at ${path}${owner.trim()
88
+ ? ` by PID ${owner.trim()}`
89
+ : ''}. Retry when it exits. If the lock is stale, verify the owner has exited before removing the lock file.`);
90
+ }
91
+ finally {
92
+ await unlink(temporary);
93
+ }
94
+ return async () => unlink(path);
95
+ }
60
96
  class JsonStore {
61
97
  directory;
62
98
  schema;
@@ -128,27 +164,47 @@ export class StateStore extends JsonStore {
128
164
  constructor(gitCommonDir) {
129
165
  super(join(gitCommonDir, 'wt'), stateSchema, 'worktree');
130
166
  }
131
- async lock(name) {
167
+ /**
168
+ * Locks one worktree for as long as a command changes it. Fails at once when
169
+ * another command holds the lock, because that command may run for minutes.
170
+ * Names that differ only in case share a lock.
171
+ */
172
+ async lockWorktree(name) {
173
+ const directory = join(this.directory, 'locks');
174
+ await mkdir(directory, { recursive: true });
175
+ return acquire(join(directory, `${encodeURIComponent(name.toLowerCase())}.lock`), `Worktree ${name} is busy: it is locked`);
176
+ }
177
+ /**
178
+ * Locks the repository's shared state for a short step: checking that a new
179
+ * worktree's name and directory are free, registering it, and adding or
180
+ * removing Git worktrees. Waits up to `timeout` milliseconds for another
181
+ * command to finish its step.
182
+ */
183
+ async lockRepository(timeout = repositoryLockTimeout) {
132
184
  await mkdir(this.directory, { recursive: true });
133
- const path = this.pathFor(name, '.lock');
134
- const temporary = this.pathFor(randomUUID(), '.tmp');
135
- const started = new Date(Date.now() - process.uptime() * 1000).toISOString();
136
- await writeFile(temporary, `${process.pid} (started ${started})\n`, { mode: 0o600, flag: 'wx' });
137
- try {
138
- await link(temporary, path);
185
+ const path = join(this.directory, 'repository.lock');
186
+ const deadline = Date.now() + timeout;
187
+ for (;;) {
188
+ try {
189
+ return await acquire(path, 'Worktree operations are locked');
190
+ }
191
+ catch (error) {
192
+ if (error.code !== 'locked' || Date.now() >= deadline)
193
+ throw error;
194
+ }
195
+ await sleep(lockPollInterval);
196
+ currentSignal()?.throwIfAborted();
139
197
  }
140
- catch (error) {
141
- if (error.code !== 'EEXIST')
142
- throw error;
143
- const owner = await readFile(path, 'utf8').catch(() => '');
144
- throw new WtError('locked', `Worktree operations are locked at ${path}${owner.trim()
145
- ? ` by PID ${owner.trim()}`
146
- : ''}. Retry when it exits. If the lock is stale, verify the owner has exited before removing the lock file.`);
198
+ }
199
+ /** Runs `work` while the repository lock is held. */
200
+ async withRepositoryLock(work) {
201
+ const unlock = await this.lockRepository();
202
+ try {
203
+ return await work();
147
204
  }
148
205
  finally {
149
- await unlink(temporary);
206
+ await unlock();
150
207
  }
151
- return async () => unlink(path);
152
208
  }
153
209
  }
154
210
  /**
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@joberthel/worktree",
3
3
  "type": "module",
4
- "version": "1.3.0",
4
+ "version": "1.4.0",
5
5
  "description": "Isolated development environments from Git worktrees, each with its own Docker Compose project and cloned volumes.",
6
6
  "author": "Johannes Berthel",
7
7
  "license": "MIT",