@joberthel/worktree 0.0.0-stage → 1.0.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/dist/cli.js ADDED
@@ -0,0 +1,264 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync } from 'node:fs';
3
+ import process from 'node:process';
4
+ import { parseArgs } from 'node:util';
5
+ import { commands, extractWorkingDir, isCommand, parseOptions, shells, UsageError, workingDirectory } from './cli-spec.js';
6
+ import { complete, completionScripts, formatCompletion } from './completion.js';
7
+ import { listBranches } from './git/repository.js';
8
+ import { composeOperation, createEnvironment, inspectEnvironment, listEnvironmentNames, listEnvironments, removeEnvironment, resetEnvironment, resolveEnvironmentName, runningEnvironmentNames } from './operations/commands.js';
9
+ import { ProcessFailure, withOperationSignal } from './operations/process.js';
10
+ import { formatEnvironmentInfo } from './ui/environment-info.js';
11
+ import { formatEnvironmentTable } from './ui/environment-table.js';
12
+ import { formatStatus } from './ui/format-status.js';
13
+ import { environmentInfoJson, environmentListJson, formatJson } from './ui/json-output.js';
14
+ import { showOperation } from './ui/show-operation.js';
15
+ const description = 'Manage isolated Git worktrees with Docker Compose.';
16
+ class Interrupted extends Error {
17
+ signal;
18
+ constructor(signal) {
19
+ super(`Interrupted by ${signal}.`);
20
+ this.signal = signal;
21
+ }
22
+ }
23
+ function usage(command) {
24
+ if (command !== undefined) {
25
+ const { usage: args, summary, shared } = commands[command];
26
+ const options = [
27
+ ...(command === 'completion'
28
+ ? []
29
+ : [' -w, --working-dir <dir> Run as if wt was started in <dir>']),
30
+ ...(shared
31
+ ? [' --format <text|json> Output format (default: text)']
32
+ : []),
33
+ ];
34
+ const optionList = options.length
35
+ ? `\n\nOptions:\n${options.join('\n')}`
36
+ : '';
37
+ return `Usage: ${`wt ${command} ${args}`.trimEnd()}\n\n${summary}${optionList}`;
38
+ }
39
+ const width = Math.max(...Object.keys(commands).map(name => name.length));
40
+ const list = Object.entries(commands).map(([name, spec]) => ` ${name.padEnd(width)} ${spec.usage.padEnd(43)} ${spec.summary}`).join('\n');
41
+ 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`;
42
+ }
43
+ /** Handles help and version, which need neither a command nor a repository. Returns whether it printed something. */
44
+ function printBuiltin(command, [topic]) {
45
+ if (command === undefined || command === '' || command === '-h' || command === '--help') {
46
+ process.stdout.write(`${usage()}\n`);
47
+ return true;
48
+ }
49
+ if (command === 'help') {
50
+ if (topic !== undefined && !isCommand(topic))
51
+ throw new UsageError(`Unknown command ${topic}. Run wt --help to see available commands.`);
52
+ process.stdout.write(`${usage(topic)}\n`);
53
+ return true;
54
+ }
55
+ if (command === '-v' || command === '--version') {
56
+ const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
57
+ process.stdout.write(`${pkg.version}\n`);
58
+ return true;
59
+ }
60
+ return false;
61
+ }
62
+ /** How long completion waits for Docker before it offers every environment. */
63
+ const completionDockerTimeout = 1500;
64
+ /** Answers the shell completion scripts. It prints nothing on failure, so a broken repository never garbles the prompt. */
65
+ async function printCompletion(words) {
66
+ const completion = await complete(words, {
67
+ environments: listEnvironmentNames,
68
+ running: async (cwd) => runningEnvironmentNames(cwd, completionDockerTimeout),
69
+ branches: listBranches,
70
+ }).catch(() => undefined);
71
+ if (completion !== undefined)
72
+ process.stdout.write(formatCompletion(completion));
73
+ }
74
+ function printCompletionScript([shell, extra]) {
75
+ if (extra !== undefined || !shells.includes(shell))
76
+ throw new UsageError(usage('completion'));
77
+ process.stdout.write(completionScripts[shell]);
78
+ }
79
+ async function main(argv, signal, interrupt) {
80
+ if (argv[0] === '__complete') {
81
+ await printCompletion(argv[1] === '--'
82
+ ? argv.slice(2)
83
+ : argv.slice(1));
84
+ return;
85
+ }
86
+ const { rest, workingDir } = extractWorkingDir(argv[0] === '--'
87
+ ? argv.slice(1)
88
+ : argv);
89
+ const [command, ...args] = rest;
90
+ if (printBuiltin(command, args))
91
+ return;
92
+ if (!isCommand(command))
93
+ throw new UsageError(`Unknown command ${command}. Run wt --help to see available commands.`);
94
+ const action = command;
95
+ const separator = args.indexOf('--');
96
+ const ownArgs = separator === -1
97
+ ? args
98
+ : args.slice(0, separator);
99
+ if (ownArgs.includes('--help') || ownArgs.includes('-h')) {
100
+ process.stdout.write(`${usage(action)}\n`);
101
+ return;
102
+ }
103
+ if (action === 'completion') {
104
+ printCompletionScript(args);
105
+ return;
106
+ }
107
+ const cwd = await workingDirectory(workingDir);
108
+ if (action === 'docker') {
109
+ await dispatchDocker(args, cwd);
110
+ return;
111
+ }
112
+ const { format, positionals, values } = parseCommandArgs(action, args);
113
+ const result = await showOperation(`Running wt ${action}`, async (report, confirm) => withOperationSignal(signal, async () => runCommand(action, positionals, values, cwd, {
114
+ report,
115
+ confirm,
116
+ signal,
117
+ })), interrupt);
118
+ signal.throwIfAborted();
119
+ process.stdout.write(`${renderResult(result, format)}\n`);
120
+ }
121
+ function renderResult(result, format) {
122
+ return format === 'json'
123
+ ? formatJson(result.json)
124
+ : result.text;
125
+ }
126
+ async function dispatchDocker(args, cwd) {
127
+ const separator = args.indexOf('--');
128
+ if ((separator !== 0 && separator !== 1) || args.length <= separator + 1 || (separator === 1 && !args[0]))
129
+ throw new UsageError(usage('docker'));
130
+ const name = await resolveEnvironmentName(separator === 1
131
+ ? args[0]
132
+ : undefined, cwd);
133
+ try {
134
+ await composeOperation(name, 'docker', args.slice(separator + 1), cwd);
135
+ }
136
+ catch (error) {
137
+ if (!(error instanceof ProcessFailure))
138
+ throw error;
139
+ process.exitCode = error.exitCode;
140
+ }
141
+ }
142
+ /** Parses and validates arguments before anything runs, so a usage error never leaves a half-done operation. */
143
+ function parseCommandArgs(action, args) {
144
+ const { positionals, values } = parseArgs({
145
+ args,
146
+ allowPositionals: true,
147
+ options: parseOptions(action),
148
+ });
149
+ const [name, extra] = positionals;
150
+ if (extra !== undefined || (action === 'ls' && name !== undefined) || ((action === 'create' || action === 'rm') && !name))
151
+ throw new UsageError(usage(action));
152
+ const format = values.format ?? 'text';
153
+ if (!isFormat(format))
154
+ throw new UsageError(`Unknown format ${String(format)}. Use --format text or --format json.`);
155
+ return { format, positionals, values };
156
+ }
157
+ function isFormat(value) {
158
+ return value === 'text' || value === 'json';
159
+ }
160
+ async function runCommand(action, [name], values, cwd, { report, confirm, signal }) {
161
+ if (action === 'create') {
162
+ const options = { branch: values.branch, from: values.from };
163
+ const result = await createEnvironment(name, options, cwd, report);
164
+ return {
165
+ text: formatStatus(`Created ${name} at ${result.path} (${result.projectName})`, 'success'),
166
+ json: {
167
+ name,
168
+ action,
169
+ completed: true,
170
+ path: result.path,
171
+ projectName: result.projectName,
172
+ },
173
+ };
174
+ }
175
+ if (action === 'ls') {
176
+ const states = await listEnvironments(cwd);
177
+ return {
178
+ text: states.length
179
+ ? formatEnvironmentTable(states)
180
+ : 'No managed worktrees. Create one with wt create <name>.',
181
+ json: environmentListJson(states),
182
+ };
183
+ }
184
+ const target = await resolveEnvironmentName(name, cwd);
185
+ if (action === 'info') {
186
+ const state = await inspectEnvironment(target, cwd);
187
+ return {
188
+ text: formatEnvironmentInfo(state),
189
+ json: environmentInfoJson(state),
190
+ };
191
+ }
192
+ if (action === 'rm' || action === 'reset') {
193
+ const confirmUntilInterrupted = confirm
194
+ ? async (request) => abortable(confirm(request), signal)
195
+ : undefined;
196
+ const change = action === 'rm'
197
+ ? removeEnvironment
198
+ : resetEnvironment;
199
+ const completed = await change(target, cwd, values.force === true, confirmUntilInterrupted, report);
200
+ const json = { name: target, action, completed };
201
+ if (!completed) {
202
+ return {
203
+ text: action === 'rm'
204
+ ? 'Removal cancelled'
205
+ : 'Reset cancelled',
206
+ json,
207
+ };
208
+ }
209
+ return {
210
+ text: formatStatus(`${action === 'rm'
211
+ ? 'Removed'
212
+ : 'Reset'} ${target}`, 'success'),
213
+ json,
214
+ };
215
+ }
216
+ await composeOperation(target, action, [], cwd, report);
217
+ return {
218
+ text: formatStatus(`${{ start: 'Started', stop: 'Stopped', restart: 'Restarted' }[action]} ${target}`, 'success'),
219
+ json: { name: target, action, completed: true },
220
+ };
221
+ }
222
+ async function abortable(work, signal) {
223
+ signal.throwIfAborted();
224
+ let abort;
225
+ const interruption = new Promise((_resolve, reject) => {
226
+ abort = () => reject(signal.reason);
227
+ signal.addEventListener('abort', abort, { once: true });
228
+ });
229
+ try {
230
+ return await Promise.race([work, interruption]);
231
+ }
232
+ finally {
233
+ signal.removeEventListener('abort', abort);
234
+ }
235
+ }
236
+ const controller = new AbortController();
237
+ const interrupt = () => controller.abort(new Interrupted('SIGINT'));
238
+ const terminate = () => controller.abort(new Interrupted('SIGTERM'));
239
+ process.on('SIGINT', interrupt);
240
+ process.on('SIGTERM', terminate);
241
+ process.stdout.on('error', (error) => {
242
+ if (error.code !== 'EPIPE')
243
+ throw error;
244
+ });
245
+ try {
246
+ await withOperationSignal(controller.signal, async () => main(process.argv.slice(2), controller.signal, interrupt));
247
+ }
248
+ catch (error) {
249
+ const reason = controller.signal.aborted ? controller.signal.reason : error;
250
+ process.exitCode = reason instanceof Interrupted
251
+ ? reason.signal === 'SIGINT'
252
+ ? 130
253
+ : 143
254
+ : reason instanceof UsageError || reason?.code?.startsWith('ERR_PARSE_ARGS')
255
+ ? 2
256
+ : 1;
257
+ process.stderr.write(`${formatStatus(reason instanceof Error
258
+ ? reason.message
259
+ : String(reason), 'error')}\n`);
260
+ }
261
+ finally {
262
+ process.off('SIGINT', interrupt);
263
+ process.off('SIGTERM', terminate);
264
+ }
@@ -0,0 +1,178 @@
1
+ import { commands, extractWorkingDir, isCommand, shells, workingDirectory } from './cli-spec.js';
2
+ const none = { kind: 'values', values: [] };
3
+ const workingDirOptions = ['-w', '--working-dir'];
4
+ const globalOptions = [
5
+ { value: '--working-dir', description: 'Run as if wt was started in this directory' },
6
+ { value: '--help', description: 'Show help' },
7
+ { value: '--version', description: 'Show the version' },
8
+ ];
9
+ function values(...candidates) {
10
+ return { kind: 'values', values: candidates };
11
+ }
12
+ function commandCandidates() {
13
+ return values(...Object.entries(commands).map(([value, spec]) => ({ value, description: spec.summary })));
14
+ }
15
+ /** Options of a command that take a value, as typed on the command line. */
16
+ function valueOptions(command) {
17
+ const spec = commands[command];
18
+ return new Set([
19
+ ...Object.entries(spec.options).filter(([, type]) => type === 'string').map(([name]) => `--${name}`),
20
+ ...(spec.shared
21
+ ? ['--format']
22
+ : []),
23
+ ]);
24
+ }
25
+ function optionCandidates(command) {
26
+ const spec = commands[command];
27
+ return values(...Object.keys(spec.options).map(name => ({ value: `--${name}`, description: '' })), ...(spec.shared
28
+ ? [
29
+ { value: '--format', description: 'Output format' },
30
+ ]
31
+ : []), ...(command === 'completion'
32
+ ? []
33
+ : [
34
+ { value: '--working-dir', description: 'Run as if wt was started in this directory' },
35
+ ]), { value: '--help', description: 'Show help' });
36
+ }
37
+ /**
38
+ * The environments a command applies to. When Docker cannot tell which
39
+ * services run, all environments are offered rather than none.
40
+ */
41
+ async function applicableEnvironments(command, cwd, sources) {
42
+ const wanted = commands[command].environment;
43
+ const [environments, running] = await Promise.all([
44
+ sources.environments(cwd),
45
+ wanted === 'running' || wanted === 'stopped'
46
+ ? sources.running(cwd).catch(() => undefined)
47
+ : undefined,
48
+ ]);
49
+ return running === undefined
50
+ ? environments
51
+ : environments.filter(({ name }) => running.has(name) === (wanted === 'running'));
52
+ }
53
+ async function environmentCandidates(command, cwd, sources) {
54
+ const environments = await applicableEnvironments(command, cwd, sources);
55
+ return values(...environments.map(({ name, branch }) => ({ value: name, description: branch || '(detached)' })), ...(command === 'docker'
56
+ ? [
57
+ { value: '--', description: 'Compose arguments follow' },
58
+ ]
59
+ : []));
60
+ }
61
+ /**
62
+ * Completes the last word of `words`, the arguments typed after `wt`. The
63
+ * last word is the one under the cursor and may be empty.
64
+ */
65
+ export async function complete(words, sources) {
66
+ const before = words.slice(0, -1);
67
+ const current = words.at(-1) ?? '';
68
+ const previous = before.at(-1);
69
+ if (before.includes('--'))
70
+ return none;
71
+ if (previous !== undefined && workingDirOptions.includes(previous))
72
+ return { kind: 'directories' };
73
+ let parsed;
74
+ try {
75
+ parsed = extractWorkingDir(before);
76
+ }
77
+ catch {
78
+ return none;
79
+ }
80
+ const [command, ...args] = parsed.rest;
81
+ if (command === undefined) {
82
+ return current.startsWith('-')
83
+ ? values(...globalOptions)
84
+ : commandCandidates();
85
+ }
86
+ if (command === 'help') {
87
+ return args.length === 0
88
+ ? commandCandidates()
89
+ : none;
90
+ }
91
+ if (!isCommand(command))
92
+ return none;
93
+ return completeArguments(command, args, current, {
94
+ cwd: async () => workingDirectory(parsed.workingDir),
95
+ sources,
96
+ });
97
+ }
98
+ /** Completes the word after `wt <command> <args...>`. */
99
+ async function completeArguments(command, args, current, { cwd, sources }) {
100
+ const previous = args.at(-1);
101
+ const takesValue = valueOptions(command);
102
+ if (previous === '--format' && takesValue.has('--format'))
103
+ return values({ value: 'text', description: 'For people (default)' }, { value: 'json', description: 'For scripts and agents' });
104
+ if (previous !== undefined && takesValue.has(previous))
105
+ return values(...(await sources.branches(await cwd())).map(value => ({ value, description: '' })));
106
+ if (current.startsWith('-'))
107
+ return optionCandidates(command);
108
+ const positionals = args.filter((arg, index) => !arg.startsWith('-') && !takesValue.has(args[index - 1]));
109
+ if (positionals.length > 0) {
110
+ return command === 'docker'
111
+ ? values({ value: '--', description: 'Compose arguments follow' })
112
+ : none;
113
+ }
114
+ if (command === 'completion')
115
+ return values(...shells.map(value => ({ value, description: '' })));
116
+ return commands[command].environment !== false
117
+ ? environmentCandidates(command, await cwd(), sources)
118
+ : none;
119
+ }
120
+ export function formatCompletion(completion) {
121
+ if (completion.kind === 'directories')
122
+ return 'directories\n';
123
+ return `values\n${completion.values.map(({ value, description }) => `${value}\t${description}\n`).join('')}`;
124
+ }
125
+ const zsh = `#compdef wt
126
+ # zsh completion for wt. Load it with: source <(wt completion zsh)
127
+ _wt() {
128
+ local -a lines described
129
+ local line value description
130
+ lines=("\${(@f)$(wt __complete -- "\${(@Q)words[2,CURRENT]}" 2>/dev/null)}")
131
+ case $lines[1] in
132
+ directories) _directories ;;
133
+ values)
134
+ for line in "\${(@)lines[2,-1]}"; do
135
+ [[ -z $line ]] && continue
136
+ value=\${line%%$'\\t'*}
137
+ description=\${line#*$'\\t'}
138
+ value=\${value//:/\\\\:}
139
+ if [[ -n $description ]]; then
140
+ described+=("$value:$description")
141
+ else
142
+ described+=("$value")
143
+ fi
144
+ done
145
+ (( $#described )) && _describe -t wt-values wt described
146
+ ;;
147
+ esac
148
+ }
149
+ if [[ $zsh_eval_context[-1] == loadautofunc ]]; then
150
+ _wt "$@"
151
+ else
152
+ compdef _wt wt
153
+ fi
154
+ `;
155
+ const bash = `# bash completion for wt. Load it with: eval "$(wt completion bash)"
156
+ # Written for bash 3.2 too, which mangles array slices when IFS is changed.
157
+ _wt() {
158
+ local cur=\${COMP_WORDS[COMP_CWORD]} tab=$'\\t' candidates= i
159
+ local -a args lines
160
+ args=("\${COMP_WORDS[@]:1:COMP_CWORD}")
161
+ local IFS=$'\\n'
162
+ lines=($(wt __complete -- "\${args[@]}" 2>/dev/null))
163
+ case \${lines[0]} in
164
+ directories)
165
+ compopt -o filenames 2>/dev/null
166
+ COMPREPLY=($(compgen -d -- "$cur"))
167
+ ;;
168
+ values)
169
+ for ((i = 1; i < \${#lines[@]}; i++)); do
170
+ candidates+="\${lines[i]%%"$tab"*}"$'\\n'
171
+ done
172
+ COMPREPLY=($(compgen -W "$candidates" -- "$cur"))
173
+ ;;
174
+ esac
175
+ }
176
+ complete -F _wt wt
177
+ `;
178
+ export const completionScripts = { zsh, bash };
@@ -0,0 +1,46 @@
1
+ import { access, readFile } from 'node:fs/promises';
2
+ import { parse } from 'yaml';
3
+ import { parseConfig } from './schema.js';
4
+ export async function configPath(root, fallback) {
5
+ for (const directory of new Set([root, fallback])) {
6
+ const path = `${directory}/.wt.yml`;
7
+ try {
8
+ await access(path);
9
+ return path;
10
+ }
11
+ catch (error) {
12
+ if (error.code !== 'ENOENT')
13
+ throw error;
14
+ }
15
+ }
16
+ }
17
+ export async function loadConfig(root, path) {
18
+ if (path === null)
19
+ return parseConfig({});
20
+ const file = path ?? `${root}/.wt.yml`;
21
+ let source;
22
+ try {
23
+ source = await readFile(file, 'utf8');
24
+ }
25
+ catch (error) {
26
+ if (error.code === 'ENOENT') {
27
+ if (path === undefined)
28
+ return parseConfig({});
29
+ throw new Error(`Configuration file ${file} is missing. Restore it before retrying.`, { cause: error });
30
+ }
31
+ throw error;
32
+ }
33
+ let input;
34
+ try {
35
+ input = parse(source, { uniqueKeys: true, strict: true });
36
+ }
37
+ catch (error) {
38
+ throw new Error(`${file}: invalid YAML syntax: ${error.message}`);
39
+ }
40
+ try {
41
+ return parseConfig(input);
42
+ }
43
+ catch (error) {
44
+ throw new Error(`${file}: ${error.message}`);
45
+ }
46
+ }
@@ -0,0 +1,57 @@
1
+ import { z } from 'zod';
2
+ const relativePath = z.string().min(1).transform(value => value.split('/').filter(part => part !== '.').join('/').replace(/\/+$/, '')).refine((value) => {
3
+ if (value.startsWith('~') || value.startsWith('/') || value.includes('\\'))
4
+ return false;
5
+ return value.split('/').every(part => part !== '..' && part.toLowerCase() !== '.git' && part !== '');
6
+ }, 'must be a normalized relative path without ..');
7
+ const hook = z.union([
8
+ relativePath,
9
+ z.object({
10
+ script: z.string().refine(value => value.trim().length > 0, 'must not be empty'),
11
+ }).strict(),
12
+ ]);
13
+ function emptySection(input) {
14
+ return input === null
15
+ ? undefined
16
+ : input;
17
+ }
18
+ const hookGroup = z.preprocess(emptySection, z.object({
19
+ before_create: hook.optional(),
20
+ after_create: hook.optional(),
21
+ }).strict().optional());
22
+ 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
+ }).strict();
26
+ export const configSchema = z.object({
27
+ host: host.optional(),
28
+ 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([])),
32
+ hooks: z.preprocess(emptySection, z.object({
33
+ worktree: hookGroup,
34
+ source: hookGroup,
35
+ }).strict().default({})),
36
+ }).strict().superRefine((config, ctx) => {
37
+ const paths = new Set();
38
+ for (const path of config.copy) {
39
+ const overlap = [...paths].find(previous => previous === path || path.startsWith(`${previous}/`) || previous.startsWith(`${path}/`));
40
+ if (overlap !== undefined) {
41
+ ctx.addIssue({
42
+ code: 'custom',
43
+ path: ['copy'],
44
+ message: `overlapping paths: ${overlap} and ${path}`,
45
+ });
46
+ }
47
+ paths.add(path);
48
+ }
49
+ });
50
+ export function parseConfig(input) {
51
+ if (typeof input === 'object' && input !== null && 'host' in input && 'worktrees' in input)
52
+ throw new Error('worktrees: cannot be combined with host; the host checkout\'s .wt.yml sets the worktree directory');
53
+ const result = configSchema.safeParse(input ?? {});
54
+ if (!result.success)
55
+ throw new Error(z.prettifyError(result.error));
56
+ return result.data;
57
+ }