@joberthel/worktree 1.1.0 → 1.3.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 +19 -8
- package/dist/cli-spec.js +33 -5
- package/dist/cli.js +209 -51
- package/dist/cli.test/harness.js +64 -0
- package/dist/config/json-schema.js +37 -0
- package/dist/config/load.js +4 -3
- package/dist/config/schema.js +17 -15
- package/dist/docker/compose.js +2 -1
- package/dist/docker/ports.js +43 -0
- package/dist/errors.js +66 -0
- package/dist/git/repository.js +4 -3
- package/dist/operations/attached.js +8 -7
- package/dist/operations/commands.js +2 -1
- package/dist/operations/confirmation.js +13 -1
- package/dist/operations/create.js +11 -10
- package/dist/operations/manage.js +14 -11
- package/dist/operations/process.js +3 -2
- package/dist/state/store.js +4 -3
- package/dist/ui/environment-info.js +12 -0
- package/dist/ui/json-output.js +6 -1
- package/package.json +4 -2
- package/schema/wt.schema.json +208 -0
package/dist/config/schema.js
CHANGED
|
@@ -5,9 +5,9 @@ const relativePath = z.string().min(1).transform(value => value.split('/').filte
|
|
|
5
5
|
return value.split('/').every(part => part !== '..' && part.toLowerCase() !== '.git' && part !== '');
|
|
6
6
|
}, 'must be a normalized relative path without ..');
|
|
7
7
|
const hook = z.union([
|
|
8
|
-
relativePath,
|
|
8
|
+
relativePath.meta({ description: 'Path to an executable, relative to the directory the hook runs in.' }),
|
|
9
9
|
z.object({
|
|
10
|
-
script: z.string().refine(value => value.trim().length > 0, 'must not be empty'),
|
|
10
|
+
script: z.string().refine(value => value.trim().length > 0, 'must not be empty').meta({ description: 'Inline shell script run with /bin/sh. Start it with `set -eu` to stop at the first failure.' }),
|
|
11
11
|
}).strict(),
|
|
12
12
|
]);
|
|
13
13
|
function emptySection(input) {
|
|
@@ -15,24 +15,26 @@ function emptySection(input) {
|
|
|
15
15
|
? undefined
|
|
16
16
|
: input;
|
|
17
17
|
}
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
18
|
+
function hookGroup(description) {
|
|
19
|
+
return z.preprocess(emptySection, z.object({
|
|
20
|
+
before_create: hook.optional().meta({ description: 'Runs after the worktree, copied files, and cloned volumes are in place, before Docker Compose starts the services.' }),
|
|
21
|
+
after_create: hook.optional().meta({ description: 'Runs after Docker Compose has started the services.' }),
|
|
22
|
+
}).strict().optional()).meta({ description });
|
|
23
|
+
}
|
|
22
24
|
const host = z.object({
|
|
23
|
-
path: z.string().min(1).refine(value => !value.startsWith('~'), 'use an absolute path or a path relative to this checkout'),
|
|
24
|
-
from: z.string().min(1).optional(),
|
|
25
|
+
path: z.string().min(1).refine(value => !value.startsWith('~'), 'use an absolute path or a path relative to this checkout').meta({ description: 'Root of the host checkout, absolute or relative to this checkout.' }),
|
|
26
|
+
from: z.string().min(1).optional().meta({ description: 'Host ref to check out. Defaults to the host checkout\'s HEAD.' }),
|
|
25
27
|
}).strict();
|
|
26
28
|
export const configSchema = z.object({
|
|
27
|
-
host: host.optional(),
|
|
29
|
+
host: host.optional().meta({ description: 'Runs this repository inside the Docker environment of a host repository. Cannot be combined with `worktrees`.' }),
|
|
28
30
|
worktrees: z.preprocess(emptySection, z.object({
|
|
29
|
-
directory: z.string().min(1).refine(value => !value.startsWith('~'), 'use an absolute path or a path relative to the main checkout').default('../worktrees'),
|
|
30
|
-
}).strict().default({ directory: '../worktrees' })),
|
|
31
|
-
copy: z.preprocess(emptySection, z.array(relativePath).default([])),
|
|
31
|
+
directory: z.string().min(1).refine(value => !value.startsWith('~'), 'use an absolute path or a path relative to the main checkout').default('../worktrees').meta({ description: 'Where worktrees are created, absolute or relative to the main checkout.' }),
|
|
32
|
+
}).strict().default({ directory: '../worktrees' })).meta({ description: 'Worktree placement.' }),
|
|
33
|
+
copy: z.preprocess(emptySection, z.array(relativePath).default([])).meta({ description: 'Relative files and directories copied from the source checkout into each new worktree. Entries must not overlap.' }),
|
|
32
34
|
hooks: z.preprocess(emptySection, z.object({
|
|
33
|
-
worktree: hookGroup,
|
|
34
|
-
source: hookGroup,
|
|
35
|
-
}).strict().default({})),
|
|
35
|
+
worktree: hookGroup('Hooks that run in the new worktree.'),
|
|
36
|
+
source: hookGroup('Hooks that run in the source checkout.'),
|
|
37
|
+
}).strict().default({})).meta({ description: 'Commands run by `wt create` and `wt reset`.' }),
|
|
36
38
|
}).strict().superRefine((config, ctx) => {
|
|
37
39
|
const paths = new Set();
|
|
38
40
|
for (const path of config.copy) {
|
package/dist/docker/compose.js
CHANGED
|
@@ -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
|
|
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
|
+
}
|
package/dist/git/repository.js
CHANGED
|
@@ -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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
181
|
-
if (!force && !process.stdin.isTTY)
|
|
182
|
-
throw new
|
|
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
|
|
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
|
|
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
|
|
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
|
-
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
|
212
|
-
if (!force && !process.stdin.isTTY)
|
|
213
|
-
throw new
|
|
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
|
|
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
|
|
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
|
|
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
|
|
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
|
package/dist/state/store.js
CHANGED
|
@@ -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
|
|
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
|
|
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
|
|
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
|
}
|
package/dist/ui/json-output.js
CHANGED
|
@@ -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.
|
|
4
|
+
"version": "1.3.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",
|
|
@@ -25,7 +25,8 @@
|
|
|
25
25
|
"wt": "./dist/cli.js"
|
|
26
26
|
},
|
|
27
27
|
"files": [
|
|
28
|
-
"dist"
|
|
28
|
+
"dist",
|
|
29
|
+
"schema"
|
|
29
30
|
],
|
|
30
31
|
"engines": {
|
|
31
32
|
"node": ">=22"
|
|
@@ -66,6 +67,7 @@
|
|
|
66
67
|
"test:unit": "vitest run --exclude 'e2e/**/*.e2e.test.ts'",
|
|
67
68
|
"test:coverage": "pnpm test:unit --coverage",
|
|
68
69
|
"test:e2e": "pnpm build && vitest run e2e",
|
|
70
|
+
"schema": "vitest run src/config/json-schema.test.ts --update",
|
|
69
71
|
"lint": "eslint . --max-warnings 0",
|
|
70
72
|
"lint:fix": "eslint . --fix",
|
|
71
73
|
"commitlint": "commitlint",
|