@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.
@@ -1,4 +1,5 @@
1
- import { commands, extractWorkingDir, isCommand, shells, workingDirectory } from './cli-spec.js';
1
+ import { commandOptions, commands, extractWorkingDir, isCommand, shells, workingDirectory } from './cli-spec.js';
2
+ import { filterStates } from './list-filter.js';
2
3
  const none = { kind: 'values', values: [] };
3
4
  const workingDirOptions = ['-w', '--working-dir'];
4
5
  const globalOptions = [
@@ -16,7 +17,7 @@ function commandCandidates() {
16
17
  function valueOptions(command) {
17
18
  const spec = commands[command];
18
19
  return new Set([
19
- ...Object.entries(spec.options).filter(([, type]) => type === 'string').map(([name]) => `--${name}`),
20
+ ...commandOptions(command).filter(([, { type }]) => type !== 'boolean').map(([name]) => `--${name}`),
20
21
  ...(spec.shared
21
22
  ? ['--format']
22
23
  : []),
@@ -24,7 +25,7 @@ function valueOptions(command) {
24
25
  }
25
26
  function optionCandidates(command) {
26
27
  const spec = commands[command];
27
- return values(...Object.keys(spec.options).map(name => ({ value: `--${name}`, description: '' })), ...(spec.shared
28
+ return values(...commandOptions(command).map(([name, { description }]) => ({ value: `--${name}`, description })), ...(spec.shared
28
29
  ? [
29
30
  { value: '--format', description: 'Output format' },
30
31
  ]
@@ -50,6 +51,14 @@ async function applicableEnvironments(command, cwd, sources) {
50
51
  ? environments
51
52
  : environments.filter(({ name }) => running.has(name) === (wanted === 'running'));
52
53
  }
54
+ /** Complete filters for `wt ls --filter`: every state, and the names and branches of the environments. */
55
+ async function filterCandidates(cwd, sources) {
56
+ const environments = await sources.environments(cwd);
57
+ const branches = [
58
+ ...new Set(environments.map(({ branch }) => branch).filter(Boolean)),
59
+ ];
60
+ return values(...filterStates.map(state => ({ value: `state=${state}`, description: '' })), ...environments.map(({ name, branch }) => ({ value: `name=${name}`, description: branch || '(detached)' })), ...branches.map(branch => ({ value: `branch=${branch}`, description: '' })));
61
+ }
53
62
  async function environmentCandidates(command, cwd, sources) {
54
63
  const environments = await applicableEnvironments(command, cwd, sources);
55
64
  return values(...environments.map(({ name, branch }) => ({ value: name, description: branch || '(detached)' })), ...(command === 'docker'
@@ -101,6 +110,8 @@ async function completeArguments(command, args, current, { cwd, sources }) {
101
110
  const takesValue = valueOptions(command);
102
111
  if (previous === '--format' && takesValue.has('--format'))
103
112
  return values({ value: 'text', description: 'For people (default)' }, { value: 'json', description: 'For scripts and agents' });
113
+ if (previous === '--filter' && takesValue.has('--filter'))
114
+ return filterCandidates(await cwd(), sources);
104
115
  if (previous !== undefined && takesValue.has(previous))
105
116
  return values(...(await sources.branches(await cwd())).map(value => ({ value, description: '' })));
106
117
  if (current.startsWith('-'))
@@ -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,77 @@
1
+ import { run } from '../operations/process.js';
2
+ import { docker } from './compose.js';
3
+ /** Container label that gives a container custom OrbStack domains. */
4
+ export const domainsLabel = 'dev.orbstack.domains';
5
+ /**
6
+ * OrbStack's network settings when the Docker engine is OrbStack, otherwise
7
+ * undefined. HTTPS is OrbStack's default, so it is assumed when `orbctl`
8
+ * cannot answer.
9
+ */
10
+ export async function orbstackNetwork(cwd) {
11
+ const [system, https] = await Promise.all([
12
+ docker(['info', '--format', '{{.OperatingSystem}}'], cwd).catch(() => ''),
13
+ run('orbctl', ['config', 'get', 'network.https'], cwd, { timeout: 2000 }).catch(() => ''),
14
+ ]);
15
+ if (system !== 'OrbStack')
16
+ return undefined;
17
+ return {
18
+ scheme: https === 'false'
19
+ ? 'http'
20
+ : 'https',
21
+ };
22
+ }
23
+ /** Domains of a `dev.orbstack.domains` label. Wildcards are not addresses, so they are left out. */
24
+ export function parseDomains(label) {
25
+ return label.split(',').map(domain => domain.trim()).filter(domain => domain !== '' && !domain.includes('*'));
26
+ }
27
+ /**
28
+ * Addresses of a Compose project's containers. A service is reached as
29
+ * `<service>.<project>.orb.local`; a service with several containers falls
30
+ * back to `<container>.orb.local` so each address stays unique.
31
+ */
32
+ export function containerAddresses(containers, project, { scheme }) {
33
+ const counts = new Map();
34
+ for (const { service } of containers)
35
+ counts.set(service, (counts.get(service) ?? 0) + 1);
36
+ return containers.map(({ name, service, domains }) => ({
37
+ hostname: counts.get(service) === 1
38
+ ? `${service}.${project}.orb.local`
39
+ : `${name}.orb.local`,
40
+ urls: domains.map(domain => `${scheme}://${domain}`),
41
+ }));
42
+ }
43
+ /**
44
+ * The main URL of each Compose project: its custom domain closest to the
45
+ * root, so `shop.orb.local` wins over `admin.shop.orb.local`. Among domains
46
+ * of equal depth, the one listed first in its label wins.
47
+ */
48
+ export async function projectUrls(cwd) {
49
+ const network = await orbstackNetwork(cwd);
50
+ if (network === undefined)
51
+ return () => undefined;
52
+ const output = await docker([
53
+ 'ps',
54
+ '-a',
55
+ '--filter',
56
+ `label=${domainsLabel}`,
57
+ '--format',
58
+ `{{.Label "com.docker.compose.project"}}\t{{.Label "${domainsLabel}"}}`,
59
+ ], cwd);
60
+ const domains = new Map();
61
+ for (const line of output.split('\n').filter(Boolean)) {
62
+ const [project, label = ''] = line.split('\t');
63
+ domains.set(project, [
64
+ ...domains.get(project) ?? [],
65
+ ...parseDomains(label).map((domain, position) => ({ domain, position })),
66
+ ]);
67
+ }
68
+ const depth = (domain) => domain.split('.').length;
69
+ return (project) => {
70
+ const [main] = [
71
+ ...domains.get(project) ?? [],
72
+ ].sort((a, b) => depth(a.domain) - depth(b.domain) || a.position - b.position || a.domain.localeCompare(b.domain));
73
+ return main === undefined
74
+ ? undefined
75
+ : `${network.scheme}://${main.domain}`;
76
+ };
77
+ }
@@ -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);
@@ -0,0 +1,57 @@
1
+ import { UsageError } from './cli-spec.js';
2
+ /*
3
+ * Filters for `wt ls --filter key=value`, modeled on `docker ps --filter`.
4
+ * Values of the same key match if any of them does, and different keys must
5
+ * all match.
6
+ */
7
+ export const filterKeys = ['name', 'branch', 'state'];
8
+ /** Values `state=` accepts: the setup states other than `ready`, and the Docker states. */
9
+ export const filterStates = [
10
+ 'running',
11
+ 'stopped',
12
+ 'finished',
13
+ 'missing',
14
+ 'creating',
15
+ 'resetting',
16
+ 'removing',
17
+ 'failed',
18
+ ];
19
+ function isFilterKey(value) {
20
+ return filterKeys.includes(value);
21
+ }
22
+ export function parseListFilter(expressions) {
23
+ const filter = {};
24
+ for (const expression of expressions) {
25
+ const separator = expression.indexOf('=');
26
+ const key = expression.slice(0, separator);
27
+ const value = expression.slice(separator + 1);
28
+ if (separator === -1 || !isFilterKey(key))
29
+ throw new UsageError(`Unknown filter ${expression}. Use ${filterKeys.map(name => `${name}=<value>`).join(', ')}.`);
30
+ if (value === '')
31
+ throw new UsageError(`Filter ${key}= needs a value.`);
32
+ if (key === 'state' && !filterStates.includes(value))
33
+ throw new UsageError(`Unknown state ${value}. Use one of ${filterStates.join(', ')}.`);
34
+ const values = filter[key] ?? [];
35
+ values.push(value);
36
+ filter[key] = values;
37
+ }
38
+ return filter;
39
+ }
40
+ /** The state shown in the STATE column: the setup state until it is ready, then the Docker state without its exited count. */
41
+ function displayedState(item) {
42
+ const status = item.status !== undefined && item.status !== 'ready'
43
+ ? item.status
44
+ : item.dockerStatus;
45
+ return status.split(' ')[0];
46
+ }
47
+ export function matchesListFilter(item, filter) {
48
+ const tests = {
49
+ name: value => item.name.includes(value),
50
+ branch: value => item.branch.includes(value),
51
+ state: value => displayedState(item) === value,
52
+ };
53
+ return filterKeys.every(key => filter[key] === undefined || filter[key].some(tests[key]));
54
+ }
55
+ export function hasListFilter(filter) {
56
+ return Object.keys(filter).length > 0;
57
+ }
@@ -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,5 +1,7 @@
1
1
  import { realpath } from 'node:fs/promises';
2
2
  import { resolve } from 'node:path';
3
+ import { projectUrls } from '../docker/orbstack.js';
4
+ import { WtError } from '../errors.js';
3
5
  import { repositoryInfo } from '../git/repository.js';
4
6
  import { AttachedStore, StateStore } from '../state/store.js';
5
7
  import { attachedHost, createAttached, removeAttached, resetAttached } from './attached.js';
@@ -37,6 +39,16 @@ export async function resolveEnvironmentName(name, cwd) {
37
39
  return manage.resolveEnvironmentName(undefined, cwd);
38
40
  }
39
41
  export async function listEnvironments(cwd) {
42
+ const [rows, url] = await Promise.all([
43
+ listedEnvironments(cwd),
44
+ projectUrls(cwd),
45
+ ]);
46
+ return rows.map(row => ({
47
+ ...row,
48
+ url: url(row.projectName),
49
+ }));
50
+ }
51
+ async function listedEnvironments(cwd) {
40
52
  const own = await manage.listEnvironments(cwd);
41
53
  const { gitCommonDir } = await repositoryInfo(cwd);
42
54
  const states = await new AttachedStore(gitCommonDir).list();
@@ -132,7 +144,7 @@ export async function composeOperation(name, action, args, cwd, progress) {
132
144
  return manage.composeOperation(name, action, args, cwd, progress);
133
145
  const { state } = target;
134
146
  if (state.status !== 'ready' && action !== 'docker')
135
- 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.`);
136
148
  const hostStore = new StateStore(state.host.gitCommonDir);
137
149
  const unlock = action === 'docker'
138
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',