@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.
package/README.md CHANGED
@@ -43,10 +43,10 @@ Start the project's Compose environment from the root of your checkout, so that
43
43
  docker compose up -d
44
44
  wt create feature/login
45
45
  wt ls
46
- cd ../worktrees/feature--login
46
+ cd "$(wt path feature/login)"
47
47
  ```
48
48
 
49
- This creates the branch `feature/login`, the worktree `../worktrees/feature--login`, and a running copy of the Compose project. To check out an existing local or remote branch instead, give the worktree a name and pass `--branch`. To branch off a ref other than `HEAD`, pass `--from`:
49
+ This creates the branch `feature/login`, the worktree `../worktrees/feature--login`, and a running copy of the Compose project. With the [shell function](#changing-to-a-worktree), `wt cd feature/login` changes to the worktree. To check out an existing local or remote branch instead, give the worktree a name and pass `--branch`. To branch off a ref other than `HEAD`, pass `--from`:
50
50
 
51
51
  ```sh
52
52
  wt create login-review --branch origin/feature/login
@@ -66,13 +66,17 @@ wt rm feature/login
66
66
  | `wt create <name> [--branch <branch> \| --from <ref>]` | Create a worktree, branch, and isolated Compose environment. |
67
67
  | `wt ls [--filter <key=value>...]` | List managed worktrees, their Docker status and, with OrbStack, their main URL. Filter by `name`, `branch` or `state`. |
68
68
  | `wt info [name]` | Show a worktree's branch, path, status, services, published ports, OrbStack domains and volumes. |
69
+ | `wt path [name]` | Print the absolute path of a worktree. |
70
+ | `wt cd [name]` | Change to a worktree's directory. Needs the [shell function](#changing-to-a-worktree). |
69
71
  | `wt start [name]` | Start its Compose services. |
70
72
  | `wt stop [name]` | Stop its Compose services. |
71
73
  | `wt restart [name]` | Restart its Compose services. |
72
74
  | `wt docker [name] -- <compose args...>` | Run a Docker Compose command in that worktree's project. |
73
75
  | `wt reset [name] [--force \| --dry-run]` | Stop the environment, recopy configured paths, refresh cloned volumes, and start it again. |
74
76
  | `wt rm <name> [--force \| --dry-run]` | Remove the managed environment and Git worktree while keeping its branch. |
77
+ | `wt unlock <name> \| --repository [--force \| --dry-run]` | Remove a lock that a killed command left behind and `wt` could not take over by itself. |
75
78
  | `wt completion <zsh\|bash>` | Print a shell completion script. |
79
+ | `wt shell-init <zsh\|bash>` | Print the shell function for `wt cd`. |
76
80
 
77
81
  Run them from any worktree of the repository. Commands with an optional `[name]` default to the worktree that contains the current directory.
78
82
 
@@ -84,9 +88,9 @@ wt docker -- exec app sh # from inside the feature/login worktree
84
88
  Two options are shared by the commands:
85
89
 
86
90
  - `-w <dir>` or `--working-dir <dir>` runs `wt` as if it was started in `<dir>`, for example for a repository in a subdirectory. It can go before or after the command, but not after `--`.
87
- - `--format json` prints the result, or an error with a stable code, as JSON on stdout, for every command except `wt docker` and `wt completion`. Set `WT_FORMAT=json` to make it the default. See [JSON output](docs/json-output.md).
91
+ - `--format json` prints the result, or an error with a stable code, as JSON on stdout, for every command except `wt docker`, `wt cd`, `wt completion` and `wt shell-init`. Set `WT_FORMAT=json` to make it the default. See [JSON output](docs/json-output.md).
88
92
 
89
- `wt reset` and `wt rm` ask before they change anything. Pass `--force` to skip the question, for example in scripts, or `--dry-run` to only see what would change. See [Commands](docs/commands.md) for how branches are resolved, the confirmation prompt, and the progress view.
93
+ `wt reset`, `wt rm` and `wt unlock` ask before they change anything. Pass `--force` to skip the question, for example in scripts, or `--dry-run` to only see what would change. See [Commands](docs/commands.md) for how branches are resolved, the confirmation prompt, locks, and the progress view.
90
94
 
91
95
  ### Shell completion
92
96
 
@@ -100,9 +104,29 @@ source <(wt completion zsh)
100
104
  eval "$(wt completion bash)"
101
105
  ```
102
106
 
107
+ ### Changing to a worktree
108
+
109
+ `wt path [name]` prints the absolute path of a worktree and nothing else. It reads only `wt`'s state, never Docker, so it is quick enough for scripts:
110
+
111
+ ```sh
112
+ cd "$(wt path feature/login)"
113
+ ```
114
+
115
+ A program cannot change the directory of the shell that started it, so `wt cd` needs a shell function. Load it from your shell's startup file:
116
+
117
+ ```sh
118
+ # ~/.zshrc
119
+ eval "$(wt shell-init zsh)"
120
+
121
+ # ~/.bashrc
122
+ eval "$(wt shell-init bash)"
123
+ ```
124
+
125
+ Then `wt cd feature/login` changes to that worktree, and `wt cd` without a name to the root of the worktree you are in. The function passes every other command to `wt` unchanged.
126
+
103
127
  ### Coding agents
104
128
 
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:
129
+ 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
130
 
107
131
  ```sh
108
132
  npx skills add joberthel/worktree
@@ -133,11 +157,11 @@ hooks:
133
157
 
134
158
  The first line enables completion and validation in editors; see [Editor support](docs/configuration.md#editor-support). See [Configuration](docs/configuration.md) for every option, the hook order and variables, and how volumes are cloned. For a repository that runs inside another one, such as a Shopware plugin, see [Nested repositories](docs/nested-repositories.md).
135
159
 
136
- Before you clone a database volume, stop writes to it or stop the source services if you need a consistent snapshot. Use dynamic host ports and leave out fixed `container_name` values, so the source and worktree projects can run side by side.
160
+ By default, the source services keep running while `wt` copies their volumes, so a database that writes during the copy can leave an inconsistent clone. Set [`volumes.pause_source`](docs/configuration.md#volumespause_source) to pause them during the copy, or stop them first. Use dynamic host ports and leave out fixed `container_name` values, so the source and worktree projects can run side by side.
137
161
 
138
162
  ## Documentation
139
163
 
140
- - [Commands](docs/commands.md): branches, confirmations, progress, and shell completion in detail.
164
+ - [Commands](docs/commands.md): branches, confirmations, progress, `wt cd`, and shell completion in detail.
141
165
  - [Configuration](docs/configuration.md): `.wt.yml`, hooks, environment variables, and Docker volumes.
142
166
  - [Nested repositories](docs/nested-repositories.md): worktrees of a repository that lives inside another checkout.
143
167
  - [JSON output](docs/json-output.md): the output of `--format json` for scripts and coding agents, including error codes.
package/dist/cli-spec.js CHANGED
@@ -11,7 +11,7 @@ const dryRun = {
11
11
  description: 'Show what would change, without changing anything',
12
12
  };
13
13
  export const commands = {
14
- create: {
14
+ 'create': {
15
15
  usage: '<name> [--branch <branch> | --from <ref>]',
16
16
  summary: 'Create an environment',
17
17
  options: {
@@ -21,7 +21,7 @@ export const commands = {
21
21
  environment: false,
22
22
  shared: true,
23
23
  },
24
- ls: {
24
+ 'ls': {
25
25
  usage: '[--filter <key=value>...]',
26
26
  summary: 'List managed environments',
27
27
  options: {
@@ -30,67 +30,106 @@ export const commands = {
30
30
  environment: false,
31
31
  shared: true,
32
32
  },
33
- info: {
33
+ 'info': {
34
34
  usage: '[name]',
35
35
  summary: 'Show environment details',
36
36
  options: {},
37
37
  environment: 'any',
38
38
  shared: true,
39
39
  },
40
- start: {
40
+ 'path': {
41
+ usage: '[name]',
42
+ summary: 'Print the worktree path',
43
+ options: {},
44
+ environment: 'any',
45
+ shared: true,
46
+ },
47
+ 'cd': {
48
+ usage: '[name]',
49
+ summary: 'Change to the worktree directory (needs wt shell-init)',
50
+ options: {},
51
+ environment: 'any',
52
+ shared: false,
53
+ },
54
+ 'start': {
41
55
  usage: '[name]',
42
56
  summary: 'Start services',
43
57
  options: {},
44
58
  environment: 'stopped',
45
59
  shared: true,
46
60
  },
47
- stop: {
61
+ 'stop': {
48
62
  usage: '[name]',
49
63
  summary: 'Stop services',
50
64
  options: {},
51
65
  environment: 'running',
52
66
  shared: true,
53
67
  },
54
- restart: {
68
+ 'restart': {
55
69
  usage: '[name]',
56
70
  summary: 'Restart services',
57
71
  options: {},
58
72
  environment: 'running',
59
73
  shared: true,
60
74
  },
61
- docker: {
75
+ 'docker': {
62
76
  usage: '[name] -- <compose arguments...>',
63
77
  summary: 'Run a Compose command',
64
78
  options: {},
65
79
  environment: 'any',
66
80
  shared: false,
67
81
  },
68
- reset: {
82
+ 'reset': {
69
83
  usage: '[name] [--force | --dry-run]',
70
84
  summary: 'Refresh files and volumes from the source',
71
85
  options: { force, 'dry-run': dryRun },
72
86
  environment: 'any',
73
87
  shared: true,
74
88
  },
75
- rm: {
89
+ 'rm': {
76
90
  usage: '<name> [--force | --dry-run]',
77
91
  summary: 'Remove an environment and keep its branch',
78
92
  options: { force, 'dry-run': dryRun },
79
93
  environment: 'any',
80
94
  shared: true,
81
95
  },
82
- completion: {
96
+ 'unlock': {
97
+ usage: '<name> | --repository [--force | --dry-run]',
98
+ summary: 'Remove a lock that a killed command left behind',
99
+ options: {
100
+ 'repository': { type: 'boolean', description: 'Remove the repository lock instead of a worktree lock' },
101
+ force,
102
+ 'dry-run': dryRun,
103
+ },
104
+ environment: 'any',
105
+ shared: true,
106
+ },
107
+ 'completion': {
83
108
  usage: '<zsh|bash>',
84
109
  summary: 'Print a shell completion script',
85
110
  options: {},
86
111
  environment: false,
87
112
  shared: false,
88
113
  },
114
+ 'shell-init': {
115
+ usage: '<zsh|bash>',
116
+ summary: 'Print the shell function for wt cd',
117
+ options: {},
118
+ environment: false,
119
+ shared: false,
120
+ },
89
121
  };
90
122
  export const shells = ['zsh', 'bash'];
91
123
  export function isCommand(value) {
92
124
  return Object.hasOwn(commands, value);
93
125
  }
126
+ /**
127
+ * Whether the command prints a script for the shell named by its argument.
128
+ * Such commands need no repository, so `-w` does not apply to them.
129
+ */
130
+ export function printsScript(command) {
131
+ return command === 'completion' || command === 'shell-init';
132
+ }
94
133
  /** Options of a command without the shared ones, as name and spec. */
95
134
  export function commandOptions(command) {
96
135
  const spec = commands[command];
package/dist/cli.js CHANGED
@@ -1,21 +1,32 @@
1
1
  #!/usr/bin/env node
2
- import { readFileSync } from 'node:fs';
3
2
  import process from 'node:process';
4
3
  import { parseArgs } from 'node:util';
5
- import { commandOptions, commands, extractWorkingDir, isCommand, isFormat, parseOptions, requestedFormat, shells, UsageError, workingDirectory } from './cli-spec.js';
4
+ import { commands, extractWorkingDir, isCommand, isFormat, parseOptions, printsScript, requestedFormat, shells, UsageError, workingDirectory } from './cli-spec.js';
6
5
  import { complete, completionScripts, formatCompletion } from './completion.js';
7
6
  import { errorCode, WtError } from './errors.js';
8
- import { listBranches } from './git/repository.js';
7
+ import { listBranches, withRepositoryCache } from './git/repository.js';
8
+ import { helpJson, usage, version } from './help.js';
9
9
  import { hasListFilter, matchesListFilter, parseListFilter } from './list-filter.js';
10
- import { composeOperation, createEnvironment, inspectEnvironment, listEnvironmentNames, listEnvironments, removeEnvironment, resetEnvironment, resolveEnvironmentName, runningEnvironmentNames } from './operations/commands.js';
11
- import { formatDryRun } from './operations/confirmation.js';
10
+ import { composeOperation, createEnvironment, environmentPath, inspectEnvironment, listEnvironmentNames, listEnvironments, removeEnvironment, resetEnvironment, resolveEnvironmentName, runningEnvironmentNames, unlockEnvironment } from './operations/commands.js';
11
+ import { formatDryRun, preview } from './operations/confirmation.js';
12
12
  import { ProcessFailure, withOperationSignal } from './operations/process.js';
13
+ import { shellInitScripts } from './shell-init.js';
13
14
  import { formatEnvironmentInfo } from './ui/environment-info.js';
14
15
  import { formatEnvironmentTable } from './ui/environment-table.js';
15
16
  import { formatStatus } from './ui/format-status.js';
16
17
  import { environmentInfoJson, environmentListJson, formatJson } from './ui/json-output.js';
17
18
  import { showOperation } from './ui/show-operation.js';
18
- const description = 'Manage isolated Git worktrees with Docker Compose.';
19
+ /** Commands that print their own output, without the progress view of an operation. */
20
+ const directCommands = [
21
+ 'docker',
22
+ 'path',
23
+ 'cd',
24
+ 'completion',
25
+ 'shell-init',
26
+ ];
27
+ function isDirect(command) {
28
+ return directCommands.includes(command);
29
+ }
19
30
  class Interrupted extends WtError {
20
31
  signal;
21
32
  constructor(signal) {
@@ -23,108 +34,6 @@ class Interrupted extends WtError {
23
34
  this.signal = signal;
24
35
  }
25
36
  }
26
- const workingDirOption = {
27
- name: '--working-dir',
28
- alias: '-w',
29
- value: '<dir>',
30
- description: 'Run as if wt was started in <dir>',
31
- repeatable: false,
32
- };
33
- const formatOption = {
34
- name: '--format',
35
- alias: null,
36
- value: '<text|json>',
37
- description: 'Output format (default: text, or WT_FORMAT)',
38
- repeatable: false,
39
- };
40
- function optionHelp(command) {
41
- return [
42
- ...commandOptions(command).map(([name, { type, value, description }]) => ({
43
- name: `--${name}`,
44
- alias: null,
45
- value: value ?? null,
46
- description,
47
- repeatable: type === 'strings',
48
- })),
49
- ...(command === 'completion'
50
- ? []
51
- : [workingDirOption]),
52
- ...(commands[command].shared
53
- ? [formatOption]
54
- : []),
55
- ];
56
- }
57
- function optionFlags({ name, alias, value }) {
58
- return `${alias === null
59
- ? ''
60
- : `${alias}, `}${name}${value === null
61
- ? ''
62
- : ` ${value}`}`;
63
- }
64
- function commandUsage(command) {
65
- return `wt ${command} ${commands[command].usage}`.trimEnd();
66
- }
67
- function usage(command) {
68
- if (command !== undefined) {
69
- const options = optionHelp(command).map(option => [
70
- optionFlags(option),
71
- option.description,
72
- ]);
73
- const width = Math.max(...options.map(([flags]) => flags.length));
74
- const optionList = options.length
75
- ? `\n\nOptions:\n${options.map(([flags, text]) => ` ${flags.padEnd(width)} ${text}`).join('\n')}`
76
- : '';
77
- return `Usage: ${commandUsage(command)}\n\n${commands[command].summary}${optionList}`;
78
- }
79
- const width = Math.max(...Object.keys(commands).map(name => name.length));
80
- const list = Object.entries(commands).map(([name, spec]) => ` ${name.padEnd(width)} ${spec.usage.padEnd(43)} ${spec.summary}`).join('\n');
81
- 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 docker\n -h, --help Show help\n -v, --version Show the version`;
82
- }
83
- function commandHelpJson(command) {
84
- return {
85
- name: command,
86
- usage: commandUsage(command),
87
- summary: commands[command].summary,
88
- options: optionHelp(command),
89
- formats: commands[command].shared
90
- ? ['text', 'json']
91
- : ['text'],
92
- };
93
- }
94
- /** `--help --format json`: the commands and options, read from the same table as the text help. */
95
- function helpJson(command) {
96
- if (command !== undefined)
97
- return commandHelpJson(command);
98
- return {
99
- name: 'wt',
100
- description,
101
- version: version(),
102
- usage: 'wt [-w <dir>] <command>',
103
- commands: Object.keys(commands).map(name => commandHelpJson(name)),
104
- options: [
105
- workingDirOption,
106
- { ...formatOption, description: 'Output format, for all commands except docker and completion (default: text, or WT_FORMAT)' },
107
- {
108
- name: '--help',
109
- alias: '-h',
110
- value: null,
111
- description: 'Show help',
112
- repeatable: false,
113
- },
114
- {
115
- name: '--version',
116
- alias: '-v',
117
- value: null,
118
- description: 'Show the version',
119
- repeatable: false,
120
- },
121
- ],
122
- };
123
- }
124
- function version() {
125
- const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
126
- return pkg.version;
127
- }
128
37
  function unknownFormat(format) {
129
38
  return new UsageError(`Unknown format ${format}. Use text or json with --format or WT_FORMAT.`);
130
39
  }
@@ -179,10 +88,29 @@ async function printCompletion(words) {
179
88
  if (completion !== undefined)
180
89
  process.stdout.write(formatCompletion(completion));
181
90
  }
182
- function printCompletionScript([shell, extra]) {
91
+ const scripts = {
92
+ 'completion': completionScripts,
93
+ 'shell-init': shellInitScripts,
94
+ };
95
+ function printScript(command, [shell, extra]) {
183
96
  if (extra !== undefined || !shells.includes(shell))
184
- throw new UsageError(usage('completion'));
185
- process.stdout.write(completionScripts[shell]);
97
+ throw new UsageError(usage(command));
98
+ process.stdout.write(scripts[command][shell]);
99
+ }
100
+ /** `wt cd` reaches the program only when the shell function from `wt shell-init` is not loaded. */
101
+ const cdNeedsShellFunction = 'wt cd needs the shell function from wt shell-init, because a program cannot change the directory of the shell that runs it. Add eval "$(wt shell-init zsh)" to ~/.zshrc or eval "$(wt shell-init bash)" to ~/.bashrc, or run cd "$(wt path <name>)".';
102
+ async function runDirect(action, args, workingDir) {
103
+ if (printsScript(action)) {
104
+ printScript(action, args);
105
+ return;
106
+ }
107
+ if (action === 'cd')
108
+ throw new UsageError(cdNeedsShellFunction);
109
+ const cwd = await workingDirectory(workingDir);
110
+ if (action === 'docker')
111
+ await dispatchDocker(args, cwd);
112
+ else
113
+ await printPath(args, cwd);
186
114
  }
187
115
  /**
188
116
  * The format of an error message. Errors are printed as JSON when the command
@@ -218,22 +146,18 @@ async function main(argv, signal, interrupt) {
218
146
  printHelp(helpFormat(ownArgs), action);
219
147
  return;
220
148
  }
221
- if (action === 'completion') {
222
- printCompletionScript(args);
149
+ if (isDirect(action)) {
150
+ await runDirect(action, args, workingDir);
223
151
  return;
224
152
  }
225
153
  const cwd = await workingDirectory(workingDir);
226
- if (action === 'docker') {
227
- await dispatchDocker(args, cwd);
228
- return;
229
- }
230
154
  const { format, filter, positionals, values } = parseCommandArgs(action, args);
231
155
  const result = await showOperation(`Running wt ${action}`, async (report, confirm) => withOperationSignal(signal, async () => runCommand(action, positionals, values, cwd, {
232
156
  format,
233
157
  filter,
234
158
  report,
235
- confirm,
236
- signal,
159
+ // Stop waiting for an answer when the command is interrupted.
160
+ confirm: confirm && (async (request) => abortable(confirm(request), signal)),
237
161
  })), interrupt);
238
162
  signal.throwIfAborted();
239
163
  process.stdout.write(`${renderResult(result, format)}\n`);
@@ -259,6 +183,13 @@ async function dispatchDocker(args, cwd) {
259
183
  process.exitCode = error.exitCode;
260
184
  }
261
185
  }
186
+ /** Prints the path of a worktree. It reads only state files and Git, so it shows no progress. */
187
+ async function printPath(args, cwd) {
188
+ const { format, positionals: [name] } = parseCommandArgs('path', args);
189
+ const target = await resolveEnvironmentName(name, cwd);
190
+ const json = { name: target, path: await environmentPath(target, cwd) };
191
+ process.stdout.write(`${renderResult({ text: json.path, json }, format)}\n`);
192
+ }
262
193
  /** Parses and validates arguments before anything runs, so a usage error never leaves a half-done operation. */
263
194
  function parseCommandArgs(action, args) {
264
195
  const { positionals, values } = parseArgs({
@@ -267,7 +198,9 @@ function parseCommandArgs(action, args) {
267
198
  options: parseOptions(action),
268
199
  });
269
200
  const [name, extra] = positionals;
270
- if (extra !== undefined || (action === 'ls' && name !== undefined) || ((action === 'create' || action === 'rm') && !name))
201
+ // A <name> in the usage is required, except that --repository of wt unlock replaces it.
202
+ const required = commands[action].usage.startsWith('<name>');
203
+ if (extra !== undefined || (action === 'ls' && name !== undefined) || (required && Boolean(name) === (values.repository === true)))
271
204
  throw new UsageError(usage(action));
272
205
  const format = values.format ?? requestedFormat([]) ?? 'text';
273
206
  if (!isFormat(format))
@@ -301,7 +234,7 @@ async function changedJson(name, action, cwd, fallback = {}) {
301
234
  };
302
235
  }
303
236
  }
304
- async function runCommand(action, [name], values, cwd, { format, filter, report, confirm, signal }) {
237
+ async function runCommand(action, [name], values, cwd, { format, filter, report, confirm }) {
305
238
  const describe = async (target, fallback) => format === 'json'
306
239
  ? changedJson(target, action, cwd, fallback)
307
240
  : undefined;
@@ -324,6 +257,8 @@ async function runCommand(action, [name], values, cwd, { format, filter, report,
324
257
  json: environmentListJson(states),
325
258
  };
326
259
  }
260
+ if (action === 'unlock')
261
+ return unlock(name, values, cwd, confirm);
327
262
  const target = await resolveEnvironmentName(name, cwd);
328
263
  if (action === 'info') {
329
264
  const state = await inspectEnvironment(target, cwd);
@@ -338,10 +273,7 @@ async function runCommand(action, [name], values, cwd, { format, filter, report,
338
273
  : resetEnvironment;
339
274
  if (values['dry-run'] === true)
340
275
  return dryRun(target, action, await preview(async (ask) => change(target, cwd, false, ask, report)));
341
- const confirmUntilInterrupted = confirm
342
- ? async (request) => abortable(confirm(request), signal)
343
- : undefined;
344
- const completed = await change(target, cwd, values.force === true, confirmUntilInterrupted, report);
276
+ const completed = await change(target, cwd, values.force === true, confirm, report);
345
277
  if (!completed) {
346
278
  return {
347
279
  text: action === 'rm'
@@ -365,22 +297,23 @@ async function runCommand(action, [name], values, cwd, { format, filter, report,
365
297
  json: await describe(target),
366
298
  };
367
299
  }
368
- /** Runs an operation up to its confirmation, declines it, and returns what it asked. */
369
- async function preview(operation) {
370
- let request;
371
- await operation(async (asked) => {
372
- request = asked;
373
- return false;
374
- });
375
- if (request === undefined)
376
- throw new Error('The operation finished without asking for confirmation.');
377
- return request;
300
+ /** Removes the lock of worktree `name`, or the repository lock for `--repository`, which comes without a name. */
301
+ async function unlock(name, values, cwd, confirm) {
302
+ if (values['dry-run'] === true)
303
+ return dryRun(name, 'unlock', await preview(async (ask) => unlockEnvironment(name, cwd, false, ask)));
304
+ const completed = await unlockEnvironment(name, cwd, values.force === true, confirm);
305
+ return {
306
+ text: completed
307
+ ? formatStatus(`Unlocked ${name ?? 'worktree operations'}`, 'success')
308
+ : 'Unlock cancelled',
309
+ json: { name: name ?? null, action: 'unlock', completed },
310
+ };
378
311
  }
379
312
  function dryRun(name, action, { title, details, note }) {
380
313
  return {
381
314
  text: formatDryRun({ title, details, note, action }),
382
315
  json: {
383
- name,
316
+ name: name ?? null,
384
317
  action,
385
318
  completed: false,
386
319
  dryRun: true,
@@ -412,7 +345,7 @@ process.stdout.on('error', (error) => {
412
345
  throw error;
413
346
  });
414
347
  try {
415
- await withOperationSignal(controller.signal, async () => main(process.argv.slice(2), controller.signal, interrupt));
348
+ await withOperationSignal(controller.signal, async () => withRepositoryCache(async () => main(process.argv.slice(2), controller.signal, interrupt)));
416
349
  }
417
350
  catch (error) {
418
351
  const reason = controller.signal.aborted ? controller.signal.reason : error;
@@ -1,4 +1,4 @@
1
- import { commandOptions, commands, extractWorkingDir, isCommand, shells, workingDirectory } from './cli-spec.js';
1
+ import { commandOptions, commands, extractWorkingDir, isCommand, printsScript, shells, workingDirectory } from './cli-spec.js';
2
2
  import { filterStates } from './list-filter.js';
3
3
  const none = { kind: 'values', values: [] };
4
4
  const workingDirOptions = ['-w', '--working-dir'];
@@ -29,7 +29,7 @@ function optionCandidates(command) {
29
29
  ? [
30
30
  { value: '--format', description: 'Output format' },
31
31
  ]
32
- : []), ...(command === 'completion'
32
+ : []), ...(printsScript(command)
33
33
  ? []
34
34
  : [
35
35
  { value: '--working-dir', description: 'Run as if wt was started in this directory' },
@@ -122,7 +122,7 @@ async function completeArguments(command, args, current, { cwd, sources }) {
122
122
  ? values({ value: '--', description: 'Compose arguments follow' })
123
123
  : none;
124
124
  }
125
- if (command === 'completion')
125
+ if (printsScript(command))
126
126
  return values(...shells.map(value => ({ value, description: '' })));
127
127
  return commands[command].environment !== false
128
128
  ? environmentCandidates(command, await cwd(), sources)
@@ -1,5 +1,5 @@
1
1
  import { z } from 'zod';
2
- import { configSchema } from './schema.js';
2
+ import { configSchema, hostKeys } from './schema.js';
3
3
  export const configSchemaUrl = 'https://unpkg.com/@joberthel/worktree@1/schema/wt.schema.json';
4
4
  // Sections accept an empty value such as `copy:`, which YAML reads as null.
5
5
  // The Zod schema allows that through a preprocess step, which JSON Schema cannot express.
@@ -31,7 +31,9 @@ export function configJsonSchema() {
31
31
  description: 'Configuration for wt, read from .wt.yml at the root of the source checkout.',
32
32
  ...schema,
33
33
  not: {
34
- required: ['host', 'worktrees'],
34
+ anyOf: Object.keys(hostKeys).map(key => ({
35
+ required: ['host', key],
36
+ })),
35
37
  },
36
38
  };
37
39
  }
@@ -25,12 +25,20 @@ const host = z.object({
25
25
  path: z.string().min(1).refine(value => !value.startsWith('~'), 'use an absolute path or a path relative to this checkout').meta({ description: 'Root of the host checkout, absolute or relative to this checkout.' }),
26
26
  from: z.string().min(1).optional().meta({ description: 'Host ref to check out. Defaults to the host checkout\'s HEAD.' }),
27
27
  }).strict();
28
+ /** Keys that a nested repository leaves to its host checkout's .wt.yml, with what they set. */
29
+ export const hostKeys = {
30
+ worktrees: 'the worktree directory',
31
+ volumes: 'how volumes are cloned',
32
+ };
28
33
  export const configSchema = z.object({
29
- host: host.optional().meta({ description: 'Runs this repository inside the Docker environment of a host repository. Cannot be combined with `worktrees`.' }),
34
+ host: host.optional().meta({ description: 'Runs this repository inside the Docker environment of a host repository. Cannot be combined with `worktrees` or `volumes`.' }),
30
35
  worktrees: z.preprocess(emptySection, z.object({
31
36
  directory: z.string().min(1).refine(value => !value.startsWith('~'), 'use an absolute path or a path relative to the main checkout').default('../worktrees').meta({ description: 'Where worktrees are created, absolute or relative to the main checkout.' }),
32
37
  }).strict().default({ directory: '../worktrees' })).meta({ description: 'Worktree placement.' }),
33
38
  copy: z.preprocess(emptySection, z.array(relativePath).default([])).meta({ description: 'Relative files and directories copied from the source checkout into each new worktree. Entries must not overlap.' }),
39
+ volumes: z.preprocess(emptySection, z.object({
40
+ pause_source: z.boolean().default(false).meta({ description: 'Pauses the running containers that mount a source volume while `wt create` and `wt reset` copy the volumes, for a crash-consistent copy. These services do not respond until the copy has finished.' }),
41
+ }).strict().default({ pause_source: false })).meta({ description: 'How the named Docker volumes of the source project are cloned.' }),
34
42
  hooks: z.preprocess(emptySection, z.object({
35
43
  worktree: hookGroup('Hooks that run in the new worktree.'),
36
44
  source: hookGroup('Hooks that run in the source checkout.'),
@@ -50,8 +58,12 @@ export const configSchema = z.object({
50
58
  }
51
59
  });
52
60
  export function parseConfig(input) {
53
- if (typeof input === 'object' && input !== null && 'host' in input && 'worktrees' in input)
54
- throw new Error('worktrees: cannot be combined with host; the host checkout\'s .wt.yml sets the worktree directory');
61
+ if (typeof input === 'object' && input !== null && 'host' in input) {
62
+ for (const [key, setting] of Object.entries(hostKeys)) {
63
+ if (key in input)
64
+ throw new Error(`${key}: cannot be combined with host; the host checkout's .wt.yml sets ${setting}`);
65
+ }
66
+ }
55
67
  const result = configSchema.safeParse(input ?? {});
56
68
  if (!result.success)
57
69
  throw new Error(z.prettifyError(result.error));