@joberthel/worktree 1.3.0 → 1.5.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 +31 -7
- package/dist/cli-spec.js +49 -10
- package/dist/cli.js +70 -137
- package/dist/completion.js +3 -3
- package/dist/config/json-schema.js +4 -2
- package/dist/config/schema.js +15 -3
- package/dist/docker/compose.js +53 -4
- package/dist/docker/pause.js +36 -0
- package/dist/errors.js +5 -3
- package/dist/git/repository.js +40 -3
- package/dist/help.js +111 -0
- package/dist/operations/attached.js +35 -39
- package/dist/operations/commands.js +16 -5
- package/dist/operations/confirmation.js +11 -0
- package/dist/operations/create.js +69 -55
- package/dist/operations/locks.js +36 -0
- package/dist/operations/manage.js +50 -38
- package/dist/operations/progress.js +27 -0
- package/dist/operations/unlock.js +111 -0
- package/dist/shell-init.js +46 -0
- package/dist/state/lock-file.js +245 -0
- package/dist/state/process-start.js +29 -0
- package/dist/state/store.js +64 -19
- package/dist/ui/show-operation.js +9 -3
- package/package.json +1 -1
- package/schema/wt.schema.json +36 -4
- package/dist/cli.test/harness.js +0 -64
- package/dist/operations/manage.test/fixture.js +0 -67
package/dist/docker/compose.js
CHANGED
|
@@ -4,9 +4,10 @@ import { basename, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
|
4
4
|
import process from 'node:process';
|
|
5
5
|
import { WtError } from '../errors.js';
|
|
6
6
|
import { repositoryInfo } from '../git/repository.js';
|
|
7
|
-
import { run } from '../operations/process.js';
|
|
7
|
+
import { checkInterrupted, run } from '../operations/process.js';
|
|
8
8
|
import { writeAtomicFile } from '../state/atomic-file.js';
|
|
9
9
|
import { StateStore } from '../state/store.js';
|
|
10
|
+
import { withPausedContainers } from './pause.js';
|
|
10
11
|
export async function docker(args, cwd, { project, timeout } = {}) {
|
|
11
12
|
return run('docker', args, cwd, {
|
|
12
13
|
env: project !== undefined
|
|
@@ -152,9 +153,21 @@ export async function prepareVolumeCopy(cwd) {
|
|
|
152
153
|
}
|
|
153
154
|
return image;
|
|
154
155
|
}
|
|
155
|
-
|
|
156
|
+
/** How many volumes are copied at the same time. */
|
|
157
|
+
const volumeCopyConcurrency = 3;
|
|
158
|
+
/**
|
|
159
|
+
* Clones the source volumes into new volumes of `owner` and returns them by
|
|
160
|
+
* logical name in the order of `sources`. Each new volume is passed to
|
|
161
|
+
* `onVolume` before it is created, one call at a time, so cleanup finds it
|
|
162
|
+
* after a failure. The volumes are created one after the other and then
|
|
163
|
+
* copied `volumeCopyConcurrency` at a time. With `pauseSource`, the
|
|
164
|
+
* containers that use the source volumes are paused before the first copy
|
|
165
|
+
* and unpaused once the last one has settled.
|
|
166
|
+
*/
|
|
167
|
+
export async function cloneNamedVolumes(sources, owner, cwd, { image, pauseSource }, onVolume) {
|
|
156
168
|
const { repositoryId: repoId, name } = owner;
|
|
157
169
|
const mapping = new Map();
|
|
170
|
+
const copies = [];
|
|
158
171
|
for (const [logicalName, source] of Object.entries(sources)) {
|
|
159
172
|
const target = `wt-${repoId}-${worktreeResourceName(name)}-${randomUUID()}`;
|
|
160
173
|
mapping.set(logicalName, target);
|
|
@@ -185,9 +198,16 @@ export async function cloneNamedVolumes(sources, owner, cwd, image, onVolume) {
|
|
|
185
198
|
const targetLabels = JSON.parse(targetLabelsRaw || 'null');
|
|
186
199
|
if (targetLabels?.['com.wt.repository'] !== repoId || targetLabels['com.wt.worktree'] !== name)
|
|
187
200
|
throw new Error(`Refusing to clone data into volume ${target}: ownership labels do not match this repository and worktree.`);
|
|
201
|
+
copies.push({ source, target, sourceBefore });
|
|
202
|
+
}
|
|
203
|
+
const copyAll = async () => forEachLimited(copies, volumeCopyConcurrency, async ({ source, target, sourceBefore }) => {
|
|
188
204
|
await docker([
|
|
189
205
|
'run',
|
|
190
206
|
'--rm',
|
|
207
|
+
// As PID 1, bash would ignore an interrupt; docker-init passes it on to the whole copy.
|
|
208
|
+
'--init',
|
|
209
|
+
'-e',
|
|
210
|
+
'TINI_KILL_PROCESS_GROUP=1',
|
|
191
211
|
'-v',
|
|
192
212
|
`${source}:/src:ro`,
|
|
193
213
|
'-v',
|
|
@@ -204,11 +224,40 @@ export async function cloneNamedVolumes(sources, owner, cwd, image, onVolume) {
|
|
|
204
224
|
'{{json .}}',
|
|
205
225
|
source,
|
|
206
226
|
], cwd);
|
|
227
|
+
// This metadata changes when the volume is removed or recreated, but not when data is written to it.
|
|
207
228
|
if (sourceBefore !== sourceAfter)
|
|
208
|
-
throw new Error(`Source volume ${source}
|
|
209
|
-
}
|
|
229
|
+
throw new Error(`Source volume ${source} was removed or recreated while it was being cloned. Retry once the source project is stable.`);
|
|
230
|
+
});
|
|
231
|
+
await (pauseSource
|
|
232
|
+
? withPausedContainers(Object.values(sources), cwd, copyAll)
|
|
233
|
+
: copyAll());
|
|
210
234
|
return Object.fromEntries(mapping);
|
|
211
235
|
}
|
|
236
|
+
/**
|
|
237
|
+
* Runs `task` for each item, at most `limit` at a time. After a task fails or
|
|
238
|
+
* the operation is interrupted, it starts no further tasks, waits for the
|
|
239
|
+
* running ones to settle, and throws the first error.
|
|
240
|
+
*/
|
|
241
|
+
async function forEachLimited(items, limit, task) {
|
|
242
|
+
const errors = [];
|
|
243
|
+
const workers = Math.min(limit, items.length);
|
|
244
|
+
let next = 0;
|
|
245
|
+
const worker = async () => {
|
|
246
|
+
while (errors.length === 0 && next < items.length) {
|
|
247
|
+
const item = items[next++];
|
|
248
|
+
try {
|
|
249
|
+
checkInterrupted();
|
|
250
|
+
await task(item);
|
|
251
|
+
}
|
|
252
|
+
catch (error) {
|
|
253
|
+
errors.push(error);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
};
|
|
257
|
+
await Promise.all(Array.from({ length: workers }, worker));
|
|
258
|
+
if (errors.length > 0)
|
|
259
|
+
throw errors[0];
|
|
260
|
+
}
|
|
212
261
|
export function composeArgs(files, override, project, worktree, args) {
|
|
213
262
|
return [
|
|
214
263
|
'compose',
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { checkInterrupted, run, withoutOperationSignal } from '../operations/process.js';
|
|
2
|
+
/**
|
|
3
|
+
* Pauses the running containers that mount any of `volumes`, runs `work`, and
|
|
4
|
+
* unpauses them again, also when `work` fails or the operation is
|
|
5
|
+
* interrupted. Containers that do not run, such as ones that are paused
|
|
6
|
+
* already, are left alone.
|
|
7
|
+
*/
|
|
8
|
+
export async function withPausedContainers(volumes, cwd, work) {
|
|
9
|
+
// Without a volume filter, docker ps would list every running container.
|
|
10
|
+
if (volumes.length === 0)
|
|
11
|
+
return work();
|
|
12
|
+
// Docker ORs the volume filters and ANDs them with the status filter.
|
|
13
|
+
const running = await run('docker', [
|
|
14
|
+
'ps',
|
|
15
|
+
'--quiet',
|
|
16
|
+
'--no-trunc',
|
|
17
|
+
'--filter',
|
|
18
|
+
'status=running',
|
|
19
|
+
...volumes.flatMap(volume => ['--filter', `volume=${volume}`]),
|
|
20
|
+
], cwd);
|
|
21
|
+
const paused = [];
|
|
22
|
+
try {
|
|
23
|
+
for (const container of running.split('\n').filter(Boolean)) {
|
|
24
|
+
checkInterrupted();
|
|
25
|
+
// An interrupt lets the pause finish, so the container is unpaused exactly when it was paused.
|
|
26
|
+
await withoutOperationSignal(async () => run('docker', ['pause', container], cwd));
|
|
27
|
+
paused.push(container);
|
|
28
|
+
}
|
|
29
|
+
return await work();
|
|
30
|
+
}
|
|
31
|
+
finally {
|
|
32
|
+
// run() refuses to start a command once the operation is interrupted.
|
|
33
|
+
if (paused.length > 0)
|
|
34
|
+
await withoutOperationSignal(async () => run('docker', ['unpause', ...paused], cwd));
|
|
35
|
+
}
|
|
36
|
+
}
|
package/dist/errors.js
CHANGED
|
@@ -24,13 +24,15 @@ export const errorCodes = [
|
|
|
24
24
|
'not_ready',
|
|
25
25
|
/** `wt create` made the worktree but its setup failed; run `wt reset` or `wt rm`. */
|
|
26
26
|
'setup_failed',
|
|
27
|
-
/** `wt rm` or `wt
|
|
27
|
+
/** `wt rm`, `wt reset` or `wt unlock` needs `--force` without a terminal. */
|
|
28
28
|
'confirmation_required',
|
|
29
29
|
/** The current directory is inside the worktree that would be removed. */
|
|
30
30
|
'inside_worktree',
|
|
31
|
-
/** Another wt command holds the repository
|
|
31
|
+
/** Another wt command holds the lock of the worktree, its source, or the repository. */
|
|
32
32
|
'locked',
|
|
33
|
-
/**
|
|
33
|
+
/** `wt unlock` found no lock to remove. */
|
|
34
|
+
'not_locked',
|
|
35
|
+
/** The worktree or its lock changed while the command waited; retry it. */
|
|
34
36
|
'changed',
|
|
35
37
|
/** No single running Compose project belongs to the source checkout. */
|
|
36
38
|
'no_compose_project',
|
package/dist/git/repository.js
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
1
2
|
import { realpath } from 'node:fs/promises';
|
|
2
3
|
import { dirname, isAbsolute, resolve } from 'node:path';
|
|
3
4
|
import process from 'node:process';
|
|
4
5
|
import { WtError } from '../errors.js';
|
|
5
6
|
import { checkInterrupted, run } from '../operations/process.js';
|
|
6
7
|
import { StateStore } from '../state/store.js';
|
|
8
|
+
/** Lookups of repositoryInfo by directory, kept while withRepositoryCache runs. */
|
|
9
|
+
const repositoryCache = new AsyncLocalStorage();
|
|
7
10
|
const gitLocalVariables = [
|
|
8
11
|
'GIT_ALTERNATE_OBJECT_DIRECTORIES',
|
|
9
12
|
'GIT_CONFIG',
|
|
@@ -29,9 +32,16 @@ export function gitEnvironment() {
|
|
|
29
32
|
return env;
|
|
30
33
|
}
|
|
31
34
|
export async function git(args, cwd) {
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
+
try {
|
|
36
|
+
return await run('git', args, cwd, {
|
|
37
|
+
env: gitEnvironment(),
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
finally {
|
|
41
|
+
// Lookups from before a worktree was added or removed may be out of date.
|
|
42
|
+
if (args[0] === 'worktree' && args[1] !== 'list')
|
|
43
|
+
repositoryCache.getStore()?.clear();
|
|
44
|
+
}
|
|
35
45
|
}
|
|
36
46
|
/** Local branches and remote-tracking branches, without the `<remote>/HEAD` aliases. */
|
|
37
47
|
export async function listBranches(cwd) {
|
|
@@ -45,7 +55,34 @@ export async function listBranches(cwd) {
|
|
|
45
55
|
.filter(ref => ref !== '' && !ref.endsWith('/HEAD'))
|
|
46
56
|
.map(ref => ref.replace(/^refs\/(?:heads|remotes)\//, ''));
|
|
47
57
|
}
|
|
58
|
+
/**
|
|
59
|
+
* Runs `operation` with its own cache of repositoryInfo, so that a command
|
|
60
|
+
* asks Git about each directory once. Git commands that add or remove
|
|
61
|
+
* worktrees clear the cache.
|
|
62
|
+
*/
|
|
63
|
+
export async function withRepositoryCache(operation) {
|
|
64
|
+
return repositoryCache.run(new Map(), operation);
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* The checkout that contains `cwd`, the Git directory its worktrees share,
|
|
68
|
+
* and the main checkout. Inside withRepositoryCache, callers share one
|
|
69
|
+
* lookup per directory; a failed lookup is not kept.
|
|
70
|
+
*/
|
|
48
71
|
export async function repositoryInfo(cwd) {
|
|
72
|
+
const cache = repositoryCache.getStore();
|
|
73
|
+
if (cache === undefined)
|
|
74
|
+
return locateRepository(cwd);
|
|
75
|
+
let lookup = cache.get(cwd);
|
|
76
|
+
if (lookup === undefined) {
|
|
77
|
+
lookup = locateRepository(cwd).catch((error) => {
|
|
78
|
+
cache.delete(cwd);
|
|
79
|
+
throw error;
|
|
80
|
+
});
|
|
81
|
+
cache.set(cwd, lookup);
|
|
82
|
+
}
|
|
83
|
+
return lookup;
|
|
84
|
+
}
|
|
85
|
+
async function locateRepository(cwd) {
|
|
49
86
|
const common = await git(['rev-parse', '--git-common-dir'], cwd).catch((error) => {
|
|
50
87
|
if (error instanceof Error && /not a git repository/i.test(error.message))
|
|
51
88
|
throw new WtError('not_a_repository', 'Run wt from a Git checkout or its repository directory.', { cause: error });
|
package/dist/help.js
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { commandOptions, commands, printsScript } from './cli-spec.js';
|
|
3
|
+
/*
|
|
4
|
+
* Help for people and, with `--format json`, for scripts and coding agents.
|
|
5
|
+
* Both are read from the command table in cli-spec.ts.
|
|
6
|
+
*/
|
|
7
|
+
const description = 'Manage isolated Git worktrees with Docker Compose.';
|
|
8
|
+
const workingDirOption = {
|
|
9
|
+
name: '--working-dir',
|
|
10
|
+
alias: '-w',
|
|
11
|
+
value: '<dir>',
|
|
12
|
+
description: 'Run as if wt was started in <dir>',
|
|
13
|
+
repeatable: false,
|
|
14
|
+
};
|
|
15
|
+
const formatOption = {
|
|
16
|
+
name: '--format',
|
|
17
|
+
alias: null,
|
|
18
|
+
value: '<text|json>',
|
|
19
|
+
description: 'Output format (default: text, or WT_FORMAT)',
|
|
20
|
+
repeatable: false,
|
|
21
|
+
};
|
|
22
|
+
/** The commands without JSON output, as help names them. */
|
|
23
|
+
const textOnlyCommands = new Intl.ListFormat('en').format(Object.entries(commands).filter(([, spec]) => !spec.shared).map(([name]) => name));
|
|
24
|
+
function optionHelp(command) {
|
|
25
|
+
return [
|
|
26
|
+
...commandOptions(command).map(([name, { type, value, description }]) => ({
|
|
27
|
+
name: `--${name}`,
|
|
28
|
+
alias: null,
|
|
29
|
+
value: value ?? null,
|
|
30
|
+
description,
|
|
31
|
+
repeatable: type === 'strings',
|
|
32
|
+
})),
|
|
33
|
+
...(printsScript(command)
|
|
34
|
+
? []
|
|
35
|
+
: [workingDirOption]),
|
|
36
|
+
...(commands[command].shared
|
|
37
|
+
? [formatOption]
|
|
38
|
+
: []),
|
|
39
|
+
];
|
|
40
|
+
}
|
|
41
|
+
function optionFlags({ name, alias, value }) {
|
|
42
|
+
return `${alias === null
|
|
43
|
+
? ''
|
|
44
|
+
: `${alias}, `}${name}${value === null
|
|
45
|
+
? ''
|
|
46
|
+
: ` ${value}`}`;
|
|
47
|
+
}
|
|
48
|
+
function commandUsage(command) {
|
|
49
|
+
return `wt ${command} ${commands[command].usage}`.trimEnd();
|
|
50
|
+
}
|
|
51
|
+
export function usage(command) {
|
|
52
|
+
if (command !== undefined) {
|
|
53
|
+
const options = optionHelp(command).map(option => [
|
|
54
|
+
optionFlags(option),
|
|
55
|
+
option.description,
|
|
56
|
+
]);
|
|
57
|
+
const width = Math.max(...options.map(([flags]) => flags.length));
|
|
58
|
+
const optionList = options.length
|
|
59
|
+
? `\n\nOptions:\n${options.map(([flags, text]) => ` ${flags.padEnd(width)} ${text}`).join('\n')}`
|
|
60
|
+
: '';
|
|
61
|
+
return `Usage: ${commandUsage(command)}\n\n${commands[command].summary}${optionList}`;
|
|
62
|
+
}
|
|
63
|
+
const width = Math.max(...Object.keys(commands).map(name => name.length));
|
|
64
|
+
const list = Object.entries(commands).map(([name, spec]) => ` ${name.padEnd(width)} ${spec.usage.padEnd(43)} ${spec.summary}`).join('\n');
|
|
65
|
+
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 ${textOnlyCommands}\n -h, --help Show help\n -v, --version Show the version`;
|
|
66
|
+
}
|
|
67
|
+
function commandHelpJson(command) {
|
|
68
|
+
return {
|
|
69
|
+
name: command,
|
|
70
|
+
usage: commandUsage(command),
|
|
71
|
+
summary: commands[command].summary,
|
|
72
|
+
options: optionHelp(command),
|
|
73
|
+
formats: commands[command].shared
|
|
74
|
+
? ['text', 'json']
|
|
75
|
+
: ['text'],
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
/** `--help --format json`: the commands and options, read from the same table as the text help. */
|
|
79
|
+
export function helpJson(command) {
|
|
80
|
+
if (command !== undefined)
|
|
81
|
+
return commandHelpJson(command);
|
|
82
|
+
return {
|
|
83
|
+
name: 'wt',
|
|
84
|
+
description,
|
|
85
|
+
version: version(),
|
|
86
|
+
usage: 'wt [-w <dir>] <command>',
|
|
87
|
+
commands: Object.keys(commands).map(name => commandHelpJson(name)),
|
|
88
|
+
options: [
|
|
89
|
+
workingDirOption,
|
|
90
|
+
{ ...formatOption, description: `Output format, for all commands except ${textOnlyCommands} (default: text, or WT_FORMAT)` },
|
|
91
|
+
{
|
|
92
|
+
name: '--help',
|
|
93
|
+
alias: '-h',
|
|
94
|
+
value: null,
|
|
95
|
+
description: 'Show help',
|
|
96
|
+
repeatable: false,
|
|
97
|
+
},
|
|
98
|
+
{
|
|
99
|
+
name: '--version',
|
|
100
|
+
alias: '-v',
|
|
101
|
+
value: null,
|
|
102
|
+
description: 'Show the version',
|
|
103
|
+
repeatable: false,
|
|
104
|
+
},
|
|
105
|
+
],
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
export function version() {
|
|
109
|
+
const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
|
|
110
|
+
return pkg.version;
|
|
111
|
+
}
|
|
@@ -7,10 +7,10 @@ import { WtError } from '../errors.js';
|
|
|
7
7
|
import { git, repositoryInfo } from '../git/repository.js';
|
|
8
8
|
import { AttachedStore, StateStore } from '../state/store.js';
|
|
9
9
|
import { copyConfiguredPaths } from './copy-paths.js';
|
|
10
|
-
import {
|
|
10
|
+
import { createManagedEnvironment, loadCreateConfig, planCheckout, validateHookRevision } from './create.js';
|
|
11
11
|
import { validateSourceHooks, validateWorktreeHooks } from './hooks.js';
|
|
12
|
+
import { sourceLock, withLocks, worktreeLock } from './locks.js';
|
|
12
13
|
import { checkUnchanged, exists, prepareReset, removeLocked, requestConfirmation, resetLocked, validateCopyAndHooks } from './manage.js';
|
|
13
|
-
import { checkInterrupted } from './process.js';
|
|
14
14
|
import { runStep } from './progress.js';
|
|
15
15
|
function isInside(parent, child) {
|
|
16
16
|
const path = relative(parent, child);
|
|
@@ -65,9 +65,16 @@ async function checkAbsent(path) {
|
|
|
65
65
|
/**
|
|
66
66
|
* Creates a worktree of this repository nested in a new detached worktree of
|
|
67
67
|
* its host repository, with the host's Docker environment. The host checkout
|
|
68
|
-
* gets no branch; the attached worktree gets the requested one.
|
|
68
|
+
* gets no branch; the attached worktree gets the requested one. The attached
|
|
69
|
+
* worktree stays locked while it is set up.
|
|
69
70
|
*/
|
|
70
|
-
export async function createAttached(name, options,
|
|
71
|
+
export async function createAttached(name, options, settings, progress) {
|
|
72
|
+
const store = new StateStore(settings.repository.gitCommonDir);
|
|
73
|
+
return withLocks([
|
|
74
|
+
worktreeLock(store, name),
|
|
75
|
+
], async () => createAttachedLocked(name, options, store, settings, progress));
|
|
76
|
+
}
|
|
77
|
+
async function createAttachedLocked(name, options, store, { repository, config, configurationPath }, progress) {
|
|
71
78
|
const { root, gitCommonDir } = repository;
|
|
72
79
|
const { host, mountPath } = await locateHost(root, config.host.path, progress);
|
|
73
80
|
const attached = new AttachedStore(gitCommonDir);
|
|
@@ -80,7 +87,6 @@ export async function createAttached(name, options, { repository, config, config
|
|
|
80
87
|
await access(resolve(root, path));
|
|
81
88
|
const hostName = `${worktreeResourceName(basename(mountPath)) || 'attached'}/${name}`;
|
|
82
89
|
const hostStore = new StateStore(host.gitCommonDir);
|
|
83
|
-
const unlock = await hostStore.lock('repository');
|
|
84
90
|
let state;
|
|
85
91
|
try {
|
|
86
92
|
const hostConfig = await loadCreateConfig(host, progress);
|
|
@@ -107,7 +113,7 @@ export async function createAttached(name, options, { repository, config, config
|
|
|
107
113
|
const { path } = state;
|
|
108
114
|
await checkAbsent(path);
|
|
109
115
|
await mkdir(dirname(path), { recursive: true });
|
|
110
|
-
await runStep(progress, `Creating Git worktree ${name} at ${mountPath}`, async () => git(plan.args(path), root));
|
|
116
|
+
await store.withRepositoryLock(async () => runStep(progress, `Creating Git worktree ${name} at ${mountPath}`, async () => git(plan.args(path), root)));
|
|
111
117
|
if (config.copy.length > 0)
|
|
112
118
|
await runStep(progress, `Copying configured files into ${mountPath}`, async () => copyConfiguredPaths(root, path, config.copy));
|
|
113
119
|
await validateWorktreeHooks(config.hooks, path);
|
|
@@ -116,7 +122,7 @@ export async function createAttached(name, options, { repository, config, config
|
|
|
116
122
|
attachedLayer(config, state, environment),
|
|
117
123
|
],
|
|
118
124
|
};
|
|
119
|
-
const result = await
|
|
125
|
+
const result = await createManagedEnvironment(hostName, { detach: true, from: config.host.from }, host, hostStore, { ...hostConfig, nested, progress });
|
|
120
126
|
await attached.save({ ...state, status: 'ready' });
|
|
121
127
|
return { path: state.path, projectName: result.projectName };
|
|
122
128
|
}
|
|
@@ -129,9 +135,6 @@ export async function createAttached(name, options, { repository, config, config
|
|
|
129
135
|
}
|
|
130
136
|
throw error;
|
|
131
137
|
}
|
|
132
|
-
finally {
|
|
133
|
-
await unlock();
|
|
134
|
-
}
|
|
135
138
|
}
|
|
136
139
|
async function hostOf(state) {
|
|
137
140
|
const store = new StateStore(state.host.gitCommonDir);
|
|
@@ -152,22 +155,6 @@ async function isRegistered(path, cwd) {
|
|
|
152
155
|
], cwd);
|
|
153
156
|
return listed.split('\0').includes(`worktree ${target}`);
|
|
154
157
|
}
|
|
155
|
-
async function withLocks(store, hostStore, work) {
|
|
156
|
-
const unlock = await store.lock('repository');
|
|
157
|
-
try {
|
|
158
|
-
const unlockHost = await hostStore.lock('repository');
|
|
159
|
-
try {
|
|
160
|
-
checkInterrupted();
|
|
161
|
-
return await work();
|
|
162
|
-
}
|
|
163
|
-
finally {
|
|
164
|
-
await unlockHost();
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
finally {
|
|
168
|
-
await unlock();
|
|
169
|
-
}
|
|
170
|
-
}
|
|
171
158
|
/**
|
|
172
159
|
* Removes the attached worktree, then its host worktree and Docker
|
|
173
160
|
* environment. The attached branch is kept.
|
|
@@ -208,20 +195,25 @@ export async function removeAttached({ state, attached, store }, cwd, force = fa
|
|
|
208
195
|
if (!await requestConfirmation(request, confirm))
|
|
209
196
|
return false;
|
|
210
197
|
}
|
|
211
|
-
await withLocks(
|
|
198
|
+
await withLocks([
|
|
199
|
+
worktreeLock(store, name),
|
|
200
|
+
worktreeLock(hostStore, state.host.name),
|
|
201
|
+
], async () => {
|
|
212
202
|
await checkUnchanged(attached, state);
|
|
213
203
|
await attached.save({ ...state, status: 'removing' });
|
|
214
|
-
|
|
215
|
-
await
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
204
|
+
await store.withRepositoryLock(async () => {
|
|
205
|
+
if (await isRegistered(state.path, state.sourceWorktreePath)) {
|
|
206
|
+
await runStep(progress, `Removing Git worktree ${name}`, async () => git([
|
|
207
|
+
'worktree',
|
|
208
|
+
'remove',
|
|
209
|
+
'--force',
|
|
210
|
+
state.path,
|
|
211
|
+
], state.sourceWorktreePath));
|
|
212
|
+
}
|
|
213
|
+
else if (await exists(state.path)) {
|
|
214
|
+
throw new Error(`Unregistered directory still exists at ${state.path}. Move it out of the way and retry wt rm ${name}.`);
|
|
215
|
+
}
|
|
216
|
+
});
|
|
225
217
|
const current = await hostStore.find(state.host.name);
|
|
226
218
|
if (current !== undefined)
|
|
227
219
|
await removeLocked(current, hostStore, state.host.repositoryRoot, progress, name);
|
|
@@ -264,7 +256,11 @@ export async function resetAttached({ state, attached, store }, force = false, c
|
|
|
264
256
|
if (!await requestConfirmation(request, confirm))
|
|
265
257
|
return false;
|
|
266
258
|
}
|
|
267
|
-
await withLocks(
|
|
259
|
+
await withLocks([
|
|
260
|
+
worktreeLock(store, name),
|
|
261
|
+
worktreeLock(hostStore, state.host.name),
|
|
262
|
+
sourceLock(hostStore, host.sourceProject, state.host.name),
|
|
263
|
+
], async () => {
|
|
268
264
|
await checkUnchanged(attached, state);
|
|
269
265
|
await checkUnchanged(hostStore, host);
|
|
270
266
|
if (host.status === 'removing' || state.status === 'removing')
|
|
@@ -5,8 +5,9 @@ import { WtError } from '../errors.js';
|
|
|
5
5
|
import { repositoryInfo } from '../git/repository.js';
|
|
6
6
|
import { AttachedStore, StateStore } from '../state/store.js';
|
|
7
7
|
import { attachedHost, createAttached, removeAttached, resetAttached } from './attached.js';
|
|
8
|
-
import {
|
|
8
|
+
import { createManagedEnvironment, withCreateContext } from './create.js';
|
|
9
9
|
import * as manage from './manage.js';
|
|
10
|
+
export { unlockEnvironment } from './unlock.js';
|
|
10
11
|
/*
|
|
11
12
|
* Entry points of the CLI. A name refers to an environment of the current
|
|
12
13
|
* repository or to a worktree attached to an environment of a host
|
|
@@ -14,7 +15,7 @@ import * as manage from './manage.js';
|
|
|
14
15
|
*/
|
|
15
16
|
export async function createEnvironment(name, options, cwd, progress) {
|
|
16
17
|
return withCreateContext(name, options, cwd, progress, async (repository, store, loaded) => loaded.config.host === undefined
|
|
17
|
-
?
|
|
18
|
+
? createManagedEnvironment(name, options, repository, store, { ...loaded, progress })
|
|
18
19
|
: createAttached(name, options, { repository, ...loaded }, progress));
|
|
19
20
|
}
|
|
20
21
|
async function findAttached(name, cwd) {
|
|
@@ -49,12 +50,13 @@ export async function listEnvironments(cwd) {
|
|
|
49
50
|
}));
|
|
50
51
|
}
|
|
51
52
|
async function listedEnvironments(cwd) {
|
|
52
|
-
const own = await manage.listEnvironments(cwd);
|
|
53
53
|
const { gitCommonDir } = await repositoryInfo(cwd);
|
|
54
54
|
const states = await new AttachedStore(gitCommonDir).list();
|
|
55
55
|
if (states.length === 0)
|
|
56
|
-
return
|
|
56
|
+
return manage.listEnvironments(cwd);
|
|
57
|
+
// One docker ps serves the own and the attached worktrees.
|
|
57
58
|
const dockerStatus = await manage.dockerStatuses(cwd);
|
|
59
|
+
const own = await manage.listEnvironments(cwd, dockerStatus);
|
|
58
60
|
const rows = await Promise.all(states.map(async (state) => {
|
|
59
61
|
const host = await attachedHost(state);
|
|
60
62
|
return {
|
|
@@ -92,6 +94,15 @@ export async function listEnvironmentNames(cwd) {
|
|
|
92
94
|
.map(({ name, branch }) => ({ name, branch }))
|
|
93
95
|
.sort((a, b) => a.name.localeCompare(b.name));
|
|
94
96
|
}
|
|
97
|
+
/**
|
|
98
|
+
* The path of an environment's worktree, read from the state files only. It
|
|
99
|
+
* never asks Docker, so `wt path` and `wt cd` stay fast.
|
|
100
|
+
*/
|
|
101
|
+
export async function environmentPath(name, cwd) {
|
|
102
|
+
const { gitCommonDir } = await repositoryInfo(cwd);
|
|
103
|
+
const state = await new AttachedStore(gitCommonDir).find(name) ?? await new StateStore(gitCommonDir).get(name);
|
|
104
|
+
return state.path;
|
|
105
|
+
}
|
|
95
106
|
/**
|
|
96
107
|
* Names of the environments whose Compose services run. It asks Docker once
|
|
97
108
|
* and gives up after `timeout` milliseconds, so it suits shell completion.
|
|
@@ -148,7 +159,7 @@ export async function composeOperation(name, action, args, cwd, progress) {
|
|
|
148
159
|
const hostStore = new StateStore(state.host.gitCommonDir);
|
|
149
160
|
const unlock = action === 'docker'
|
|
150
161
|
? undefined
|
|
151
|
-
: await hostStore.
|
|
162
|
+
: await hostStore.lockWorktree(state.host.name);
|
|
152
163
|
try {
|
|
153
164
|
return await manage.runManagedCompose(await hostStore.get(state.host.name), action, args, progress);
|
|
154
165
|
}
|
|
@@ -25,3 +25,14 @@ export function formatDryRun(request) {
|
|
|
25
25
|
'Dry run: nothing was changed.',
|
|
26
26
|
].join('\n');
|
|
27
27
|
}
|
|
28
|
+
/** Runs an operation up to its confirmation, declines it, and returns what it asked. */
|
|
29
|
+
export async function preview(operation) {
|
|
30
|
+
let request;
|
|
31
|
+
await operation(async (asked) => {
|
|
32
|
+
request = asked;
|
|
33
|
+
return false;
|
|
34
|
+
});
|
|
35
|
+
if (request === undefined)
|
|
36
|
+
throw new Error('The operation finished without asking for confirmation.');
|
|
37
|
+
return request;
|
|
38
|
+
}
|