@joberthel/worktree 1.1.0 → 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
@@ -65,13 +65,13 @@ wt rm feature/login
65
65
  | --- | --- |
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
- | `wt info [name]` | Show a worktree's branch, path, status, services, OrbStack domains and volumes. |
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,10 +1,15 @@
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';
4
5
  const force = {
5
6
  type: 'boolean',
6
7
  description: 'Skip the confirmation',
7
8
  };
9
+ const dryRun = {
10
+ type: 'boolean',
11
+ description: 'Show what would change, without changing anything',
12
+ };
8
13
  export const commands = {
9
14
  create: {
10
15
  usage: '<name> [--branch <branch> | --from <ref>]',
@@ -61,16 +66,16 @@ export const commands = {
61
66
  shared: false,
62
67
  },
63
68
  reset: {
64
- usage: '[name] [--force]',
69
+ usage: '[name] [--force | --dry-run]',
65
70
  summary: 'Refresh files and volumes from the source',
66
- options: { force },
71
+ options: { force, 'dry-run': dryRun },
67
72
  environment: 'any',
68
73
  shared: true,
69
74
  },
70
75
  rm: {
71
- usage: '<name> [--force]',
76
+ usage: '<name> [--force | --dry-run]',
72
77
  summary: 'Remove an environment and keep its branch',
73
- options: { force },
78
+ options: { force, 'dry-run': dryRun },
74
79
  environment: 'any',
75
80
  shared: true,
76
81
  },
@@ -108,7 +113,30 @@ export function parseOptions(command) {
108
113
  : { type },
109
114
  ]));
110
115
  }
111
- 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);
112
140
  }
113
141
  /**
114
142
  * Removes `-w`/`--working-dir` from the arguments. It may appear before or
package/dist/cli.js CHANGED
@@ -2,11 +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 { commandOptions, 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';
8
9
  import { hasListFilter, matchesListFilter, parseListFilter } from './list-filter.js';
9
10
  import { composeOperation, createEnvironment, inspectEnvironment, listEnvironmentNames, listEnvironments, removeEnvironment, resetEnvironment, resolveEnvironmentName, runningEnvironmentNames } from './operations/commands.js';
11
+ import { formatDryRun } from './operations/confirmation.js';
10
12
  import { ProcessFailure, withOperationSignal } from './operations/process.js';
11
13
  import { formatEnvironmentInfo } from './ui/environment-info.js';
12
14
  import { formatEnvironmentTable } from './ui/environment-table.js';
@@ -14,59 +16,153 @@ import { formatStatus } from './ui/format-status.js';
14
16
  import { environmentInfoJson, environmentListJson, formatJson } from './ui/json-output.js';
15
17
  import { showOperation } from './ui/show-operation.js';
16
18
  const description = 'Manage isolated Git worktrees with Docker Compose.';
17
- class Interrupted extends Error {
19
+ class Interrupted extends WtError {
18
20
  signal;
19
21
  constructor(signal) {
20
- super(`Interrupted by ${signal}.`);
22
+ super('interrupted', `Interrupted by ${signal}.`);
21
23
  this.signal = signal;
22
24
  }
23
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
+ }
24
67
  function usage(command) {
25
68
  if (command !== undefined) {
26
- const { usage: args, summary, shared } = commands[command];
27
- const options = [
28
- ...commandOptions(command).map(([name, { value, description }]) => [
29
- value === undefined
30
- ? `--${name}`
31
- : `--${name} ${value}`,
32
- description,
33
- ]),
34
- ...(command === 'completion'
35
- ? []
36
- : [
37
- ['-w, --working-dir <dir>', 'Run as if wt was started in <dir>'],
38
- ]),
39
- ...(shared
40
- ? [
41
- ['--format <text|json>', 'Output format (default: text)'],
42
- ]
43
- : []),
44
- ];
69
+ const options = optionHelp(command).map(option => [
70
+ optionFlags(option),
71
+ option.description,
72
+ ]);
45
73
  const width = Math.max(...options.map(([flags]) => flags.length));
46
74
  const optionList = options.length
47
75
  ? `\n\nOptions:\n${options.map(([flags, text]) => ` ${flags.padEnd(width)} ${text}`).join('\n')}`
48
76
  : '';
49
- return `Usage: ${`wt ${command} ${args}`.trimEnd()}\n\n${summary}${optionList}`;
77
+ return `Usage: ${commandUsage(command)}\n\n${commands[command].summary}${optionList}`;
50
78
  }
51
79
  const width = Math.max(...Object.keys(commands).map(name => name.length));
52
80
  const list = Object.entries(commands).map(([name, spec]) => ` ${name.padEnd(width)} ${spec.usage.padEnd(43)} ${spec.summary}`).join('\n');
53
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`;
54
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
+ }
55
147
  /** Handles help and version, which need neither a command nor a repository. Returns whether it printed something. */
56
- function printBuiltin(command, [topic]) {
148
+ function printBuiltin(command, args) {
57
149
  if (command === undefined || command === '' || command === '-h' || command === '--help') {
58
- process.stdout.write(`${usage()}\n`);
150
+ printHelp(helpFormat(args));
59
151
  return true;
60
152
  }
61
153
  if (command === 'help') {
154
+ const [topic] = withoutFormat(args);
62
155
  if (topic !== undefined && !isCommand(topic))
63
156
  throw new UsageError(`Unknown command ${topic}. Run wt --help to see available commands.`);
64
- process.stdout.write(`${usage(topic)}\n`);
157
+ printHelp(helpFormat(args), topic);
65
158
  return true;
66
159
  }
67
160
  if (command === '-v' || command === '--version') {
68
- const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
69
- process.stdout.write(`${pkg.version}\n`);
161
+ process.stdout.write(`${helpFormat(args) === 'json'
162
+ ? formatJson({
163
+ version: version(),
164
+ })
165
+ : version()}\n`);
70
166
  return true;
71
167
  }
72
168
  return false;
@@ -88,6 +184,11 @@ function printCompletionScript([shell, extra]) {
88
184
  throw new UsageError(usage('completion'));
89
185
  process.stdout.write(completionScripts[shell]);
90
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';
91
192
  async function main(argv, signal, interrupt) {
92
193
  if (argv[0] === '__complete') {
93
194
  await printCompletion(argv[1] === '--'
@@ -95,10 +196,15 @@ async function main(argv, signal, interrupt) {
95
196
  : argv.slice(1));
96
197
  return;
97
198
  }
199
+ const requested = requestedFormat(argv);
200
+ if (requested !== undefined && isFormat(requested))
201
+ errorFormat = requested;
98
202
  const { rest, workingDir } = extractWorkingDir(argv[0] === '--'
99
203
  ? argv.slice(1)
100
204
  : argv);
101
205
  const [command, ...args] = rest;
206
+ if (isCommand(command) && !commands[command].shared)
207
+ errorFormat = 'text';
102
208
  if (printBuiltin(command, args))
103
209
  return;
104
210
  if (!isCommand(command))
@@ -109,7 +215,7 @@ async function main(argv, signal, interrupt) {
109
215
  ? args
110
216
  : args.slice(0, separator);
111
217
  if (ownArgs.includes('--help') || ownArgs.includes('-h')) {
112
- process.stdout.write(`${usage(action)}\n`);
218
+ printHelp(helpFormat(ownArgs), action);
113
219
  return;
114
220
  }
115
221
  if (action === 'completion') {
@@ -123,6 +229,7 @@ async function main(argv, signal, interrupt) {
123
229
  }
124
230
  const { format, filter, positionals, values } = parseCommandArgs(action, args);
125
231
  const result = await showOperation(`Running wt ${action}`, async (report, confirm) => withOperationSignal(signal, async () => runCommand(action, positionals, values, cwd, {
232
+ format,
126
233
  filter,
127
234
  report,
128
235
  confirm,
@@ -162,30 +269,48 @@ function parseCommandArgs(action, args) {
162
269
  const [name, extra] = positionals;
163
270
  if (extra !== undefined || (action === 'ls' && name !== undefined) || ((action === 'create' || action === 'rm') && !name))
164
271
  throw new UsageError(usage(action));
165
- const format = values.format ?? 'text';
272
+ const format = values.format ?? requestedFormat([]) ?? 'text';
166
273
  if (!isFormat(format))
167
- throw new UsageError(`Unknown format ${String(format)}. Use --format text or --format json.`);
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.');
168
277
  const filter = parseListFilter(Array.isArray(values.filter)
169
278
  ? values.filter
170
279
  : []);
171
280
  return { format, filter, positionals, values };
172
281
  }
173
- function isFormat(value) {
174
- 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
+ }
175
303
  }
176
- async function runCommand(action, [name], values, cwd, { filter, 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;
177
308
  if (action === 'create') {
178
309
  const options = { branch: values.branch, from: values.from };
179
310
  const result = await createEnvironment(name, options, cwd, report);
180
311
  return {
181
312
  text: formatStatus(`Created ${name} at ${result.path} (${result.projectName})`, 'success'),
182
- json: {
183
- name,
184
- action,
185
- completed: true,
186
- path: result.path,
187
- projectName: result.projectName,
188
- },
313
+ json: await describe(name, { path: result.path, projectName: result.projectName }),
189
314
  };
190
315
  }
191
316
  if (action === 'ls') {
@@ -208,33 +333,59 @@ async function runCommand(action, [name], values, cwd, { filter, report, confirm
208
333
  };
209
334
  }
210
335
  if (action === 'rm' || action === 'reset') {
211
- const confirmUntilInterrupted = confirm
212
- ? async (request) => abortable(confirm(request), signal)
213
- : undefined;
214
336
  const change = action === 'rm'
215
337
  ? removeEnvironment
216
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;
217
344
  const completed = await change(target, cwd, values.force === true, confirmUntilInterrupted, report);
218
- const json = { name: target, action, completed };
219
345
  if (!completed) {
220
346
  return {
221
347
  text: action === 'rm'
222
348
  ? 'Removal cancelled'
223
349
  : 'Reset cancelled',
224
- json,
350
+ json: { name: target, action, completed },
225
351
  };
226
352
  }
227
353
  return {
228
354
  text: formatStatus(`${action === 'rm'
229
355
  ? 'Removed'
230
356
  : 'Reset'} ${target}`, 'success'),
231
- json,
357
+ json: action === 'rm'
358
+ ? { name: target, action, completed }
359
+ : await describe(target),
232
360
  };
233
361
  }
234
362
  await composeOperation(target, action, [], cwd, report);
235
363
  return {
236
364
  text: formatStatus(`${{ start: 'Started', stop: 'Stopped', restart: 'Restarted' }[action]} ${target}`, 'success'),
237
- 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
+ },
238
389
  };
239
390
  }
240
391
  async function abortable(work, signal) {
@@ -265,16 +416,23 @@ try {
265
416
  }
266
417
  catch (error) {
267
418
  const reason = controller.signal.aborted ? controller.signal.reason : error;
419
+ const code = errorCode(reason);
268
420
  process.exitCode = reason instanceof Interrupted
269
421
  ? reason.signal === 'SIGINT'
270
422
  ? 130
271
423
  : 143
272
- : reason instanceof UsageError || reason?.code?.startsWith('ERR_PARSE_ARGS')
424
+ : code === 'usage'
273
425
  ? 2
274
426
  : 1;
275
- process.stderr.write(`${formatStatus(reason instanceof Error
427
+ const message = reason instanceof Error
276
428
  ? reason.message
277
- : 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`);
278
436
  }
279
437
  finally {
280
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
+ }
@@ -1,5 +1,6 @@
1
1
  import { access, readFile } from 'node:fs/promises';
2
2
  import { parse } from 'yaml';
3
+ import { WtError } from '../errors.js';
3
4
  import { parseConfig } from './schema.js';
4
5
  export async function configPath(root, fallback) {
5
6
  for (const directory of new Set([root, fallback])) {
@@ -26,7 +27,7 @@ export async function loadConfig(root, path) {
26
27
  if (error.code === 'ENOENT') {
27
28
  if (path === undefined)
28
29
  return parseConfig({});
29
- throw new Error(`Configuration file ${file} is missing. Restore it before retrying.`, { cause: error });
30
+ throw new WtError('invalid_config', `Configuration file ${file} is missing. Restore it before retrying.`, { cause: error });
30
31
  }
31
32
  throw error;
32
33
  }
@@ -35,12 +36,12 @@ export async function loadConfig(root, path) {
35
36
  input = parse(source, { uniqueKeys: true, strict: true });
36
37
  }
37
38
  catch (error) {
38
- throw new Error(`${file}: invalid YAML syntax: ${error.message}`);
39
+ throw new WtError('invalid_config', `${file}: invalid YAML syntax: ${error.message}`);
39
40
  }
40
41
  try {
41
42
  return parseConfig(input);
42
43
  }
43
44
  catch (error) {
44
- throw new Error(`${file}: ${error.message}`);
45
+ throw new WtError('invalid_config', `${file}: ${error.message}`);
45
46
  }
46
47
  }
@@ -2,6 +2,7 @@ import { createHash, randomUUID } from 'node:crypto';
2
2
  import { access, realpath } from 'node:fs/promises';
3
3
  import { basename, isAbsolute, join, relative, resolve, sep } from 'node:path';
4
4
  import process from 'node:process';
5
+ import { WtError } from '../errors.js';
5
6
  import { repositoryInfo } from '../git/repository.js';
6
7
  import { run } from '../operations/process.js';
7
8
  import { writeAtomicFile } from '../state/atomic-file.js';
@@ -85,7 +86,7 @@ async function composeContainerLabels(worktree) {
85
86
  }
86
87
  function singleComposeSource(projects) {
87
88
  if (projects.size !== 1)
88
- throw new Error(projects.size ? 'Multiple Compose projects match this worktree; stop or disambiguate them.' : 'No Compose project found for this worktree. Start it with the Git checkout root as the Compose project directory.');
89
+ throw new WtError('no_compose_project', projects.size ? 'Multiple Compose projects match this worktree; stop or disambiguate them.' : 'No Compose project found for this worktree. Start it with the Git checkout root as the Compose project directory.');
89
90
  const [source] = projects.values();
90
91
  if (source.files.length === 0)
91
92
  throw new Error(`No Compose config files found for project ${source.project}.`);
@@ -0,0 +1,43 @@
1
+ const publishedPattern = /^(.*):(\d+)(?:-(\d+))?->(\d+)(?:-(\d+))?\/(\w+)$/;
2
+ /**
3
+ * Parses the `{{.Ports}}` column of `docker ps`, such as
4
+ * `0.0.0.0:55001->80/tcp, [::]:55001->80/tcp, 9000/tcp`. Ports that are only
5
+ * exposed are left out, ranges are expanded, and a port bound to both IPv4 and
6
+ * IPv6 is listed once.
7
+ */
8
+ export function parsePorts(value) {
9
+ const ports = new Map();
10
+ for (const entry of value.split(',')) {
11
+ const match = publishedPattern.exec(entry.trim());
12
+ if (match === null)
13
+ continue;
14
+ const [, ip, hostStart, hostEnd = hostStart, containerStart, containerEnd = containerStart, protocol] = match;
15
+ const hostIp = ip.replace(/^\[(.*)\]$/, '$1');
16
+ const count = Number(hostEnd) - Number(hostStart);
17
+ if (count !== Number(containerEnd) - Number(containerStart))
18
+ continue;
19
+ for (let offset = 0; offset <= count; offset++) {
20
+ const port = {
21
+ hostIp,
22
+ hostPort: Number(hostStart) + offset,
23
+ containerPort: Number(containerStart) + offset,
24
+ protocol,
25
+ };
26
+ const key = `${port.hostPort}:${port.containerPort}/${protocol}`;
27
+ if (!ports.has(key))
28
+ ports.set(key, port);
29
+ }
30
+ }
31
+ return [
32
+ ...ports.values(),
33
+ ].sort((a, b) => a.containerPort - b.containerPort || a.hostPort - b.hostPort || a.protocol.localeCompare(b.protocol));
34
+ }
35
+ const wildcards = new Set(['0.0.0.0', '::', '']);
36
+ /** Where to reach a published port from the host, such as `localhost:55001`. */
37
+ export function portAddress({ hostIp, hostPort }) {
38
+ if (wildcards.has(hostIp))
39
+ return `localhost:${hostPort}`;
40
+ return hostIp.includes(':')
41
+ ? `[${hostIp}]:${hostPort}`
42
+ : `${hostIp}:${hostPort}`;
43
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,66 @@
1
+ /*
2
+ * Errors with a stable code. `--format json` prints the code, so scripts and
3
+ * coding agents can react to a failure without matching its message. The
4
+ * codes are part of the public interface; messages may change in any release.
5
+ */
6
+ export const errorCodes = [
7
+ /** The command line is invalid. Exits with status 2. */
8
+ 'usage',
9
+ /** The worktree name given to `wt create` is not allowed. */
10
+ 'invalid_name',
11
+ /** No managed worktree has the given name. */
12
+ 'not_found',
13
+ /** No name was given and the current directory is not inside a managed worktree. */
14
+ 'not_in_worktree',
15
+ /** The worktree, its directory or its Compose project exists already. */
16
+ 'already_exists',
17
+ /** `wt create` would create a branch that exists already; pass `--branch`. */
18
+ 'branch_exists',
19
+ /** The branch given to `--branch` exists neither locally nor on a remote. */
20
+ 'branch_not_found',
21
+ /** The branch given to `--branch` exists on several remotes. */
22
+ 'branch_ambiguous',
23
+ /** The worktree is not ready; run `wt reset` or `wt rm`. */
24
+ 'not_ready',
25
+ /** `wt create` made the worktree but its setup failed; run `wt reset` or `wt rm`. */
26
+ 'setup_failed',
27
+ /** `wt rm` or `wt reset` needs `--force` without a terminal. */
28
+ 'confirmation_required',
29
+ /** The current directory is inside the worktree that would be removed. */
30
+ 'inside_worktree',
31
+ /** Another wt command holds the repository lock. */
32
+ 'locked',
33
+ /** The worktree changed while the command waited; retry it. */
34
+ 'changed',
35
+ /** No single running Compose project belongs to the source checkout. */
36
+ 'no_compose_project',
37
+ /** `.wt.yml` is missing, not valid YAML, or has invalid settings. */
38
+ 'invalid_config',
39
+ /** The directory is not inside a Git checkout. */
40
+ 'not_a_repository',
41
+ /** Git or Docker exited with an error. */
42
+ 'command_failed',
43
+ /** The command was interrupted by SIGINT or SIGTERM. */
44
+ 'interrupted',
45
+ /** Any other failure. */
46
+ 'error',
47
+ ];
48
+ export class WtError extends Error {
49
+ code;
50
+ constructor(code, message, options) {
51
+ super(message, options);
52
+ this.code = code;
53
+ }
54
+ }
55
+ export class UsageError extends WtError {
56
+ constructor(message) {
57
+ super('usage', message);
58
+ }
59
+ }
60
+ export function errorCode(error) {
61
+ if (error instanceof WtError)
62
+ return error.code;
63
+ if (error?.code?.startsWith('ERR_PARSE_ARGS'))
64
+ return 'usage';
65
+ return 'error';
66
+ }
@@ -1,6 +1,7 @@
1
1
  import { realpath } from 'node:fs/promises';
2
2
  import { dirname, isAbsolute, resolve } from 'node:path';
3
3
  import process from 'node:process';
4
+ import { WtError } from '../errors.js';
4
5
  import { checkInterrupted, run } from '../operations/process.js';
5
6
  import { StateStore } from '../state/store.js';
6
7
  const gitLocalVariables = [
@@ -47,7 +48,7 @@ export async function listBranches(cwd) {
47
48
  export async function repositoryInfo(cwd) {
48
49
  const common = await git(['rev-parse', '--git-common-dir'], cwd).catch((error) => {
49
50
  if (error instanceof Error && /not a git repository/i.test(error.message))
50
- throw new Error('Run wt from a Git checkout or its repository directory.', { cause: error });
51
+ throw new WtError('not_a_repository', 'Run wt from a Git checkout or its repository directory.', { cause: error });
51
52
  throw error;
52
53
  });
53
54
  const gitCommonDir = isAbsolute(common)
@@ -179,7 +180,7 @@ export async function resolveExistingBranch(name, cwd) {
179
180
  }));
180
181
  const found = matches.filter(match => match.tracked || match.tip !== undefined);
181
182
  if (found.length > 1)
182
- throw new Error(`Branch ${name} exists on several remotes; use --branch with one of ${found.map(({ candidate }) => `${candidate.remote}/${candidate.branch}`).join(', ')}.`);
183
+ throw new WtError('branch_ambiguous', `Branch ${name} exists on several remotes; use --branch with one of ${found.map(({ candidate }) => `${candidate.remote}/${candidate.branch}`).join(', ')}.`);
183
184
  if (found.length === 1) {
184
185
  const [{ candidate, tip }] = found;
185
186
  if (tip !== undefined)
@@ -189,7 +190,7 @@ export async function resolveExistingBranch(name, cwd) {
189
190
  : { branch: candidate.branch, track: `refs/remotes/${candidate.remote}/${candidate.branch}` };
190
191
  }
191
192
  }
192
- throw new Error(`Branch ${name} was not found locally or on a reachable remote.`);
193
+ throw new WtError('branch_not_found', `Branch ${name} was not found locally or on a reachable remote.`);
193
194
  }
194
195
  export function resolveWorktreeDirectory(directory, repositoryRoot) {
195
196
  return resolve(repositoryRoot, directory);
@@ -3,6 +3,7 @@ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'nod
3
3
  import process from 'node:process';
4
4
  import { loadConfig } from '../config/load.js';
5
5
  import { worktreeResourceName } from '../docker/compose.js';
6
+ import { WtError } from '../errors.js';
6
7
  import { git, repositoryInfo } from '../git/repository.js';
7
8
  import { AttachedStore, StateStore } from '../state/store.js';
8
9
  import { copyConfiguredPaths } from './copy-paths.js';
@@ -71,7 +72,7 @@ export async function createAttached(name, options, { repository, config, config
71
72
  const { host, mountPath } = await locateHost(root, config.host.path, progress);
72
73
  const attached = new AttachedStore(gitCommonDir);
73
74
  if ((await attached.list()).some(item => item.name.toLowerCase() === name.toLowerCase()))
74
- throw new Error(`Worktree ${name} is already managed.`);
75
+ throw new WtError('already_exists', `Worktree ${name} is already managed.`);
75
76
  const plan = await planCheckout(name, options, root, progress);
76
77
  await validateHookRevision(config, root, plan.revision);
77
78
  await validateSourceHooks(config.hooks, root);
@@ -177,9 +178,9 @@ export async function removeAttached({ state, attached, store }, cwd, force = fa
177
178
  const outer = await realpath(host?.path ?? state.path).catch(() => resolve(host?.path ?? state.path));
178
179
  const here = await realpath(cwd);
179
180
  if (here === outer || isInside(outer, here))
180
- throw new Error(`Current directory is inside ${outer}; change directory before removing it.`);
181
- if (!force && !process.stdin.isTTY)
182
- throw new Error('wt rm requires an interactive terminal or --force.');
181
+ throw new WtError('inside_worktree', `Current directory is inside ${outer}; change directory before removing it.`);
182
+ if (!force && confirm === undefined && !process.stdin.isTTY)
183
+ throw new WtError('confirmation_required', 'wt rm requires an interactive terminal or --force. Run it with --dry-run to see what it removes.');
183
184
  if (!force) {
184
185
  const changes = await uncommittedChanges(state.path);
185
186
  const request = {
@@ -243,8 +244,8 @@ export async function resetAttached({ state, attached, store }, force = false, c
243
244
  const config = await loadConfig(sourceRoot, state.configurationPath);
244
245
  const { sourceRoot: hostSource, config: hostConfig } = await prepareReset(host, state.host.repositoryRoot, name);
245
246
  await validateCopyAndHooks(config, sourceRoot, state.path);
246
- if (!force && !process.stdin.isTTY)
247
- throw new Error('wt reset requires an interactive terminal or --force.');
247
+ if (!force && confirm === undefined && !process.stdin.isTTY)
248
+ throw new WtError('confirmation_required', 'wt reset requires an interactive terminal or --force. Run it with --dry-run to see what it replaces.');
248
249
  if (!force) {
249
250
  const request = {
250
251
  title: `Reset worktree ${name}?`,
@@ -267,7 +268,7 @@ export async function resetAttached({ state, attached, store }, force = false, c
267
268
  await checkUnchanged(attached, state);
268
269
  await checkUnchanged(hostStore, host);
269
270
  if (host.status === 'removing' || state.status === 'removing')
270
- throw new Error(`Removal of ${name} is incomplete. Retry wt rm ${name}.`);
271
+ throw new WtError('not_ready', `Removal of ${name} is incomplete. Retry wt rm ${name}.`);
271
272
  await attached.save({ ...state, status: 'resetting' });
272
273
  try {
273
274
  if (config.copy.length > 0)
@@ -1,6 +1,7 @@
1
1
  import { realpath } from 'node:fs/promises';
2
2
  import { resolve } from 'node:path';
3
3
  import { projectUrls } from '../docker/orbstack.js';
4
+ import { WtError } from '../errors.js';
4
5
  import { repositoryInfo } from '../git/repository.js';
5
6
  import { AttachedStore, StateStore } from '../state/store.js';
6
7
  import { attachedHost, createAttached, removeAttached, resetAttached } from './attached.js';
@@ -143,7 +144,7 @@ export async function composeOperation(name, action, args, cwd, progress) {
143
144
  return manage.composeOperation(name, action, args, cwd, progress);
144
145
  const { state } = target;
145
146
  if (state.status !== 'ready' && action !== 'docker')
146
- throw new Error(`Worktree ${name} is ${state.status}. Run wt reset ${name} to retry setup or wt rm ${name} to remove it.`);
147
+ throw new WtError('not_ready', `Worktree ${name} is ${state.status}. Run wt reset ${name} to retry setup or wt rm ${name} to remove it.`);
147
148
  const hostStore = new StateStore(state.host.gitCommonDir);
148
149
  const unlock = action === 'docker'
149
150
  ? undefined
@@ -5,11 +5,23 @@ export function detailRows(details) {
5
5
  value: detail.value,
6
6
  }));
7
7
  }
8
- export function formatConfirmation(request) {
8
+ function formatRequest(request) {
9
9
  return [
10
10
  request.title,
11
11
  ...detailRows(request.details).map(row => ` ${row.label} ${row.value}`),
12
12
  request.note,
13
+ ];
14
+ }
15
+ export function formatConfirmation(request) {
16
+ return [
17
+ ...formatRequest(request),
13
18
  `${request.action}? [y/N] `,
14
19
  ].join('\n');
15
20
  }
21
+ /** What `--dry-run` prints: the confirmation that would be asked, without the question. */
22
+ export function formatDryRun(request) {
23
+ return [
24
+ ...formatRequest(request),
25
+ 'Dry run: nothing was changed.',
26
+ ].join('\n');
27
+ }
@@ -2,6 +2,7 @@ import { access, lstat, mkdir, realpath } from 'node:fs/promises';
2
2
  import { isAbsolute, relative, resolve, sep } from 'node:path';
3
3
  import { configPath, loadConfig } from '../config/load.js';
4
4
  import { cloneNamedVolumes, composeFilesForWorktree, discoverComposeSource, overridePath, prepareVolumeCopy, repositoryIdentifier, resolveSourceVolumes, worktreeResourceName, writeVolumeOverride } from '../docker/compose.js';
5
+ import { UsageError, WtError } from '../errors.js';
5
6
  import { git, refExists, repositoryInfo, resolveExistingBranch, resolveWorktreeDirectory } from '../git/repository.js';
6
7
  import { StateStore } from '../state/store.js';
7
8
  import { copyConfiguredPaths } from './copy-paths.js';
@@ -11,11 +12,11 @@ import { runStep } from './progress.js';
11
12
  const namePattern = /^\w[\w.-]*(?:\/\w[\w.-]*)*$/;
12
13
  export function validateCreateInput(name, options) {
13
14
  if (!namePattern.test(name))
14
- throw new Error('Name must be a slash-separated path of letters, digits, dots, underscores, or hyphens.');
15
+ throw new WtError('invalid_name', 'Name must be a slash-separated path of letters, digits, dots, underscores, or hyphens.');
15
16
  if (name.split('/').some(segment => segment.includes('..') || segment.endsWith('.') || segment.endsWith('.lock')))
16
- throw new Error('Name segments must not contain .. or end with . or .lock.');
17
+ throw new WtError('invalid_name', 'Name segments must not contain .. or end with . or .lock.');
17
18
  if (options.branch !== undefined && options.from !== undefined)
18
- throw new Error('--branch and --from cannot be used together.');
19
+ throw new UsageError('--branch and --from cannot be used together.');
19
20
  }
20
21
  export async function createEnvironment(name, options, cwd, progress) {
21
22
  return withCreateContext(name, options, cwd, progress, async (repository, store, loaded) => createEnvironmentLocked(name, options, repository, store, { ...loaded, progress }));
@@ -113,7 +114,7 @@ export async function createEnvironmentLocked(name, options, { root, gitCommonDi
113
114
  if (worktreeMade || await isRegistered(target, root)) {
114
115
  await store.save({ ...state, status: 'failed', error: error.message });
115
116
  const retry = nested?.retryName ?? name;
116
- throw new Error(`${error.message}\nRun wt reset ${retry} to retry setup or wt rm ${retry} to discard the worktree.`, { cause: error });
117
+ throw new WtError('setup_failed', `${error.message}\nRun wt reset ${retry} to retry setup or wt rm ${retry} to discard the worktree.`, { cause: error });
117
118
  }
118
119
  throw error;
119
120
  }
@@ -121,7 +122,7 @@ export async function createEnvironmentLocked(name, options, { root, gitCommonDi
121
122
  async function planTarget(name, config, gitCommonDir, repositoryRoot) {
122
123
  const resourceName = worktreeResourceName(name);
123
124
  if (!resourceName)
124
- throw new Error('Worktree name must contain a letter, digit, or underscore.');
125
+ throw new WtError('invalid_name', 'Worktree name must contain a letter, digit, or underscore.');
125
126
  const directory = await canonicalDirectory(resolveWorktreeDirectory(config.worktrees.directory, repositoryRoot));
126
127
  const repoId = repositoryIdentifier(gitCommonDir, repositoryRoot);
127
128
  return {
@@ -145,17 +146,17 @@ async function validateTarget(gitCommonDir, target, name, projectName, existingS
145
146
  if ((!isAbsolute(gitRelative) && gitRelative !== '..' && !gitRelative.startsWith(`..${sep}`)) || target.split(sep).some(part => part.toLowerCase() === '.git'))
146
147
  throw new Error(`Target is inside a Git directory: ${target}`);
147
148
  if (existingStates.some(item => item.name.toLowerCase() === name.toLowerCase()))
148
- throw new Error(`Worktree ${name} is already managed.`);
149
+ throw new WtError('already_exists', `Worktree ${name} is already managed.`);
149
150
  for (const item of existingStates) {
150
151
  const path = await realpath(item.path).catch(() => resolve(item.path));
151
152
  if (path === target || item.projectName === projectName)
152
- throw new Error(`Worktree ${name} collides with managed worktree ${item.name}.`);
153
+ throw new WtError('already_exists', `Worktree ${name} collides with managed worktree ${item.name}.`);
153
154
  if (target.startsWith(`${path}${sep}`))
154
155
  throw new Error(`Target is inside managed worktree ${item.name}.`);
155
156
  }
156
157
  try {
157
158
  await lstat(target);
158
- throw new Error(`Target already exists: ${target}`);
159
+ throw new WtError('already_exists', `Target already exists: ${target}`);
159
160
  }
160
161
  catch (error) {
161
162
  if (error.code !== 'ENOENT')
@@ -170,7 +171,7 @@ async function worktreeAdd(name, options, root, target, progress) {
170
171
  '-z',
171
172
  ], root);
172
173
  if (existingWorktrees.split('\0').includes(`worktree ${target}`))
173
- throw new Error(`A Git worktree already exists at ${target}.`);
174
+ throw new WtError('already_exists', `A Git worktree already exists at ${target}.`);
174
175
  const plan = await planCheckout(name, options, root, progress);
175
176
  return {
176
177
  ...plan,
@@ -208,7 +209,7 @@ export async function planCheckout(name, options, root, progress) {
208
209
  : await runStep(progress, `Resolving branch ${options.branch}`, async () => resolveExistingBranch(options.branch, root));
209
210
  const branch = existing?.branch ?? name;
210
211
  if (existing === undefined && await refExists(`refs/heads/${branch}`, root))
211
- throw new Error(`Branch ${branch} already exists; use --branch ${branch}.`);
212
+ throw new WtError('branch_exists', `Branch ${branch} already exists; use --branch ${branch}.`);
212
213
  const startPoint = existing === undefined
213
214
  ? await git([
214
215
  'rev-parse',
@@ -6,6 +6,8 @@ import { createInterface } from 'node:readline/promises';
6
6
  import { configPath, loadConfig } from '../config/load.js';
7
7
  import { cloneNamedVolumes, composeFilesForWorktree, docker, prepareVolumeCopy, resolveSourceVolumes, runCompose, writeVolumeOverride } from '../docker/compose.js';
8
8
  import { containerAddresses, domainsLabel, orbstackNetwork, parseDomains } from '../docker/orbstack.js';
9
+ import { parsePorts } from '../docker/ports.js';
10
+ import { WtError } from '../errors.js';
9
11
  import { git, repositoryInfo } from '../git/repository.js';
10
12
  import { AttachedStore, StateStore } from '../state/store.js';
11
13
  import { formatConfirmation } from './confirmation.js';
@@ -108,13 +110,14 @@ export async function inspectEnvironment(name, cwd) {
108
110
  }
109
111
  export function parseContainers(output) {
110
112
  return output.split('\n').filter(Boolean).map((line) => {
111
- const [name, service, domains = '', state, ...status] = line.split('\t');
113
+ const [name, service, domains = '', ports = '', state, ...status] = line.split('\t');
112
114
  return {
113
115
  name,
114
116
  service: service || name,
115
117
  state: state ?? '',
116
118
  status: status.join('\t'),
117
119
  domains: parseDomains(domains),
120
+ ports: parsePorts(ports),
118
121
  };
119
122
  }).sort((a, b) => a.service.localeCompare(b.service) || a.name.localeCompare(b.name));
120
123
  }
@@ -126,7 +129,7 @@ export async function inspectState(state, cwd) {
126
129
  '--filter',
127
130
  `label=com.docker.compose.project=${state.projectName}`,
128
131
  '--format',
129
- `{{.Names}}\t{{.Label "com.docker.compose.service"}}\t{{.Label "${domainsLabel}"}}\t{{.State}}\t{{.Status}}`,
132
+ `{{.Names}}\t{{.Label "com.docker.compose.service"}}\t{{.Label "${domainsLabel}"}}\t{{.Ports}}\t{{.State}}\t{{.Status}}`,
130
133
  ], cwd),
131
134
  orbstackNetwork(cwd),
132
135
  ]);
@@ -149,7 +152,7 @@ export async function resolveEnvironmentName(name, cwd) {
149
152
  if (path === here)
150
153
  return state.name;
151
154
  }
152
- throw new Error('Current directory is not inside a managed worktree; pass a worktree name.');
155
+ throw new WtError('not_in_worktree', 'Current directory is not inside a managed worktree; pass a worktree name.');
153
156
  }
154
157
  export async function composeOperation(name, action, args, cwd, progress) {
155
158
  const { store } = await context(cwd);
@@ -170,7 +173,7 @@ export async function runManagedCompose(state, action, args, progress) {
170
173
  throw new Error(`Worktree directory is missing: ${state.path}`);
171
174
  const incomplete = state.status !== 'ready' && (state.status !== 'failed' || !await exists(state.overridePath));
172
175
  if (incomplete && action !== 'docker')
173
- throw new Error(`Worktree ${name} is ${state.status}. Run wt reset ${name} to retry setup or wt rm ${name} to remove it.`);
176
+ throw new WtError('not_ready', `Worktree ${name} is ${state.status}. Run wt reset ${name} to retry setup or wt rm ${name} to remove it.`);
174
177
  const files = await composeFilesForWorktree(state.composeFiles, state.sourceWorktreePath, state.path);
175
178
  const command = action === 'docker'
176
179
  ? args
@@ -208,9 +211,9 @@ export async function removeEnvironment(name, cwd, force = false, confirm, progr
208
211
  const target = await realpath(state.path).catch(() => resolve(state.path));
209
212
  const rel = relative(target, here);
210
213
  if (rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel))
211
- throw new Error(`Current directory is inside ${target}; change directory before removing it.`);
212
- if (!force && !process.stdin.isTTY)
213
- throw new Error('wt rm requires an interactive terminal or --force.');
214
+ throw new WtError('inside_worktree', `Current directory is inside ${target}; change directory before removing it.`);
215
+ if (!force && confirm === undefined && !process.stdin.isTTY)
216
+ throw new WtError('confirmation_required', 'wt rm requires an interactive terminal or --force. Run it with --dry-run to see what it removes.');
214
217
  const dependents = (await store.list()).filter(item => item.sourceProject === state.projectName);
215
218
  if (!force) {
216
219
  const request = {
@@ -274,8 +277,8 @@ export async function resetEnvironment(name, cwd, force = false, confirm, progre
274
277
  const { store, state } = await managed(name, cwd);
275
278
  await checkNotHosting(state, 'reset');
276
279
  const { sourceRoot, config } = await prepareReset(state, cwd);
277
- if (!force && !process.stdin.isTTY)
278
- throw new Error('wt reset requires an interactive terminal or --force.');
280
+ if (!force && confirm === undefined && !process.stdin.isTTY)
281
+ throw new WtError('confirmation_required', 'wt reset requires an interactive terminal or --force. Run it with --dry-run to see what it replaces.');
279
282
  if (!force) {
280
283
  const request = {
281
284
  title: `Reset worktree ${name}?`,
@@ -295,7 +298,7 @@ export async function resetEnvironment(name, cwd, force = false, confirm, progre
295
298
  checkInterrupted();
296
299
  await checkUnchanged(store, state);
297
300
  if (state.status === 'removing')
298
- throw new Error(`Removal of ${name} is incomplete. Retry wt rm ${name}.`);
301
+ throw new WtError('not_ready', `Removal of ${name} is incomplete. Retry wt rm ${name}.`);
299
302
  await resetLocked({ ...state, sourceWorktreePath: sourceRoot }, store, config, cwd, { progress });
300
303
  return true;
301
304
  }
@@ -401,7 +404,7 @@ export async function exists(path) {
401
404
  }
402
405
  export async function checkUnchanged(store, state) {
403
406
  if (JSON.stringify(await store.get(state.name)) !== JSON.stringify(state))
404
- throw new Error(`Worktree ${state.name} changed while waiting. Retry the command.`);
407
+ throw new WtError('changed', `Worktree ${state.name} changed while waiting. Retry the command.`);
405
408
  }
406
409
  async function downEnvironment(state, cwd, removeImages) {
407
410
  const filter = `label=com.docker.compose.project=${state.projectName}`;
@@ -2,6 +2,7 @@ import { AsyncLocalStorage } from 'node:async_hooks';
2
2
  import { spawn } from 'node:child_process';
3
3
  import { constants } from 'node:os';
4
4
  import process from 'node:process';
5
+ import { WtError } from '../errors.js';
5
6
  const operationSignal = new AsyncLocalStorage();
6
7
  export async function withOperationSignal(signal, operation) {
7
8
  return operationSignal.run(signal, operation);
@@ -15,10 +16,10 @@ export function currentSignal() {
15
16
  export function checkInterrupted() {
16
17
  operationSignal.getStore()?.throwIfAborted();
17
18
  }
18
- export class ProcessFailure extends Error {
19
+ export class ProcessFailure extends WtError {
19
20
  exitCode;
20
21
  constructor(command, operation, code, signal, stderr) {
21
- super(`${command} ${operation} failed (${signal ?? code})${stderr
22
+ super('command_failed', `${command} ${operation} failed (${signal ?? code})${stderr
22
23
  ? `: ${stderr}`
23
24
  : ''}`);
24
25
  this.exitCode = signal
@@ -3,6 +3,7 @@ import { link, mkdir, readdir, readFile, unlink, writeFile } from 'node:fs/promi
3
3
  import { join } from 'node:path';
4
4
  import process from 'node:process';
5
5
  import { z } from 'zod';
6
+ import { WtError } from '../errors.js';
6
7
  import { writeAtomicFile } from './atomic-file.js';
7
8
  const status = z.enum([
8
9
  'creating',
@@ -89,13 +90,13 @@ class JsonStore {
89
90
  return undefined;
90
91
  });
91
92
  if (state !== undefined && state.name !== name)
92
- throw new Error(`No managed worktree named ${name}. Did you mean ${state.name}?`);
93
+ throw new WtError('not_found', `No managed worktree named ${name}. Did you mean ${state.name}?`);
93
94
  return state;
94
95
  }
95
96
  async get(name) {
96
97
  const state = await this.find(name);
97
98
  if (state === undefined)
98
- throw new Error(`No managed worktree named ${name}. Run wt ls to see the available worktrees.`);
99
+ throw new WtError('not_found', `No managed worktree named ${name}. Run wt ls to see the available worktrees.`);
99
100
  return state;
100
101
  }
101
102
  async remove(name) {
@@ -140,7 +141,7 @@ export class StateStore extends JsonStore {
140
141
  if (error.code !== 'EEXIST')
141
142
  throw error;
142
143
  const owner = await readFile(path, 'utf8').catch(() => '');
143
- throw new Error(`Worktree operations are locked at ${path}${owner.trim()
144
+ throw new WtError('locked', `Worktree operations are locked at ${path}${owner.trim()
144
145
  ? ` by PID ${owner.trim()}`
145
146
  : ''}. Retry when it exits. If the lock is stale, verify the owner has exited before removing the lock file.`);
146
147
  }
@@ -1,3 +1,4 @@
1
+ import { portAddress } from '../docker/ports.js';
1
2
  import { colorize } from './format-status.js';
2
3
  /** Icon and color of a container, from its Docker state and health. */
3
4
  export function containerIndicator({ state, status }) {
@@ -87,6 +88,11 @@ export function formatEnvironmentInfo(info) {
87
88
  const domains = addresses.flatMap(({ name, values }) => values.map((value, index) => `${(index === 0
88
89
  ? name
89
90
  : '').padEnd(addressWidth)} ${value}`));
91
+ const published = info.containers.flatMap((container, index) => container.ports.map(port => ({ name: names[index], port })));
92
+ const portWidth = Math.max(0, ...published.map(({ name }) => name.length));
93
+ const ports = published.map(({ name, port }, index) => `${(index > 0 && published[index - 1].name === name
94
+ ? ''
95
+ : name).padEnd(portWidth)} ${portAddress(port)} → ${port.containerPort}/${port.protocol}`);
90
96
  const volumes = Object.entries(info.volumes);
91
97
  const volumeWidth = Math.max(0, ...volumes.map(([logical]) => logical.length));
92
98
  return [
@@ -100,6 +106,12 @@ export function formatEnvironmentInfo(info) {
100
106
  '',
101
107
  ]
102
108
  : []),
109
+ ...(ports.length
110
+ ? [
111
+ ...section('Ports', ports),
112
+ '',
113
+ ]
114
+ : []),
103
115
  ...section('Volumes', volumes.map(([logical, volume]) => `${logical.padEnd(volumeWidth)} → ${volume}`)),
104
116
  ].join('\n');
105
117
  }
@@ -1,3 +1,4 @@
1
+ import { portAddress } from '../docker/ports.js';
1
2
  function missing(value) {
2
3
  return value === undefined || value === '' || value === '-'
3
4
  ? null
@@ -28,13 +29,17 @@ export function environmentInfoJson(info) {
28
29
  name: info.host.name,
29
30
  path: missing(info.host.path),
30
31
  },
31
- containers: info.containers.map(({ name, service, state, status, address }) => ({
32
+ containers: info.containers.map(({ name, service, state, status, address, ports }) => ({
32
33
  name,
33
34
  service,
34
35
  state,
35
36
  status,
36
37
  hostname: address?.hostname ?? null,
37
38
  urls: address?.urls ?? [],
39
+ ports: ports.map(port => ({
40
+ ...port,
41
+ address: portAddress(port),
42
+ })),
38
43
  })),
39
44
  volumes: info.volumes,
40
45
  };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@joberthel/worktree",
3
3
  "type": "module",
4
- "version": "1.1.0",
4
+ "version": "1.2.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",