@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/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,11 +100,22 @@ 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:
|
|
106
116
|
|
|
107
117
|
```yaml
|
|
118
|
+
# yaml-language-server: $schema=https://unpkg.com/@joberthel/worktree@1/schema/wt.schema.json
|
|
108
119
|
worktrees:
|
|
109
120
|
directory: ../worktrees
|
|
110
121
|
|
|
@@ -120,7 +131,7 @@ hooks:
|
|
|
120
131
|
docker compose exec -T app bin/migrate
|
|
121
132
|
```
|
|
122
133
|
|
|
123
|
-
See [Configuration](docs/configuration.md) for every option, the hook order and variables, and how volumes are cloned. For a repository that runs inside another one, such as a Shopware plugin, see [Nested repositories](docs/nested-repositories.md).
|
|
134
|
+
The first line enables completion and validation in editors; see [Editor support](docs/configuration.md#editor-support). See [Configuration](docs/configuration.md) for every option, the hook order and variables, and how volumes are cloned. For a repository that runs inside another one, such as a Shopware plugin, see [Nested repositories](docs/nested-repositories.md).
|
|
124
135
|
|
|
125
136
|
Before you clone a database volume, stop writes to it or stop the source services if you need a consistent snapshot. Use dynamic host ports and leave out fixed `container_name` values, so the source and worktree projects can run side by side.
|
|
126
137
|
|
|
@@ -129,12 +140,12 @@ Before you clone a database volume, stop writes to it or stop the source service
|
|
|
129
140
|
- [Commands](docs/commands.md): branches, confirmations, progress, and shell completion in detail.
|
|
130
141
|
- [Configuration](docs/configuration.md): `.wt.yml`, hooks, environment variables, and Docker volumes.
|
|
131
142
|
- [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.
|
|
143
|
+
- [JSON output](docs/json-output.md): the output of `--format json` for scripts and coding agents, including error codes.
|
|
133
144
|
- [Troubleshooting](docs/troubleshooting.md): recovering from a failed create or reset and stale locks.
|
|
134
145
|
|
|
135
146
|
## Versioning
|
|
136
147
|
|
|
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.
|
|
148
|
+
`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
149
|
|
|
139
150
|
## Contributing
|
|
140
151
|
|
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
|
|
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
|
|
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
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
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: ${
|
|
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,
|
|
148
|
+
function printBuiltin(command, args) {
|
|
57
149
|
if (command === undefined || command === '' || command === '-h' || command === '--help') {
|
|
58
|
-
|
|
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
|
-
|
|
157
|
+
printHelp(helpFormat(args), topic);
|
|
65
158
|
return true;
|
|
66
159
|
}
|
|
67
160
|
if (command === '-v' || command === '--version') {
|
|
68
|
-
|
|
69
|
-
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
174
|
-
|
|
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:
|
|
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
|
-
:
|
|
424
|
+
: code === 'usage'
|
|
273
425
|
? 2
|
|
274
426
|
: 1;
|
|
275
|
-
|
|
427
|
+
const message = reason instanceof Error
|
|
276
428
|
? reason.message
|
|
277
|
-
: String(reason)
|
|
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
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { configSchema } from './schema.js';
|
|
3
|
+
export const configSchemaUrl = 'https://unpkg.com/@joberthel/worktree@1/schema/wt.schema.json';
|
|
4
|
+
// Sections accept an empty value such as `copy:`, which YAML reads as null.
|
|
5
|
+
// The Zod schema allows that through a preprocess step, which JSON Schema cannot express.
|
|
6
|
+
function allowEmptySection(zodSchema, jsonSchema) {
|
|
7
|
+
const def = zodSchema._zod.def;
|
|
8
|
+
if (def.type !== 'pipe' || !def.in._zod.traits.has('$ZodTransform'))
|
|
9
|
+
return;
|
|
10
|
+
const { description, default: fallback, ...section } = jsonSchema;
|
|
11
|
+
for (const key of Object.keys(jsonSchema))
|
|
12
|
+
delete jsonSchema[key];
|
|
13
|
+
Object.assign(jsonSchema, {
|
|
14
|
+
description,
|
|
15
|
+
default: fallback,
|
|
16
|
+
anyOf: [
|
|
17
|
+
section,
|
|
18
|
+
{ type: 'null' },
|
|
19
|
+
],
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
export function configJsonSchema() {
|
|
23
|
+
const schema = z.toJSONSchema(configSchema, {
|
|
24
|
+
io: 'input',
|
|
25
|
+
override: ({ zodSchema, jsonSchema }) => allowEmptySection(zodSchema, jsonSchema),
|
|
26
|
+
});
|
|
27
|
+
return {
|
|
28
|
+
$schema: schema.$schema,
|
|
29
|
+
$id: configSchemaUrl,
|
|
30
|
+
title: 'wt configuration',
|
|
31
|
+
description: 'Configuration for wt, read from .wt.yml at the root of the source checkout.',
|
|
32
|
+
...schema,
|
|
33
|
+
not: {
|
|
34
|
+
required: ['host', 'worktrees'],
|
|
35
|
+
},
|
|
36
|
+
};
|
|
37
|
+
}
|
package/dist/config/load.js
CHANGED
|
@@ -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
|
|
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
|
|
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
|
|
45
|
+
throw new WtError('invalid_config', `${file}: ${error.message}`);
|
|
45
46
|
}
|
|
46
47
|
}
|