@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.
@@ -5,6 +5,9 @@ import process from 'node:process';
5
5
  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
+ import { containerAddresses, domainsLabel, orbstackNetwork, parseDomains } from '../docker/orbstack.js';
9
+ import { parsePorts } from '../docker/ports.js';
10
+ import { WtError } from '../errors.js';
8
11
  import { git, repositoryInfo } from '../git/repository.js';
9
12
  import { AttachedStore, StateStore } from '../state/store.js';
10
13
  import { formatConfirmation } from './confirmation.js';
@@ -107,27 +110,36 @@ export async function inspectEnvironment(name, cwd) {
107
110
  }
108
111
  export function parseContainers(output) {
109
112
  return output.split('\n').filter(Boolean).map((line) => {
110
- const [name, service, state, ...status] = line.split('\t');
113
+ const [name, service, domains = '', ports = '', state, ...status] = line.split('\t');
111
114
  return {
112
115
  name,
113
116
  service: service || name,
114
117
  state: state ?? '',
115
118
  status: status.join('\t'),
119
+ domains: parseDomains(domains),
120
+ ports: parsePorts(ports),
116
121
  };
117
122
  }).sort((a, b) => a.service.localeCompare(b.service) || a.name.localeCompare(b.name));
118
123
  }
119
124
  export async function inspectState(state, cwd) {
120
- const containers = await docker([
121
- 'ps',
122
- '-a',
123
- '--filter',
124
- `label=com.docker.compose.project=${state.projectName}`,
125
- '--format',
126
- '{{.Names}}\t{{.Label "com.docker.compose.service"}}\t{{.State}}\t{{.Status}}',
127
- ], cwd);
125
+ const [output, network] = await Promise.all([
126
+ docker([
127
+ 'ps',
128
+ '-a',
129
+ '--filter',
130
+ `label=com.docker.compose.project=${state.projectName}`,
131
+ '--format',
132
+ `{{.Names}}\t{{.Label "com.docker.compose.service"}}\t{{.Label "${domainsLabel}"}}\t{{.Ports}}\t{{.State}}\t{{.Status}}`,
133
+ ], cwd),
134
+ orbstackNetwork(cwd),
135
+ ]);
136
+ const containers = parseContainers(output);
137
+ const addresses = network && containerAddresses(containers, state.projectName, network);
128
138
  return {
129
139
  ...state,
130
- containers: parseContainers(containers),
140
+ containers: addresses
141
+ ? containers.map((container, index) => ({ ...container, address: addresses[index] }))
142
+ : containers,
131
143
  };
132
144
  }
133
145
  export async function resolveEnvironmentName(name, cwd) {
@@ -140,7 +152,7 @@ export async function resolveEnvironmentName(name, cwd) {
140
152
  if (path === here)
141
153
  return state.name;
142
154
  }
143
- 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.');
144
156
  }
145
157
  export async function composeOperation(name, action, args, cwd, progress) {
146
158
  const { store } = await context(cwd);
@@ -161,7 +173,7 @@ export async function runManagedCompose(state, action, args, progress) {
161
173
  throw new Error(`Worktree directory is missing: ${state.path}`);
162
174
  const incomplete = state.status !== 'ready' && (state.status !== 'failed' || !await exists(state.overridePath));
163
175
  if (incomplete && action !== 'docker')
164
- 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.`);
165
177
  const files = await composeFilesForWorktree(state.composeFiles, state.sourceWorktreePath, state.path);
166
178
  const command = action === 'docker'
167
179
  ? args
@@ -199,9 +211,9 @@ export async function removeEnvironment(name, cwd, force = false, confirm, progr
199
211
  const target = await realpath(state.path).catch(() => resolve(state.path));
200
212
  const rel = relative(target, here);
201
213
  if (rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel))
202
- throw new Error(`Current directory is inside ${target}; change directory before removing it.`);
203
- if (!force && !process.stdin.isTTY)
204
- 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.');
205
217
  const dependents = (await store.list()).filter(item => item.sourceProject === state.projectName);
206
218
  if (!force) {
207
219
  const request = {
@@ -265,8 +277,8 @@ export async function resetEnvironment(name, cwd, force = false, confirm, progre
265
277
  const { store, state } = await managed(name, cwd);
266
278
  await checkNotHosting(state, 'reset');
267
279
  const { sourceRoot, config } = await prepareReset(state, cwd);
268
- if (!force && !process.stdin.isTTY)
269
- 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.');
270
282
  if (!force) {
271
283
  const request = {
272
284
  title: `Reset worktree ${name}?`,
@@ -286,7 +298,7 @@ export async function resetEnvironment(name, cwd, force = false, confirm, progre
286
298
  checkInterrupted();
287
299
  await checkUnchanged(store, state);
288
300
  if (state.status === 'removing')
289
- 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}.`);
290
302
  await resetLocked({ ...state, sourceWorktreePath: sourceRoot }, store, config, cwd, { progress });
291
303
  return true;
292
304
  }
@@ -392,7 +404,7 @@ export async function exists(path) {
392
404
  }
393
405
  export async function checkUnchanged(store, state) {
394
406
  if (JSON.stringify(await store.get(state.name)) !== JSON.stringify(state))
395
- 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.`);
396
408
  }
397
409
  async function downEnvironment(state, cwd, removeImages) {
398
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 }) {
@@ -73,6 +74,25 @@ export function formatEnvironmentInfo(info) {
73
74
  const { icon, variant } = containerIndicator(container);
74
75
  return `${colorize(icon, variant)} ${names[index].padEnd(nameWidth)} ${container.status}`;
75
76
  });
77
+ const addresses = info.containers.flatMap((container, index) => container.address === undefined
78
+ ? []
79
+ : [
80
+ {
81
+ name: names[index],
82
+ values: container.address.urls.length
83
+ ? container.address.urls
84
+ : [container.address.hostname],
85
+ },
86
+ ]);
87
+ const addressWidth = Math.max(0, ...addresses.map(({ name }) => name.length));
88
+ const domains = addresses.flatMap(({ name, values }) => values.map((value, index) => `${(index === 0
89
+ ? name
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}`);
76
96
  const volumes = Object.entries(info.volumes);
77
97
  const volumeWidth = Math.max(0, ...volumes.map(([logical]) => logical.length));
78
98
  return [
@@ -80,6 +100,18 @@ export function formatEnvironmentInfo(info) {
80
100
  '',
81
101
  ...section('Services', services),
82
102
  '',
103
+ ...(domains.length
104
+ ? [
105
+ ...section('Domains', domains),
106
+ '',
107
+ ]
108
+ : []),
109
+ ...(ports.length
110
+ ? [
111
+ ...section('Ports', ports),
112
+ '',
113
+ ]
114
+ : []),
83
115
  ...section('Volumes', volumes.map(([logical, volume]) => `${logical.padEnd(volumeWidth)} → ${volume}`)),
84
116
  ].join('\n');
85
117
  }
@@ -6,9 +6,11 @@ const states = {
6
6
  const unknownState = { icon: '!', variant: 'error' };
7
7
  /**
8
8
  * Formats managed worktrees as an aligned table. Cells are padded before they
9
- * are colored so escape sequences never shift the columns.
9
+ * are colored so escape sequences never shift the columns. The URL column only
10
+ * appears when at least one environment has a URL.
10
11
  */
11
12
  export function formatEnvironmentTable(items) {
13
+ const withUrls = items.some(item => item.url !== undefined);
12
14
  const rows = items.map((item) => {
13
15
  const status = item.status !== undefined && item.status !== 'ready'
14
16
  ? item.status
@@ -22,11 +24,22 @@ export function formatEnvironmentTable(items) {
22
24
  item.branch || '(detached)',
23
25
  `${state.icon} ${status}`,
24
26
  item.projectName,
27
+ ...(withUrls
28
+ ? [item.url ?? '-']
29
+ : []),
25
30
  ],
26
31
  variant: state.variant,
27
32
  };
28
33
  });
29
- const header = ['NAME', 'BRANCH', 'STATE', 'PROJECT'];
34
+ const header = [
35
+ 'NAME',
36
+ 'BRANCH',
37
+ 'STATE',
38
+ 'PROJECT',
39
+ ...(withUrls
40
+ ? ['URL']
41
+ : []),
42
+ ];
30
43
  const widths = header.map((title, column) => Math.max(title.length, ...rows.map(row => row.cells[column].length)));
31
44
  const line = (cells, variant) => cells.map((cell, column) => {
32
45
  const padded = column === cells.length - 1
@@ -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
@@ -11,6 +12,7 @@ export function environmentListJson(items) {
11
12
  status: missing(item.status),
12
13
  dockerStatus: item.dockerStatus,
13
14
  projectName: missing(item.projectName),
15
+ url: item.url ?? null,
14
16
  }));
15
17
  }
16
18
  export function environmentInfoJson(info) {
@@ -27,11 +29,17 @@ export function environmentInfoJson(info) {
27
29
  name: info.host.name,
28
30
  path: missing(info.host.path),
29
31
  },
30
- containers: info.containers.map(({ name, service, state, status }) => ({
32
+ containers: info.containers.map(({ name, service, state, status, address, ports }) => ({
31
33
  name,
32
34
  service,
33
35
  state,
34
36
  status,
37
+ hostname: address?.hostname ?? null,
38
+ urls: address?.urls ?? [],
39
+ ports: ports.map(port => ({
40
+ ...port,
41
+ address: portAddress(port),
42
+ })),
35
43
  })),
36
44
  volumes: info.volumes,
37
45
  };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@joberthel/worktree",
3
3
  "type": "module",
4
- "version": "1.0.1",
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",