@joberthel/worktree 1.0.1 → 1.2.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
@@ -64,14 +64,14 @@ wt rm feature/login
64
64
  | Command | What it does |
65
65
  | --- | --- |
66
66
  | `wt create <name> [--branch <branch> \| --from <ref>]` | Create a worktree, branch, and isolated Compose environment. |
67
- | `wt ls` | List managed worktrees and their Docker status. |
68
- | `wt info [name]` | Show a worktree's branch, path, status, services and volumes. |
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
+ | `wt info [name]` | Show a worktree's branch, path, status, services, published ports, OrbStack domains and volumes. |
69
69
  | `wt start [name]` | Start its Compose services. |
70
70
  | `wt stop [name]` | Stop its Compose services. |
71
71
  | `wt restart [name]` | Restart its Compose services. |
72
72
  | `wt docker [name] -- <compose args...>` | Run a Docker Compose command in that worktree's project. |
73
- | `wt reset [name] [--force]` | Stop the environment, recopy configured paths, refresh cloned volumes, and start it again. |
74
- | `wt rm <name> [--force]` | Remove the managed environment and Git worktree while keeping its branch. |
73
+ | `wt reset [name] [--force \| --dry-run]` | Stop the environment, recopy configured paths, refresh cloned volumes, and start it again. |
74
+ | `wt rm <name> [--force \| --dry-run]` | Remove the managed environment and Git worktree while keeping its branch. |
75
75
  | `wt completion <zsh\|bash>` | Print a shell completion script. |
76
76
 
77
77
  Run them from any worktree of the repository. Commands with an optional `[name]` default to the worktree that contains the current directory.
@@ -84,9 +84,9 @@ wt docker -- exec app sh # from inside the feature/login worktree
84
84
  Two options are shared by the commands:
85
85
 
86
86
  - `-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 as JSON on stdout, for every command except `wt docker` and `wt completion`. See [JSON output](docs/json-output.md).
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).
88
88
 
89
- `wt reset` and `wt rm` ask before they change anything. Pass `--force` to skip the question, for example in scripts. See [Commands](docs/commands.md) for how branches are resolved, the confirmation prompt, and the progress view.
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.
90
90
 
91
91
  ### Shell completion
92
92
 
@@ -100,6 +100,16 @@ source <(wt completion zsh)
100
100
  eval "$(wt completion bash)"
101
101
  ```
102
102
 
103
+ ### Coding agents
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:
106
+
107
+ ```sh
108
+ npx skills add joberthel/worktree
109
+ ```
110
+
111
+ Agents work with the [JSON output](docs/json-output.md): results, published ports, dry runs of `rm` and `reset`, and errors with stable codes.
112
+
103
113
  ## Configuration
104
114
 
105
115
  `wt` works without a configuration file. Put `.wt.yml` at the root of your checkout to copy files into new worktrees, run setup hooks, or change the worktree directory:
@@ -129,12 +139,12 @@ Before you clone a database volume, stop writes to it or stop the source service
129
139
  - [Commands](docs/commands.md): branches, confirmations, progress, and shell completion in detail.
130
140
  - [Configuration](docs/configuration.md): `.wt.yml`, hooks, environment variables, and Docker volumes.
131
141
  - [Nested repositories](docs/nested-repositories.md): worktrees of a repository that lives inside another checkout.
132
- - [JSON output](docs/json-output.md): the output of `--format json` for scripts and coding agents.
142
+ - [JSON output](docs/json-output.md): the output of `--format json` for scripts and coding agents, including error codes.
133
143
  - [Troubleshooting](docs/troubleshooting.md): recovering from a failed create or reset and stale locks.
134
144
 
135
145
  ## Versioning
136
146
 
137
- `wt` follows [Semantic Versioning](https://semver.org). Breaking changes to the following need a new major version: commands and their options, the `.wt.yml` format, the environment variables passed to hooks, and the JSON output. The state files in the Git metadata are internal and may change in any release. See the [changelog](CHANGELOG.md) for what changed.
147
+ `wt` follows [Semantic Versioning](https://semver.org). Breaking changes to the following need a new major version: commands and their options, the `.wt.yml` format, the environment variables passed to hooks, and the JSON output including its error codes. The state files in the Git metadata are internal and may change in any release. See the [changelog](CHANGELOG.md) for what changed.
138
148
 
139
149
  ## Contributing
140
150
 
package/dist/cli-spec.js CHANGED
@@ -1,18 +1,32 @@
1
1
  import { stat } from 'node:fs/promises';
2
2
  import { resolve } from 'node:path';
3
3
  import process from 'node:process';
4
+ import { UsageError } from './errors.js';
5
+ const force = {
6
+ type: 'boolean',
7
+ description: 'Skip the confirmation',
8
+ };
9
+ const dryRun = {
10
+ type: 'boolean',
11
+ description: 'Show what would change, without changing anything',
12
+ };
4
13
  export const commands = {
5
14
  create: {
6
15
  usage: '<name> [--branch <branch> | --from <ref>]',
7
16
  summary: 'Create an environment',
8
- options: { branch: 'string', from: 'string' },
17
+ options: {
18
+ branch: { type: 'string', value: '<branch>', description: 'Check out an existing local or remote branch' },
19
+ from: { type: 'string', value: '<ref>', description: 'Create the new branch from this ref (default: HEAD)' },
20
+ },
9
21
  environment: false,
10
22
  shared: true,
11
23
  },
12
24
  ls: {
13
- usage: '',
25
+ usage: '[--filter <key=value>...]',
14
26
  summary: 'List managed environments',
15
- options: {},
27
+ options: {
28
+ filter: { type: 'strings', value: '<key=value>', description: 'Show only environments matching name=, branch= or state=; repeatable' },
29
+ },
16
30
  environment: false,
17
31
  shared: true,
18
32
  },
@@ -52,16 +66,16 @@ export const commands = {
52
66
  shared: false,
53
67
  },
54
68
  reset: {
55
- usage: '[name] [--force]',
69
+ usage: '[name] [--force | --dry-run]',
56
70
  summary: 'Refresh files and volumes from the source',
57
- options: { force: 'boolean' },
71
+ options: { force, 'dry-run': dryRun },
58
72
  environment: 'any',
59
73
  shared: true,
60
74
  },
61
75
  rm: {
62
- usage: '<name> [--force]',
76
+ usage: '<name> [--force | --dry-run]',
63
77
  summary: 'Remove an environment and keep its branch',
64
- options: { force: 'boolean' },
78
+ options: { force, 'dry-run': dryRun },
65
79
  environment: 'any',
66
80
  shared: true,
67
81
  },
@@ -77,11 +91,16 @@ export const shells = ['zsh', 'bash'];
77
91
  export function isCommand(value) {
78
92
  return Object.hasOwn(commands, value);
79
93
  }
94
+ /** Options of a command without the shared ones, as name and spec. */
95
+ export function commandOptions(command) {
96
+ const spec = commands[command];
97
+ return Object.entries(spec.options);
98
+ }
80
99
  /** Options of a command as `parseArgs` expects them, including `--format` where it applies. */
81
100
  export function parseOptions(command) {
82
101
  const spec = commands[command];
83
102
  return Object.fromEntries([
84
- ...Object.entries(spec.options),
103
+ ...commandOptions(command).map(([name, { type }]) => [name, type]),
85
104
  ...(spec.shared
86
105
  ? [
87
106
  ['format', 'string'],
@@ -89,10 +108,35 @@ export function parseOptions(command) {
89
108
  : []),
90
109
  ].map(([name, type]) => [
91
110
  name,
92
- { type },
111
+ type === 'strings'
112
+ ? { type: 'string', multiple: true }
113
+ : { type },
93
114
  ]));
94
115
  }
95
- export class UsageError extends Error {
116
+ export { UsageError } from './errors.js';
117
+ export const formats = ['text', 'json'];
118
+ export function isFormat(value) {
119
+ return formats.includes(value);
120
+ }
121
+ /**
122
+ * The output format asked for: the last `--format` before any `--`
123
+ * separator, or else the `WT_FORMAT` environment variable. It is not
124
+ * validated, so help and errors can use it before the arguments are parsed.
125
+ */
126
+ export function requestedFormat(args, env = process.env) {
127
+ let format;
128
+ for (let index = 0; index < args.length; index++) {
129
+ const token = args[index];
130
+ if (token === '--')
131
+ break;
132
+ if (token === '--format')
133
+ format = args[++index];
134
+ else if (token.startsWith('--format='))
135
+ format = token.slice('--format='.length);
136
+ }
137
+ return format ?? (env.WT_FORMAT === ''
138
+ ? undefined
139
+ : env.WT_FORMAT);
96
140
  }
97
141
  /**
98
142
  * Removes `-w`/`--working-dir` from the arguments. It may appear before or
package/dist/cli.js CHANGED
@@ -2,10 +2,13 @@
2
2
  import { readFileSync } from 'node:fs';
3
3
  import process from 'node:process';
4
4
  import { parseArgs } from 'node:util';
5
- import { commands, extractWorkingDir, isCommand, parseOptions, shells, UsageError, workingDirectory } from './cli-spec.js';
5
+ import { commandOptions, commands, extractWorkingDir, isCommand, isFormat, parseOptions, requestedFormat, shells, UsageError, workingDirectory } from './cli-spec.js';
6
6
  import { complete, completionScripts, formatCompletion } from './completion.js';
7
+ import { errorCode, WtError } from './errors.js';
7
8
  import { listBranches } from './git/repository.js';
9
+ import { hasListFilter, matchesListFilter, parseListFilter } from './list-filter.js';
8
10
  import { composeOperation, createEnvironment, inspectEnvironment, listEnvironmentNames, listEnvironments, removeEnvironment, resetEnvironment, resolveEnvironmentName, runningEnvironmentNames } from './operations/commands.js';
11
+ import { formatDryRun } from './operations/confirmation.js';
9
12
  import { ProcessFailure, withOperationSignal } from './operations/process.js';
10
13
  import { formatEnvironmentInfo } from './ui/environment-info.js';
11
14
  import { formatEnvironmentTable } from './ui/environment-table.js';
@@ -13,48 +16,153 @@ import { formatStatus } from './ui/format-status.js';
13
16
  import { environmentInfoJson, environmentListJson, formatJson } from './ui/json-output.js';
14
17
  import { showOperation } from './ui/show-operation.js';
15
18
  const description = 'Manage isolated Git worktrees with Docker Compose.';
16
- class Interrupted extends Error {
19
+ class Interrupted extends WtError {
17
20
  signal;
18
21
  constructor(signal) {
19
- super(`Interrupted by ${signal}.`);
22
+ super('interrupted', `Interrupted by ${signal}.`);
20
23
  this.signal = signal;
21
24
  }
22
25
  }
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
+ }
23
67
  function usage(command) {
24
68
  if (command !== undefined) {
25
- const { usage: args, summary, shared } = commands[command];
26
- const options = [
27
- ...(command === 'completion'
28
- ? []
29
- : [' -w, --working-dir <dir> Run as if wt was started in <dir>']),
30
- ...(shared
31
- ? [' --format <text|json> Output format (default: text)']
32
- : []),
33
- ];
69
+ const options = optionHelp(command).map(option => [
70
+ optionFlags(option),
71
+ option.description,
72
+ ]);
73
+ const width = Math.max(...options.map(([flags]) => flags.length));
34
74
  const optionList = options.length
35
- ? `\n\nOptions:\n${options.join('\n')}`
75
+ ? `\n\nOptions:\n${options.map(([flags, text]) => ` ${flags.padEnd(width)} ${text}`).join('\n')}`
36
76
  : '';
37
- return `Usage: ${`wt ${command} ${args}`.trimEnd()}\n\n${summary}${optionList}`;
77
+ return `Usage: ${commandUsage(command)}\n\n${commands[command].summary}${optionList}`;
38
78
  }
39
79
  const width = Math.max(...Object.keys(commands).map(name => name.length));
40
80
  const list = Object.entries(commands).map(([name, spec]) => ` ${name.padEnd(width)} ${spec.usage.padEnd(43)} ${spec.summary}`).join('\n');
41
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`;
42
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
+ function unknownFormat(format) {
129
+ return new UsageError(`Unknown format ${format}. Use text or json with --format or WT_FORMAT.`);
130
+ }
131
+ /** The validated format of help and version output. */
132
+ function helpFormat(args) {
133
+ const format = requestedFormat(args) ?? 'text';
134
+ if (!isFormat(format))
135
+ throw unknownFormat(format);
136
+ return format;
137
+ }
138
+ /** The arguments without `--format` and its value, so that help finds its topic. */
139
+ function withoutFormat(args) {
140
+ return args.filter((token, index) => token !== '--format' && args[index - 1] !== '--format' && !token.startsWith('--format='));
141
+ }
142
+ function printHelp(format, command) {
143
+ process.stdout.write(`${format === 'json'
144
+ ? formatJson(helpJson(command))
145
+ : usage(command)}\n`);
146
+ }
43
147
  /** Handles help and version, which need neither a command nor a repository. Returns whether it printed something. */
44
- function printBuiltin(command, [topic]) {
148
+ function printBuiltin(command, args) {
45
149
  if (command === undefined || command === '' || command === '-h' || command === '--help') {
46
- process.stdout.write(`${usage()}\n`);
150
+ printHelp(helpFormat(args));
47
151
  return true;
48
152
  }
49
153
  if (command === 'help') {
154
+ const [topic] = withoutFormat(args);
50
155
  if (topic !== undefined && !isCommand(topic))
51
156
  throw new UsageError(`Unknown command ${topic}. Run wt --help to see available commands.`);
52
- process.stdout.write(`${usage(topic)}\n`);
157
+ printHelp(helpFormat(args), topic);
53
158
  return true;
54
159
  }
55
160
  if (command === '-v' || command === '--version') {
56
- const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
57
- process.stdout.write(`${pkg.version}\n`);
161
+ process.stdout.write(`${helpFormat(args) === 'json'
162
+ ? formatJson({
163
+ version: version(),
164
+ })
165
+ : version()}\n`);
58
166
  return true;
59
167
  }
60
168
  return false;
@@ -76,6 +184,11 @@ function printCompletionScript([shell, extra]) {
76
184
  throw new UsageError(usage('completion'));
77
185
  process.stdout.write(completionScripts[shell]);
78
186
  }
187
+ /**
188
+ * The format of an error message. Errors are printed as JSON when the command
189
+ * line or `WT_FORMAT` asks for JSON, except for commands without JSON output.
190
+ */
191
+ let errorFormat = 'text';
79
192
  async function main(argv, signal, interrupt) {
80
193
  if (argv[0] === '__complete') {
81
194
  await printCompletion(argv[1] === '--'
@@ -83,10 +196,15 @@ async function main(argv, signal, interrupt) {
83
196
  : argv.slice(1));
84
197
  return;
85
198
  }
199
+ const requested = requestedFormat(argv);
200
+ if (requested !== undefined && isFormat(requested))
201
+ errorFormat = requested;
86
202
  const { rest, workingDir } = extractWorkingDir(argv[0] === '--'
87
203
  ? argv.slice(1)
88
204
  : argv);
89
205
  const [command, ...args] = rest;
206
+ if (isCommand(command) && !commands[command].shared)
207
+ errorFormat = 'text';
90
208
  if (printBuiltin(command, args))
91
209
  return;
92
210
  if (!isCommand(command))
@@ -97,7 +215,7 @@ async function main(argv, signal, interrupt) {
97
215
  ? args
98
216
  : args.slice(0, separator);
99
217
  if (ownArgs.includes('--help') || ownArgs.includes('-h')) {
100
- process.stdout.write(`${usage(action)}\n`);
218
+ printHelp(helpFormat(ownArgs), action);
101
219
  return;
102
220
  }
103
221
  if (action === 'completion') {
@@ -109,8 +227,10 @@ async function main(argv, signal, interrupt) {
109
227
  await dispatchDocker(args, cwd);
110
228
  return;
111
229
  }
112
- const { format, positionals, values } = parseCommandArgs(action, args);
230
+ const { format, filter, positionals, values } = parseCommandArgs(action, args);
113
231
  const result = await showOperation(`Running wt ${action}`, async (report, confirm) => withOperationSignal(signal, async () => runCommand(action, positionals, values, cwd, {
232
+ format,
233
+ filter,
114
234
  report,
115
235
  confirm,
116
236
  signal,
@@ -149,35 +269,58 @@ function parseCommandArgs(action, args) {
149
269
  const [name, extra] = positionals;
150
270
  if (extra !== undefined || (action === 'ls' && name !== undefined) || ((action === 'create' || action === 'rm') && !name))
151
271
  throw new UsageError(usage(action));
152
- const format = values.format ?? 'text';
272
+ const format = values.format ?? requestedFormat([]) ?? 'text';
153
273
  if (!isFormat(format))
154
- throw new UsageError(`Unknown format ${String(format)}. Use --format text or --format json.`);
155
- return { format, positionals, values };
274
+ throw unknownFormat(String(format));
275
+ if (values.force === true && values['dry-run'] === true)
276
+ throw new UsageError('--force and --dry-run cannot be used together.');
277
+ const filter = parseListFilter(Array.isArray(values.filter)
278
+ ? values.filter
279
+ : []);
280
+ return { format, filter, positionals, values };
156
281
  }
157
- function isFormat(value) {
158
- return value === 'text' || value === 'json';
282
+ /**
283
+ * The JSON result of a command that changed an environment: its name, the
284
+ * action, and the fields of `wt info`. When the environment cannot be
285
+ * inspected afterwards, only `fallback` follows, so a change that succeeded
286
+ * is never reported as a failure.
287
+ */
288
+ async function changedJson(name, action, cwd, fallback = {}) {
289
+ const head = { name, action, completed: true };
290
+ try {
291
+ const { name: _name, ...info } = environmentInfoJson(await inspectEnvironment(name, cwd));
292
+ return {
293
+ ...head,
294
+ ...info,
295
+ };
296
+ }
297
+ catch {
298
+ return {
299
+ ...head,
300
+ ...fallback,
301
+ };
302
+ }
159
303
  }
160
- async function runCommand(action, [name], values, cwd, { report, confirm, signal }) {
304
+ async function runCommand(action, [name], values, cwd, { format, filter, report, confirm, signal }) {
305
+ const describe = async (target, fallback) => format === 'json'
306
+ ? changedJson(target, action, cwd, fallback)
307
+ : undefined;
161
308
  if (action === 'create') {
162
309
  const options = { branch: values.branch, from: values.from };
163
310
  const result = await createEnvironment(name, options, cwd, report);
164
311
  return {
165
312
  text: formatStatus(`Created ${name} at ${result.path} (${result.projectName})`, 'success'),
166
- json: {
167
- name,
168
- action,
169
- completed: true,
170
- path: result.path,
171
- projectName: result.projectName,
172
- },
313
+ json: await describe(name, { path: result.path, projectName: result.projectName }),
173
314
  };
174
315
  }
175
316
  if (action === 'ls') {
176
- const states = await listEnvironments(cwd);
317
+ const states = (await listEnvironments(cwd)).filter(state => matchesListFilter(state, filter));
177
318
  return {
178
319
  text: states.length
179
320
  ? formatEnvironmentTable(states)
180
- : 'No managed worktrees. Create one with wt create <name>.',
321
+ : hasListFilter(filter)
322
+ ? 'No managed worktrees match the filter.'
323
+ : 'No managed worktrees. Create one with wt create <name>.',
181
324
  json: environmentListJson(states),
182
325
  };
183
326
  }
@@ -190,33 +333,59 @@ async function runCommand(action, [name], values, cwd, { report, confirm, signal
190
333
  };
191
334
  }
192
335
  if (action === 'rm' || action === 'reset') {
193
- const confirmUntilInterrupted = confirm
194
- ? async (request) => abortable(confirm(request), signal)
195
- : undefined;
196
336
  const change = action === 'rm'
197
337
  ? removeEnvironment
198
338
  : resetEnvironment;
339
+ if (values['dry-run'] === true)
340
+ 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;
199
344
  const completed = await change(target, cwd, values.force === true, confirmUntilInterrupted, report);
200
- const json = { name: target, action, completed };
201
345
  if (!completed) {
202
346
  return {
203
347
  text: action === 'rm'
204
348
  ? 'Removal cancelled'
205
349
  : 'Reset cancelled',
206
- json,
350
+ json: { name: target, action, completed },
207
351
  };
208
352
  }
209
353
  return {
210
354
  text: formatStatus(`${action === 'rm'
211
355
  ? 'Removed'
212
356
  : 'Reset'} ${target}`, 'success'),
213
- json,
357
+ json: action === 'rm'
358
+ ? { name: target, action, completed }
359
+ : await describe(target),
214
360
  };
215
361
  }
216
362
  await composeOperation(target, action, [], cwd, report);
217
363
  return {
218
364
  text: formatStatus(`${{ start: 'Started', stop: 'Stopped', restart: 'Restarted' }[action]} ${target}`, 'success'),
219
- json: { name: target, action, completed: true },
365
+ json: await describe(target),
366
+ };
367
+ }
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;
378
+ }
379
+ function dryRun(name, action, { title, details, note }) {
380
+ return {
381
+ text: formatDryRun({ title, details, note, action }),
382
+ json: {
383
+ name,
384
+ action,
385
+ completed: false,
386
+ dryRun: true,
387
+ plan: { title, details, note },
388
+ },
220
389
  };
221
390
  }
222
391
  async function abortable(work, signal) {
@@ -247,16 +416,23 @@ try {
247
416
  }
248
417
  catch (error) {
249
418
  const reason = controller.signal.aborted ? controller.signal.reason : error;
419
+ const code = errorCode(reason);
250
420
  process.exitCode = reason instanceof Interrupted
251
421
  ? reason.signal === 'SIGINT'
252
422
  ? 130
253
423
  : 143
254
- : reason instanceof UsageError || reason?.code?.startsWith('ERR_PARSE_ARGS')
424
+ : code === 'usage'
255
425
  ? 2
256
426
  : 1;
257
- process.stderr.write(`${formatStatus(reason instanceof Error
427
+ const message = reason instanceof Error
258
428
  ? reason.message
259
- : String(reason), 'error')}\n`);
429
+ : String(reason);
430
+ if (errorFormat === 'json') {
431
+ process.stdout.write(`${formatJson({
432
+ error: { code, message },
433
+ })}\n`);
434
+ }
435
+ process.stderr.write(`${formatStatus(message, 'error')}\n`);
260
436
  }
261
437
  finally {
262
438
  process.off('SIGINT', interrupt);
@@ -0,0 +1,64 @@
1
+ import process from 'node:process';
2
+ import { afterEach, beforeEach, vi } from 'vitest';
3
+ export function commandMocks() {
4
+ return {
5
+ composeOperation: vi.fn(),
6
+ createEnvironment: vi.fn(),
7
+ inspectEnvironment: vi.fn(),
8
+ listEnvironmentNames: vi.fn(),
9
+ listEnvironments: vi.fn(),
10
+ removeEnvironment: vi.fn(),
11
+ resetEnvironment: vi.fn(),
12
+ resolveEnvironmentName: vi.fn(),
13
+ runningEnvironmentNames: vi.fn(),
14
+ };
15
+ }
16
+ /** The `process.stdout` error listeners that were there before wt added its own. */
17
+ export const originalListeners = new Set(process.stdout.listeners('error'));
18
+ /**
19
+ * Registers hooks that load a fresh CLI for each test, record stdout and
20
+ * stderr, and restore the process afterwards. The returned spies are replaced
21
+ * before each test.
22
+ */
23
+ export function setupCli(mocks) {
24
+ const originalArgv = process.argv;
25
+ const io = {};
26
+ beforeEach(() => {
27
+ vi.resetModules();
28
+ vi.clearAllMocks();
29
+ io.stdout = vi.spyOn(process.stdout, 'write').mockImplementation(() => true);
30
+ io.stderr = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
31
+ mocks.resolveEnvironmentName.mockImplementation(async (name) => name ?? 'detected');
32
+ mocks.composeOperation.mockResolvedValue(undefined);
33
+ process.exitCode = 0;
34
+ });
35
+ afterEach(() => {
36
+ vi.restoreAllMocks();
37
+ vi.unstubAllEnvs();
38
+ process.argv = originalArgv;
39
+ process.exitCode = 0;
40
+ for (const listener of process.stdout.listeners('error')) {
41
+ if (!originalListeners.has(listener))
42
+ process.stdout.off('error', listener);
43
+ }
44
+ });
45
+ return io;
46
+ }
47
+ export async function cli(...args) {
48
+ process.argv = ['node', 'wt', ...args];
49
+ await import('../cli.js');
50
+ }
51
+ /** Runs the CLI a second time in the same test. */
52
+ export async function cliAgain(...args) {
53
+ vi.resetModules();
54
+ await cli(...args);
55
+ }
56
+ /** An error of the module graph the next `cli` call loads, so `instanceof` holds there. */
57
+ export async function codedError(code, message) {
58
+ const { WtError } = await import('../errors.js');
59
+ return new WtError(code, message);
60
+ }
61
+ /** The handler wt installed for `signal`, called directly so the test runner never sees the signal. */
62
+ export function signalHandler(signal) {
63
+ return process.listeners(signal).at(-1);
64
+ }