@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/LICENSE +21 -0
- package/README.md +315 -2
- package/dist/cli-spec.js +138 -0
- package/dist/cli.js +264 -0
- package/dist/completion.js +178 -0
- package/dist/config/load.js +46 -0
- package/dist/config/schema.js +57 -0
- package/dist/docker/compose.js +253 -0
- package/dist/git/repository.js +196 -0
- package/dist/operations/attached.js +294 -0
- package/dist/operations/commands.js +158 -0
- package/dist/operations/confirmation.js +15 -0
- package/dist/operations/copy-paths.js +109 -0
- package/dist/operations/create.js +255 -0
- package/dist/operations/hooks.js +113 -0
- package/dist/operations/manage.js +446 -0
- package/dist/operations/manage.test/fixture.js +67 -0
- package/dist/operations/process.js +122 -0
- package/dist/operations/progress.js +28 -0
- package/dist/state/atomic-file.js +14 -0
- package/dist/state/store.js +162 -0
- package/dist/ui/confirmation-prompt.js +48 -0
- package/dist/ui/environment-info.js +85 -0
- package/dist/ui/environment-table.js +43 -0
- package/dist/ui/format-status.js +29 -0
- package/dist/ui/hook-log-panel.js +57 -0
- package/dist/ui/json-output.js +41 -0
- package/dist/ui/operation-view.js +33 -0
- package/dist/ui/progress-state.js +111 -0
- package/dist/ui/progress.js +16 -0
- package/dist/ui/show-operation.js +56 -0
- package/dist/ui/use-progress.js +34 -0
- package/package.json +72 -3
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
import { access, lstat, mkdir, realpath } from 'node:fs/promises';
|
|
2
|
+
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
3
|
+
import process from 'node:process';
|
|
4
|
+
import { loadConfig } from '../config/load.js';
|
|
5
|
+
import { worktreeResourceName } from '../docker/compose.js';
|
|
6
|
+
import { git, repositoryInfo } from '../git/repository.js';
|
|
7
|
+
import { AttachedStore, StateStore } from '../state/store.js';
|
|
8
|
+
import { copyConfiguredPaths } from './copy-paths.js';
|
|
9
|
+
import { createEnvironmentLocked, loadCreateConfig, planCheckout, validateHookRevision } from './create.js';
|
|
10
|
+
import { validateSourceHooks, validateWorktreeHooks } from './hooks.js';
|
|
11
|
+
import { checkUnchanged, exists, prepareReset, removeLocked, requestConfirmation, resetLocked, validateCopyAndHooks } from './manage.js';
|
|
12
|
+
import { checkInterrupted } from './process.js';
|
|
13
|
+
import { runStep } from './progress.js';
|
|
14
|
+
function isInside(parent, child) {
|
|
15
|
+
const path = relative(parent, child);
|
|
16
|
+
return path !== '' && path !== '..' && !path.startsWith(`..${sep}`) && !isAbsolute(path);
|
|
17
|
+
}
|
|
18
|
+
async function locateHost(root, path, progress) {
|
|
19
|
+
const hostPath = resolve(root, path);
|
|
20
|
+
const host = await runStep(progress, `Locating host checkout ${hostPath}`, async () => repositoryInfo(hostPath).catch((error) => {
|
|
21
|
+
throw new Error(`host.path ${path} does not point to a Git checkout: ${hostPath}`, { cause: error });
|
|
22
|
+
}));
|
|
23
|
+
if (await realpath(hostPath) !== host.root)
|
|
24
|
+
throw new Error(`host.path must point to the root of a Git checkout; ${hostPath} is inside ${host.root}.`);
|
|
25
|
+
const mountPath = relative(host.root, root);
|
|
26
|
+
if (!isInside(host.root, root))
|
|
27
|
+
throw new Error(`This checkout must be inside its host checkout ${host.root}.`);
|
|
28
|
+
return { host, mountPath };
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Hook layer of an attached worktree. Its hooks address the host environment
|
|
32
|
+
* through Compose variables and run in the attached checkouts.
|
|
33
|
+
*/
|
|
34
|
+
export function attachedLayer(config, state, environment) {
|
|
35
|
+
return {
|
|
36
|
+
scope: basename(state.mountPath),
|
|
37
|
+
hooks: config.hooks,
|
|
38
|
+
environment: {
|
|
39
|
+
...environment,
|
|
40
|
+
name: state.name,
|
|
41
|
+
branch: state.branch,
|
|
42
|
+
path: state.path,
|
|
43
|
+
sourceWorktreePath: state.sourceWorktreePath,
|
|
44
|
+
variables: {
|
|
45
|
+
HOST_WORKTREE_NAME: worktreeResourceName(environment.name),
|
|
46
|
+
HOST_WORKTREE_ORIGINAL_NAME: environment.name,
|
|
47
|
+
HOST_WORKTREE_PATH: environment.path,
|
|
48
|
+
HOST_SOURCE_WORKTREE_PATH: environment.sourceWorktreePath,
|
|
49
|
+
},
|
|
50
|
+
},
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
async function checkAbsent(path) {
|
|
54
|
+
try {
|
|
55
|
+
await lstat(path);
|
|
56
|
+
}
|
|
57
|
+
catch (error) {
|
|
58
|
+
if (error.code === 'ENOENT')
|
|
59
|
+
return;
|
|
60
|
+
throw error;
|
|
61
|
+
}
|
|
62
|
+
throw new Error(`The host worktree already contains ${path}. Remove it from the host repository or stop tracking it there.`);
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Creates a worktree of this repository nested in a new detached worktree of
|
|
66
|
+
* its host repository, with the host's Docker environment. The host checkout
|
|
67
|
+
* gets no branch; the attached worktree gets the requested one.
|
|
68
|
+
*/
|
|
69
|
+
export async function createAttached(name, options, { repository, config, configurationPath }, progress) {
|
|
70
|
+
const { root, gitCommonDir } = repository;
|
|
71
|
+
const { host, mountPath } = await locateHost(root, config.host.path, progress);
|
|
72
|
+
const attached = new AttachedStore(gitCommonDir);
|
|
73
|
+
if ((await attached.list()).some(item => item.name.toLowerCase() === name.toLowerCase()))
|
|
74
|
+
throw new Error(`Worktree ${name} is already managed.`);
|
|
75
|
+
const plan = await planCheckout(name, options, root, progress);
|
|
76
|
+
await validateHookRevision(config, root, plan.revision);
|
|
77
|
+
await validateSourceHooks(config.hooks, root);
|
|
78
|
+
for (const path of config.copy)
|
|
79
|
+
await access(resolve(root, path));
|
|
80
|
+
const hostName = `${worktreeResourceName(basename(mountPath)) || 'attached'}/${name}`;
|
|
81
|
+
const hostStore = new StateStore(host.gitCommonDir);
|
|
82
|
+
const unlock = await hostStore.lock('repository');
|
|
83
|
+
let state;
|
|
84
|
+
try {
|
|
85
|
+
const hostConfig = await loadCreateConfig(host, progress);
|
|
86
|
+
if (hostConfig.config.host !== undefined)
|
|
87
|
+
throw new Error(`The host checkout ${host.root} sets host itself; nested hosts are not supported.`);
|
|
88
|
+
const nested = {
|
|
89
|
+
retryName: name,
|
|
90
|
+
planned: async (target) => {
|
|
91
|
+
state = {
|
|
92
|
+
schemaVersion: 1,
|
|
93
|
+
name,
|
|
94
|
+
path: join(target, mountPath),
|
|
95
|
+
branch: plan.branch,
|
|
96
|
+
sourceWorktreePath: root,
|
|
97
|
+
configurationPath,
|
|
98
|
+
mountPath,
|
|
99
|
+
host: { gitCommonDir: host.gitCommonDir, repositoryRoot: host.repositoryRoot, name: hostName },
|
|
100
|
+
status: 'creating',
|
|
101
|
+
};
|
|
102
|
+
await attached.save(state);
|
|
103
|
+
return { gitCommonDir, name, path: state.path };
|
|
104
|
+
},
|
|
105
|
+
checkedOut: async () => {
|
|
106
|
+
const { path } = state;
|
|
107
|
+
await checkAbsent(path);
|
|
108
|
+
await mkdir(dirname(path), { recursive: true });
|
|
109
|
+
await runStep(progress, `Creating Git worktree ${name} at ${mountPath}`, async () => git(plan.args(path), root));
|
|
110
|
+
if (config.copy.length > 0)
|
|
111
|
+
await runStep(progress, `Copying configured files into ${mountPath}`, async () => copyConfiguredPaths(root, path, config.copy));
|
|
112
|
+
await validateWorktreeHooks(config.hooks, path);
|
|
113
|
+
},
|
|
114
|
+
layers: environment => [
|
|
115
|
+
attachedLayer(config, state, environment),
|
|
116
|
+
],
|
|
117
|
+
};
|
|
118
|
+
const result = await createEnvironmentLocked(hostName, { detach: true, from: config.host.from }, host, hostStore, { ...hostConfig, nested, progress });
|
|
119
|
+
await attached.save({ ...state, status: 'ready' });
|
|
120
|
+
return { path: state.path, projectName: result.projectName };
|
|
121
|
+
}
|
|
122
|
+
catch (error) {
|
|
123
|
+
if (state !== undefined) {
|
|
124
|
+
if (await hostStore.find(hostName) === undefined)
|
|
125
|
+
await attached.remove(name);
|
|
126
|
+
else
|
|
127
|
+
await attached.save({ ...state, status: 'failed', error: error.message });
|
|
128
|
+
}
|
|
129
|
+
throw error;
|
|
130
|
+
}
|
|
131
|
+
finally {
|
|
132
|
+
await unlock();
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
async function hostOf(state) {
|
|
136
|
+
const store = new StateStore(state.host.gitCommonDir);
|
|
137
|
+
return { store, host: await store.find(state.host.name) };
|
|
138
|
+
}
|
|
139
|
+
async function uncommittedChanges(path) {
|
|
140
|
+
if (!await exists(path))
|
|
141
|
+
return 0;
|
|
142
|
+
return (await git(['status', '--porcelain'], path)).split('\n').filter(Boolean).length;
|
|
143
|
+
}
|
|
144
|
+
async function isRegistered(path, cwd) {
|
|
145
|
+
const target = await realpath(path).catch(() => resolve(path));
|
|
146
|
+
const listed = await git([
|
|
147
|
+
'worktree',
|
|
148
|
+
'list',
|
|
149
|
+
'--porcelain',
|
|
150
|
+
'-z',
|
|
151
|
+
], cwd);
|
|
152
|
+
return listed.split('\0').includes(`worktree ${target}`);
|
|
153
|
+
}
|
|
154
|
+
async function withLocks(store, hostStore, work) {
|
|
155
|
+
const unlock = await store.lock('repository');
|
|
156
|
+
try {
|
|
157
|
+
const unlockHost = await hostStore.lock('repository');
|
|
158
|
+
try {
|
|
159
|
+
checkInterrupted();
|
|
160
|
+
return await work();
|
|
161
|
+
}
|
|
162
|
+
finally {
|
|
163
|
+
await unlockHost();
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
finally {
|
|
167
|
+
await unlock();
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Removes the attached worktree, then its host worktree and Docker
|
|
172
|
+
* environment. The attached branch is kept.
|
|
173
|
+
*/
|
|
174
|
+
export async function removeAttached({ state, attached, store }, cwd, force = false, confirm, progress) {
|
|
175
|
+
const { name } = state;
|
|
176
|
+
const { store: hostStore, host } = await hostOf(state);
|
|
177
|
+
const outer = await realpath(host?.path ?? state.path).catch(() => resolve(host?.path ?? state.path));
|
|
178
|
+
const here = await realpath(cwd);
|
|
179
|
+
if (here === outer || isInside(outer, here))
|
|
180
|
+
throw new Error(`Current directory is inside ${outer}; change directory before removing it.`);
|
|
181
|
+
if (!force && !process.stdin.isTTY)
|
|
182
|
+
throw new Error('wt rm requires an interactive terminal or --force.');
|
|
183
|
+
if (!force) {
|
|
184
|
+
const changes = await uncommittedChanges(state.path);
|
|
185
|
+
const request = {
|
|
186
|
+
title: `Remove worktree ${name}?`,
|
|
187
|
+
details: [
|
|
188
|
+
{ label: 'Directory', value: state.path },
|
|
189
|
+
...(changes > 0
|
|
190
|
+
? [
|
|
191
|
+
{ label: 'Uncommitted changes', value: `${changes} ${changes === 1
|
|
192
|
+
? 'file'
|
|
193
|
+
: 'files'}` },
|
|
194
|
+
]
|
|
195
|
+
: []),
|
|
196
|
+
...(host !== undefined
|
|
197
|
+
? [
|
|
198
|
+
{ label: 'Host worktree', value: host.path },
|
|
199
|
+
{ label: 'Compose project', value: host.projectName },
|
|
200
|
+
{ label: 'Volumes', value: Object.values(host.volumes).join(', ') || 'none' },
|
|
201
|
+
]
|
|
202
|
+
: []),
|
|
203
|
+
],
|
|
204
|
+
note: `Uncommitted changes in both checkouts and all data in the host's volumes will be lost. The branch ${state.branch} is kept.`,
|
|
205
|
+
action: 'Remove',
|
|
206
|
+
};
|
|
207
|
+
if (!await requestConfirmation(request, confirm))
|
|
208
|
+
return false;
|
|
209
|
+
}
|
|
210
|
+
await withLocks(store, hostStore, async () => {
|
|
211
|
+
await checkUnchanged(attached, state);
|
|
212
|
+
await attached.save({ ...state, status: 'removing' });
|
|
213
|
+
if (await isRegistered(state.path, state.sourceWorktreePath)) {
|
|
214
|
+
await runStep(progress, `Removing Git worktree ${name}`, async () => git([
|
|
215
|
+
'worktree',
|
|
216
|
+
'remove',
|
|
217
|
+
'--force',
|
|
218
|
+
state.path,
|
|
219
|
+
], state.sourceWorktreePath));
|
|
220
|
+
}
|
|
221
|
+
else if (await exists(state.path)) {
|
|
222
|
+
throw new Error(`Unregistered directory still exists at ${state.path}. Move it out of the way and retry wt rm ${name}.`);
|
|
223
|
+
}
|
|
224
|
+
const current = await hostStore.find(state.host.name);
|
|
225
|
+
if (current !== undefined)
|
|
226
|
+
await removeLocked(current, hostStore, state.host.repositoryRoot, progress, name);
|
|
227
|
+
await attached.remove(name);
|
|
228
|
+
});
|
|
229
|
+
return true;
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* Resets the host environment and refreshes the attached worktree's copied
|
|
233
|
+
* files. The hooks of both run again, the attached ones after the host's.
|
|
234
|
+
*/
|
|
235
|
+
export async function resetAttached({ state, attached, store }, force = false, confirm, progress) {
|
|
236
|
+
const { name } = state;
|
|
237
|
+
const { store: hostStore, host } = await hostOf(state);
|
|
238
|
+
if (host === undefined)
|
|
239
|
+
throw new Error(`Host environment ${state.host.name} is missing. Run wt rm ${name} to clean up.`);
|
|
240
|
+
if (!await exists(state.path))
|
|
241
|
+
throw new Error(`Worktree directory is missing: ${state.path}. Run wt rm ${name} to clean up its resources.`);
|
|
242
|
+
const sourceRoot = await realpath(state.sourceWorktreePath);
|
|
243
|
+
const config = await loadConfig(sourceRoot, state.configurationPath);
|
|
244
|
+
const { sourceRoot: hostSource, config: hostConfig } = await prepareReset(host, state.host.repositoryRoot, name);
|
|
245
|
+
await validateCopyAndHooks(config, sourceRoot, state.path);
|
|
246
|
+
if (!force && !process.stdin.isTTY)
|
|
247
|
+
throw new Error('wt reset requires an interactive terminal or --force.');
|
|
248
|
+
if (!force) {
|
|
249
|
+
const request = {
|
|
250
|
+
title: `Reset worktree ${name}?`,
|
|
251
|
+
details: [
|
|
252
|
+
{ label: 'Directory', value: state.path },
|
|
253
|
+
{ label: 'Host worktree', value: host.path },
|
|
254
|
+
{ label: 'Replaced paths', value: [
|
|
255
|
+
...hostConfig.copy,
|
|
256
|
+
...config.copy.map(path => `${state.mountPath}/${path}`),
|
|
257
|
+
].join(', ') || 'none' },
|
|
258
|
+
{ label: 'Recreated volumes', value: Object.values(host.volumes).join(', ') || 'none' },
|
|
259
|
+
],
|
|
260
|
+
note: `These paths and volumes are overwritten with fresh copies from ${hostSource} and ${sourceRoot}. Other files in the worktrees are left alone.`,
|
|
261
|
+
action: 'Reset',
|
|
262
|
+
};
|
|
263
|
+
if (!await requestConfirmation(request, confirm))
|
|
264
|
+
return false;
|
|
265
|
+
}
|
|
266
|
+
await withLocks(store, hostStore, async () => {
|
|
267
|
+
await checkUnchanged(attached, state);
|
|
268
|
+
await checkUnchanged(hostStore, host);
|
|
269
|
+
if (host.status === 'removing' || state.status === 'removing')
|
|
270
|
+
throw new Error(`Removal of ${name} is incomplete. Retry wt rm ${name}.`);
|
|
271
|
+
await attached.save({ ...state, status: 'resetting' });
|
|
272
|
+
try {
|
|
273
|
+
if (config.copy.length > 0)
|
|
274
|
+
await runStep(progress, `Refreshing configured files in ${state.mountPath}`, async () => copyConfiguredPaths(sourceRoot, state.path, config.copy));
|
|
275
|
+
await resetLocked({ ...host, sourceWorktreePath: hostSource }, hostStore, hostConfig, state.host.repositoryRoot, {
|
|
276
|
+
progress,
|
|
277
|
+
nested: environment => [
|
|
278
|
+
attachedLayer(config, state, environment),
|
|
279
|
+
],
|
|
280
|
+
});
|
|
281
|
+
const { error: _error, ...ready } = state;
|
|
282
|
+
await attached.save({ ...ready, status: 'ready' });
|
|
283
|
+
}
|
|
284
|
+
catch (error) {
|
|
285
|
+
await attached.save({ ...state, status: 'failed', error: error.message });
|
|
286
|
+
throw error;
|
|
287
|
+
}
|
|
288
|
+
});
|
|
289
|
+
return true;
|
|
290
|
+
}
|
|
291
|
+
/** The host environment of an attached worktree, or undefined when it was never created. */
|
|
292
|
+
export async function attachedHost(state) {
|
|
293
|
+
return (await hostOf(state)).host;
|
|
294
|
+
}
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { realpath } from 'node:fs/promises';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
import { repositoryInfo } from '../git/repository.js';
|
|
4
|
+
import { AttachedStore, StateStore } from '../state/store.js';
|
|
5
|
+
import { attachedHost, createAttached, removeAttached, resetAttached } from './attached.js';
|
|
6
|
+
import { createEnvironmentLocked, withCreateContext } from './create.js';
|
|
7
|
+
import * as manage from './manage.js';
|
|
8
|
+
/*
|
|
9
|
+
* Entry points of the CLI. A name refers to an environment of the current
|
|
10
|
+
* repository or to a worktree attached to an environment of a host
|
|
11
|
+
* repository. Attached worktrees are routed to their host environment.
|
|
12
|
+
*/
|
|
13
|
+
export async function createEnvironment(name, options, cwd, progress) {
|
|
14
|
+
return withCreateContext(name, options, cwd, progress, async (repository, store, loaded) => loaded.config.host === undefined
|
|
15
|
+
? createEnvironmentLocked(name, options, repository, store, { ...loaded, progress })
|
|
16
|
+
: createAttached(name, options, { repository, ...loaded }, progress));
|
|
17
|
+
}
|
|
18
|
+
async function findAttached(name, cwd) {
|
|
19
|
+
const { gitCommonDir } = await repositoryInfo(cwd);
|
|
20
|
+
const attached = new AttachedStore(gitCommonDir);
|
|
21
|
+
const state = await attached.find(name);
|
|
22
|
+
return state && {
|
|
23
|
+
state,
|
|
24
|
+
attached,
|
|
25
|
+
store: new StateStore(gitCommonDir),
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
export async function resolveEnvironmentName(name, cwd) {
|
|
29
|
+
if (name !== undefined)
|
|
30
|
+
return name;
|
|
31
|
+
const { root, gitCommonDir } = await repositoryInfo(cwd);
|
|
32
|
+
const here = await realpath(root);
|
|
33
|
+
for (const state of await new AttachedStore(gitCommonDir).list()) {
|
|
34
|
+
if (await realpath(state.path).catch(() => resolve(state.path)) === here)
|
|
35
|
+
return state.name;
|
|
36
|
+
}
|
|
37
|
+
return manage.resolveEnvironmentName(undefined, cwd);
|
|
38
|
+
}
|
|
39
|
+
export async function listEnvironments(cwd) {
|
|
40
|
+
const own = await manage.listEnvironments(cwd);
|
|
41
|
+
const { gitCommonDir } = await repositoryInfo(cwd);
|
|
42
|
+
const states = await new AttachedStore(gitCommonDir).list();
|
|
43
|
+
if (states.length === 0)
|
|
44
|
+
return own;
|
|
45
|
+
const dockerStatus = await manage.dockerStatuses(cwd);
|
|
46
|
+
const rows = await Promise.all(states.map(async (state) => {
|
|
47
|
+
const host = await attachedHost(state);
|
|
48
|
+
return {
|
|
49
|
+
name: state.name,
|
|
50
|
+
branch: state.branch,
|
|
51
|
+
path: state.path,
|
|
52
|
+
status: state.status !== 'ready'
|
|
53
|
+
? state.status
|
|
54
|
+
: host?.status,
|
|
55
|
+
projectName: host?.projectName ?? '-',
|
|
56
|
+
dockerStatus: host === undefined
|
|
57
|
+
? 'missing'
|
|
58
|
+
: dockerStatus(host.projectName),
|
|
59
|
+
};
|
|
60
|
+
}));
|
|
61
|
+
return [
|
|
62
|
+
...own,
|
|
63
|
+
...rows,
|
|
64
|
+
].sort((a, b) => a.name.localeCompare(b.name));
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Names and branches of all environments, read from the state files only.
|
|
68
|
+
* It never asks Docker, so shell completion stays fast.
|
|
69
|
+
*/
|
|
70
|
+
export async function listEnvironmentNames(cwd) {
|
|
71
|
+
const { gitCommonDir } = await repositoryInfo(cwd);
|
|
72
|
+
const [own, attached] = await Promise.all([
|
|
73
|
+
new StateStore(gitCommonDir).list(),
|
|
74
|
+
new AttachedStore(gitCommonDir).list(),
|
|
75
|
+
]);
|
|
76
|
+
return [
|
|
77
|
+
...own,
|
|
78
|
+
...attached,
|
|
79
|
+
]
|
|
80
|
+
.map(({ name, branch }) => ({ name, branch }))
|
|
81
|
+
.sort((a, b) => a.name.localeCompare(b.name));
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Names of the environments whose Compose services run. It asks Docker once
|
|
85
|
+
* and gives up after `timeout` milliseconds, so it suits shell completion.
|
|
86
|
+
*/
|
|
87
|
+
export async function runningEnvironmentNames(cwd, timeout) {
|
|
88
|
+
const { gitCommonDir } = await repositoryInfo(cwd);
|
|
89
|
+
const [own, attached, dockerStatus] = await Promise.all([
|
|
90
|
+
new StateStore(gitCommonDir).list(),
|
|
91
|
+
new AttachedStore(gitCommonDir).list(),
|
|
92
|
+
manage.dockerStatuses(cwd, timeout),
|
|
93
|
+
]);
|
|
94
|
+
const projects = [
|
|
95
|
+
...own,
|
|
96
|
+
...await Promise.all(attached.map(async (state) => ({ name: state.name, projectName: (await attachedHost(state))?.projectName }))),
|
|
97
|
+
];
|
|
98
|
+
return new Set(projects
|
|
99
|
+
.filter(({ projectName }) => projectName !== undefined && dockerStatus(projectName).startsWith('running'))
|
|
100
|
+
.map(({ name }) => name));
|
|
101
|
+
}
|
|
102
|
+
export async function inspectEnvironment(name, cwd) {
|
|
103
|
+
const target = await findAttached(name, cwd);
|
|
104
|
+
if (target === undefined)
|
|
105
|
+
return manage.inspectEnvironment(name, cwd);
|
|
106
|
+
const { state } = target;
|
|
107
|
+
const host = await attachedHost(state);
|
|
108
|
+
const details = host === undefined
|
|
109
|
+
? {
|
|
110
|
+
projectName: '-',
|
|
111
|
+
volumes: {},
|
|
112
|
+
containers: [],
|
|
113
|
+
status: state.status,
|
|
114
|
+
error: state.error,
|
|
115
|
+
}
|
|
116
|
+
: await manage.inspectState(host, cwd);
|
|
117
|
+
return {
|
|
118
|
+
...details,
|
|
119
|
+
name: state.name,
|
|
120
|
+
branch: state.branch,
|
|
121
|
+
path: state.path,
|
|
122
|
+
status: state.status !== 'ready'
|
|
123
|
+
? state.status
|
|
124
|
+
: details.status,
|
|
125
|
+
error: state.error ?? details.error,
|
|
126
|
+
host: { name: state.host.name, path: host?.path ?? '-' },
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
export async function composeOperation(name, action, args, cwd, progress) {
|
|
130
|
+
const target = await findAttached(name, cwd);
|
|
131
|
+
if (target === undefined)
|
|
132
|
+
return manage.composeOperation(name, action, args, cwd, progress);
|
|
133
|
+
const { state } = target;
|
|
134
|
+
if (state.status !== 'ready' && action !== 'docker')
|
|
135
|
+
throw new Error(`Worktree ${name} is ${state.status}. Run wt reset ${name} to retry setup or wt rm ${name} to remove it.`);
|
|
136
|
+
const hostStore = new StateStore(state.host.gitCommonDir);
|
|
137
|
+
const unlock = action === 'docker'
|
|
138
|
+
? undefined
|
|
139
|
+
: await hostStore.lock('repository');
|
|
140
|
+
try {
|
|
141
|
+
return await manage.runManagedCompose(await hostStore.get(state.host.name), action, args, progress);
|
|
142
|
+
}
|
|
143
|
+
finally {
|
|
144
|
+
await unlock?.();
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
export async function removeEnvironment(name, cwd, force = false, confirm, progress) {
|
|
148
|
+
const target = await findAttached(name, cwd);
|
|
149
|
+
return target === undefined
|
|
150
|
+
? manage.removeEnvironment(name, cwd, force, confirm, progress)
|
|
151
|
+
: removeAttached(target, cwd, force, confirm, progress);
|
|
152
|
+
}
|
|
153
|
+
export async function resetEnvironment(name, cwd, force = false, confirm, progress) {
|
|
154
|
+
const target = await findAttached(name, cwd);
|
|
155
|
+
return target === undefined
|
|
156
|
+
? manage.resetEnvironment(name, cwd, force, confirm, progress)
|
|
157
|
+
: resetAttached(target, force, confirm, progress);
|
|
158
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export function detailRows(details) {
|
|
2
|
+
const width = Math.max(0, ...details.map(detail => detail.label.length));
|
|
3
|
+
return details.map(detail => ({
|
|
4
|
+
label: detail.label.padEnd(width),
|
|
5
|
+
value: detail.value,
|
|
6
|
+
}));
|
|
7
|
+
}
|
|
8
|
+
export function formatConfirmation(request) {
|
|
9
|
+
return [
|
|
10
|
+
request.title,
|
|
11
|
+
...detailRows(request.details).map(row => ` ${row.label} ${row.value}`),
|
|
12
|
+
request.note,
|
|
13
|
+
`${request.action}? [y/N] `,
|
|
14
|
+
].join('\n');
|
|
15
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { chmod, copyFile, lstat, mkdir, mkdtemp, readdir, readlink, rename, rm, symlink, utimes } from 'node:fs/promises';
|
|
2
|
+
import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
3
|
+
import process from 'node:process';
|
|
4
|
+
import { checkInterrupted } from './process.js';
|
|
5
|
+
function assertInside(root, path) {
|
|
6
|
+
const segment = relative(root, path);
|
|
7
|
+
if (segment === '' || segment === '..' || segment.startsWith(`..${sep}`) || isAbsolute(segment))
|
|
8
|
+
throw new Error(`Path escapes worktree: ${path}`);
|
|
9
|
+
}
|
|
10
|
+
async function assertNoSymlinkPath(root, relativePath, allowLeafSymlink = false) {
|
|
11
|
+
let current = resolve(root);
|
|
12
|
+
const segments = relativePath.split('/');
|
|
13
|
+
for (const [index, segment] of segments.entries()) {
|
|
14
|
+
current = join(current, segment);
|
|
15
|
+
try {
|
|
16
|
+
if ((await lstat(current)).isSymbolicLink() && !(allowLeafSymlink && index === segments.length - 1))
|
|
17
|
+
throw new Error(`Refusing to access symlink in configured target path: ${current}`);
|
|
18
|
+
}
|
|
19
|
+
catch (error) {
|
|
20
|
+
if (error.code !== 'ENOENT')
|
|
21
|
+
throw error;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
export async function copyConfiguredPaths(sourceRoot, targetRoot, paths) {
|
|
26
|
+
for (const entry of paths) {
|
|
27
|
+
checkInterrupted();
|
|
28
|
+
const source = resolve(sourceRoot, entry);
|
|
29
|
+
const target = resolve(targetRoot, entry);
|
|
30
|
+
assertInside(sourceRoot, source);
|
|
31
|
+
assertInside(targetRoot, target);
|
|
32
|
+
await assertNoSymlinkPath(sourceRoot, entry, true);
|
|
33
|
+
await assertNoSymlinkPath(targetRoot, entry, true);
|
|
34
|
+
await lstat(source);
|
|
35
|
+
await mkdir(dirname(target), { recursive: true });
|
|
36
|
+
await replaceEntry(source, target);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
async function replaceEntry(source, target) {
|
|
40
|
+
const temporary = await mkdtemp(join(dirname(target), '.wt-copy-'));
|
|
41
|
+
const fresh = join(temporary, 'fresh');
|
|
42
|
+
const previous = join(temporary, 'previous');
|
|
43
|
+
let preserveBackup = false;
|
|
44
|
+
try {
|
|
45
|
+
if (!await copyEntry(source, fresh))
|
|
46
|
+
return;
|
|
47
|
+
checkInterrupted();
|
|
48
|
+
let backedUp = false;
|
|
49
|
+
try {
|
|
50
|
+
await rename(target, previous);
|
|
51
|
+
backedUp = true;
|
|
52
|
+
}
|
|
53
|
+
catch (error) {
|
|
54
|
+
if (error.code !== 'ENOENT')
|
|
55
|
+
throw error;
|
|
56
|
+
}
|
|
57
|
+
try {
|
|
58
|
+
await rename(fresh, target);
|
|
59
|
+
}
|
|
60
|
+
catch (error) {
|
|
61
|
+
if (backedUp) {
|
|
62
|
+
preserveBackup = true;
|
|
63
|
+
await rename(previous, target);
|
|
64
|
+
preserveBackup = false;
|
|
65
|
+
}
|
|
66
|
+
throw error;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
finally {
|
|
70
|
+
if (!preserveBackup)
|
|
71
|
+
await rm(temporary, { recursive: true, force: true });
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
async function copyEntry(source, target) {
|
|
75
|
+
const details = await lstat(source).catch((error) => {
|
|
76
|
+
if (error.code !== 'ENOENT')
|
|
77
|
+
throw error;
|
|
78
|
+
});
|
|
79
|
+
if (!details)
|
|
80
|
+
return false;
|
|
81
|
+
if (details.isSymbolicLink()) {
|
|
82
|
+
await symlink(await readlink(source), target);
|
|
83
|
+
return true;
|
|
84
|
+
}
|
|
85
|
+
if (details.isDirectory()) {
|
|
86
|
+
await mkdir(target, { mode: 0o700 });
|
|
87
|
+
for (const entry of await readdir(source)) {
|
|
88
|
+
checkInterrupted();
|
|
89
|
+
try {
|
|
90
|
+
await copyEntry(join(source, entry), join(target, entry));
|
|
91
|
+
}
|
|
92
|
+
catch (error) {
|
|
93
|
+
if (error.code !== 'ENOENT' || error.path !== join(source, entry))
|
|
94
|
+
throw error;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
await chmod(target, details.mode & 0o777);
|
|
98
|
+
await utimes(target, details.atime, details.mtime);
|
|
99
|
+
return true;
|
|
100
|
+
}
|
|
101
|
+
if (!details.isFile()) {
|
|
102
|
+
process.stderr.write(`Skipping special file ${source}\n`);
|
|
103
|
+
return false;
|
|
104
|
+
}
|
|
105
|
+
await copyFile(source, target);
|
|
106
|
+
await chmod(target, details.mode & 0o777);
|
|
107
|
+
await utimes(target, details.atime, details.mtime);
|
|
108
|
+
return true;
|
|
109
|
+
}
|