@joberthel/worktree 1.4.0 → 1.6.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 +36 -8
- 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/containers.js +67 -0
- package/dist/docker/orbstack.js +20 -9
- package/dist/docker/pause.js +36 -0
- package/dist/docker/service-order.js +242 -0
- package/dist/environment-state.js +25 -0
- package/dist/errors.js +4 -2
- package/dist/git/repository.js +40 -3
- package/dist/help.js +111 -0
- package/dist/list-filter.js +2 -4
- package/dist/operations/commands.js +28 -11
- package/dist/operations/confirmation.js +11 -0
- package/dist/operations/create.js +3 -2
- package/dist/operations/manage.js +22 -31
- package/dist/operations/progress.js +39 -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 +104 -37
- package/dist/ui/environment-table.js +11 -10
- package/dist/ui/json-output.js +10 -1
- 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,67 @@
|
|
|
1
|
+
import { docker } from './compose.js';
|
|
2
|
+
import { domainsLabel, parseDomains } from './orbstack.js';
|
|
3
|
+
import { parsePorts } from './ports.js';
|
|
4
|
+
import { composeFilesFormat, parseComposeFiles, serviceOrderReader, servicePosition } from './service-order.js';
|
|
5
|
+
/** The `docker ps --format` columns that parseContainers reads. */
|
|
6
|
+
const containerFormat = [
|
|
7
|
+
'{{.Names}}',
|
|
8
|
+
'{{.Label "com.docker.compose.service"}}',
|
|
9
|
+
'{{.Label "com.docker.compose.container-number"}}',
|
|
10
|
+
'{{.Label "com.docker.compose.oneoff"}}',
|
|
11
|
+
composeFilesFormat,
|
|
12
|
+
`{{.Label "${domainsLabel}"}}`,
|
|
13
|
+
'{{.Ports}}',
|
|
14
|
+
'{{.State}}',
|
|
15
|
+
'{{.Status}}',
|
|
16
|
+
].join('\t');
|
|
17
|
+
export function parseContainers(output) {
|
|
18
|
+
return output.split('\n').filter(Boolean).map((line) => {
|
|
19
|
+
const [name, service, number = '', oneOff = '', workingDir, configFiles, domains = '', ports = '', state, ...status] = line.split('\t');
|
|
20
|
+
return {
|
|
21
|
+
container: {
|
|
22
|
+
name,
|
|
23
|
+
service: service || name,
|
|
24
|
+
number: /^\d+$/.test(number)
|
|
25
|
+
? Number(number)
|
|
26
|
+
: undefined,
|
|
27
|
+
oneOff: oneOff.toLowerCase() === 'true',
|
|
28
|
+
state: state ?? '',
|
|
29
|
+
status: status.join('\t'),
|
|
30
|
+
domains: parseDomains(domains),
|
|
31
|
+
ports: parsePorts(ports),
|
|
32
|
+
},
|
|
33
|
+
files: parseComposeFiles(workingDir, configFiles),
|
|
34
|
+
};
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Orders containers by the position of their service in `services`, the
|
|
39
|
+
* order of the Compose files. Services that `services` does not name come
|
|
40
|
+
* last, alphabetically. The containers of a service come in container number
|
|
41
|
+
* order, then the one-off containers of `docker compose run`.
|
|
42
|
+
*/
|
|
43
|
+
function sortContainers(rows, services) {
|
|
44
|
+
const position = servicePosition(services);
|
|
45
|
+
const number = ({ container }) => container.number ?? Number.MAX_SAFE_INTEGER;
|
|
46
|
+
return [...rows].sort((a, b) => position(a.container.service) - position(b.container.service)
|
|
47
|
+
|| a.container.service.localeCompare(b.container.service)
|
|
48
|
+
|| Number(a.container.oneOff) - Number(b.container.oneOff)
|
|
49
|
+
|| number(a) - number(b)
|
|
50
|
+
|| a.container.name.localeCompare(b.container.name)).map(({ container }) => container);
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* The containers of a Compose project in the order of its services in the
|
|
54
|
+
* Compose files that its containers were created from.
|
|
55
|
+
*/
|
|
56
|
+
export async function projectContainers(project, cwd) {
|
|
57
|
+
const rows = parseContainers(await docker([
|
|
58
|
+
'ps',
|
|
59
|
+
'-a',
|
|
60
|
+
'--filter',
|
|
61
|
+
`label=com.docker.compose.project=${project}`,
|
|
62
|
+
'--format',
|
|
63
|
+
containerFormat,
|
|
64
|
+
], cwd));
|
|
65
|
+
const readServiceOrder = serviceOrderReader();
|
|
66
|
+
return sortContainers(rows, await readServiceOrder(rows.map(({ files }) => files)));
|
|
67
|
+
}
|
package/dist/docker/orbstack.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { run } from '../operations/process.js';
|
|
2
2
|
import { docker } from './compose.js';
|
|
3
|
+
import { composeFilesFormat, parseComposeFiles, serviceOrderReader, servicePosition } from './service-order.js';
|
|
3
4
|
/** Container label that gives a container custom OrbStack domains. */
|
|
4
5
|
export const domainsLabel = 'dev.orbstack.domains';
|
|
5
6
|
/**
|
|
@@ -43,33 +44,43 @@ export function containerAddresses(containers, project, { scheme }) {
|
|
|
43
44
|
/**
|
|
44
45
|
* The main URL of each Compose project: its custom domain closest to the
|
|
45
46
|
* root, so `shop.orb.local` wins over `admin.shop.orb.local`. Among domains
|
|
46
|
-
* of equal depth, the one
|
|
47
|
+
* of equal depth, the one of the service that comes first in the Compose
|
|
48
|
+
* files wins, then the one listed first in its label. Services the files do
|
|
49
|
+
* not name come after the others. The files are read only when domains of
|
|
50
|
+
* several services tie.
|
|
47
51
|
*/
|
|
48
52
|
export async function projectUrls(cwd) {
|
|
49
53
|
const network = await orbstackNetwork(cwd);
|
|
50
54
|
if (network === undefined)
|
|
51
|
-
return () => undefined;
|
|
55
|
+
return async () => undefined;
|
|
52
56
|
const output = await docker([
|
|
53
57
|
'ps',
|
|
54
58
|
'-a',
|
|
55
59
|
'--filter',
|
|
56
60
|
`label=${domainsLabel}`,
|
|
57
61
|
'--format',
|
|
58
|
-
`{{.Label "com.docker.compose.project"}}\t{{.Label "${domainsLabel}"}}`,
|
|
62
|
+
`{{.Label "com.docker.compose.project"}}\t{{.Label "com.docker.compose.service"}}\t${composeFilesFormat}\t{{.Label "${domainsLabel}"}}`,
|
|
59
63
|
], cwd);
|
|
60
64
|
const domains = new Map();
|
|
61
65
|
for (const line of output.split('\n').filter(Boolean)) {
|
|
62
|
-
const [project, label = ''] = line.split('\t');
|
|
66
|
+
const [project, service = '', workingDir, configFiles, label = ''] = line.split('\t');
|
|
67
|
+
const files = parseComposeFiles(workingDir, configFiles);
|
|
63
68
|
domains.set(project, [
|
|
64
69
|
...domains.get(project) ?? [],
|
|
65
|
-
...parseDomains(label).map((domain, position) => ({ domain, position })),
|
|
70
|
+
...parseDomains(label).map((domain, position) => ({ domain, position, service, files })),
|
|
66
71
|
]);
|
|
67
72
|
}
|
|
73
|
+
const readServiceOrder = serviceOrderReader();
|
|
68
74
|
const depth = (domain) => domain.split('.').length;
|
|
69
|
-
return (project) => {
|
|
70
|
-
const
|
|
71
|
-
|
|
72
|
-
|
|
75
|
+
return async (project) => {
|
|
76
|
+
const candidates = domains.get(project) ?? [];
|
|
77
|
+
const closest = Math.min(...candidates.map(({ domain }) => depth(domain)));
|
|
78
|
+
const tied = candidates.filter(({ domain }) => depth(domain) === closest);
|
|
79
|
+
const order = new Set(tied.map(({ service }) => service)).size > 1
|
|
80
|
+
? await readServiceOrder(candidates.map(({ files }) => files))
|
|
81
|
+
: [];
|
|
82
|
+
const position = servicePosition(order);
|
|
83
|
+
const [main] = tied.sort((a, b) => position(a.service) - position(b.service) || a.position - b.position || a.domain.localeCompare(b.domain));
|
|
73
84
|
return main === undefined
|
|
74
85
|
? undefined
|
|
75
86
|
: `${network.scheme}://${main.domain}`;
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
import { Buffer } from 'node:buffer';
|
|
2
|
+
import { constants, open, stat } from 'node:fs/promises';
|
|
3
|
+
import { dirname, resolve } from 'node:path';
|
|
4
|
+
import { isAlias, isMap, isScalar, isSeq, parseAllDocuments, visit } from 'yaml';
|
|
5
|
+
/** The two `docker ps --format` columns that parseComposeFiles reads. */
|
|
6
|
+
export const composeFilesFormat = [
|
|
7
|
+
'{{.Label "com.docker.compose.project.working_dir"}}',
|
|
8
|
+
'{{.Label "com.docker.compose.project.config_files"}}',
|
|
9
|
+
].join('\t');
|
|
10
|
+
/** The Compose files of a container, from its `working_dir` and comma-separated `config_files` labels. */
|
|
11
|
+
export function parseComposeFiles(workingDir = '', configFiles = '') {
|
|
12
|
+
return {
|
|
13
|
+
workingDir,
|
|
14
|
+
configFiles: configFiles.split(',').filter(Boolean),
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Compose files larger than this are not read, and their services count as
|
|
19
|
+
* not named. Real ones are much smaller, and parsing a large file takes long.
|
|
20
|
+
*/
|
|
21
|
+
const maxFileSize = 1024 * 1024;
|
|
22
|
+
/**
|
|
23
|
+
* The resolver of a document's aliases. An alias refers to the last node
|
|
24
|
+
* with its anchor before it. One pass over the document finds them all,
|
|
25
|
+
* where Alias.resolve would search the whole document for every alias.
|
|
26
|
+
*/
|
|
27
|
+
function aliasResolver(document) {
|
|
28
|
+
const anchors = new Map();
|
|
29
|
+
const targets = new Map();
|
|
30
|
+
visit(document, {
|
|
31
|
+
Node: (_key, node) => {
|
|
32
|
+
if (isAlias(node))
|
|
33
|
+
targets.set(node, anchors.get(node.source));
|
|
34
|
+
else if (node.anchor !== undefined)
|
|
35
|
+
anchors.set(node.anchor, node);
|
|
36
|
+
},
|
|
37
|
+
});
|
|
38
|
+
return node => isAlias(node)
|
|
39
|
+
? targets.get(node)
|
|
40
|
+
: node;
|
|
41
|
+
}
|
|
42
|
+
/** The text of a scalar, also behind an alias. */
|
|
43
|
+
function text(node, resolved) {
|
|
44
|
+
const value = resolved(node);
|
|
45
|
+
return isScalar(value) && typeof value.value === 'string'
|
|
46
|
+
? value.value
|
|
47
|
+
: undefined;
|
|
48
|
+
}
|
|
49
|
+
/** The texts of a scalar or of a sequence of scalars. */
|
|
50
|
+
function texts(node, resolved) {
|
|
51
|
+
const value = resolved(node);
|
|
52
|
+
const items = isSeq(value)
|
|
53
|
+
? value.items
|
|
54
|
+
: [value];
|
|
55
|
+
return items.map(item => text(item, resolved)).filter(item => item !== undefined);
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* The keys of a mapping in document order. The keys of the mappings that it
|
|
59
|
+
* merges with `<<` take the place of the merge key. Each mapping counts
|
|
60
|
+
* once, so aliases cannot make this grow beyond the size of the file.
|
|
61
|
+
*/
|
|
62
|
+
function mappingKeys(node, resolved, seen = new Set()) {
|
|
63
|
+
const mapping = resolved(node);
|
|
64
|
+
if (!isMap(mapping) || seen.has(mapping))
|
|
65
|
+
return [];
|
|
66
|
+
seen.add(mapping);
|
|
67
|
+
return mapping.items.flatMap(({ key, value }) => {
|
|
68
|
+
// With `merge: true`, the parser gives a plain `<<` key a symbol as its value.
|
|
69
|
+
if (isScalar(key) && typeof key.value === 'symbol') {
|
|
70
|
+
const merged = resolved(value);
|
|
71
|
+
const sources = isSeq(merged)
|
|
72
|
+
? merged.items
|
|
73
|
+
: [merged];
|
|
74
|
+
return sources.flatMap(source => mappingKeys(source, resolved, seen));
|
|
75
|
+
}
|
|
76
|
+
const name = text(key, resolved);
|
|
77
|
+
return name === undefined
|
|
78
|
+
? []
|
|
79
|
+
: [name];
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
/** An entry of `include`: a path, or a mapping with `path` and `project_directory`. */
|
|
83
|
+
function includeEntry(node, resolved) {
|
|
84
|
+
const entry = resolved(node);
|
|
85
|
+
const mapping = isMap(entry);
|
|
86
|
+
const path = mapping
|
|
87
|
+
? entry.get('path', true)
|
|
88
|
+
: entry;
|
|
89
|
+
const paths = texts(path, resolved);
|
|
90
|
+
if (paths.length === 0)
|
|
91
|
+
return undefined;
|
|
92
|
+
return {
|
|
93
|
+
paths,
|
|
94
|
+
projectDirectory: mapping
|
|
95
|
+
? text(entry.get('project_directory', true), resolved)
|
|
96
|
+
: undefined,
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
/** The entries of `include`, which is a sequence. */
|
|
100
|
+
function includeEntries(node, resolved) {
|
|
101
|
+
const entries = resolved(node);
|
|
102
|
+
if (!isSeq(entries))
|
|
103
|
+
return [];
|
|
104
|
+
return entries.items.map(entry => includeEntry(entry, resolved)).filter(entry => entry !== undefined);
|
|
105
|
+
}
|
|
106
|
+
/** The services and includes of a Compose document, in the order of its keys. */
|
|
107
|
+
function documentParts(document) {
|
|
108
|
+
const parts = [];
|
|
109
|
+
if (!isMap(document.contents))
|
|
110
|
+
return parts;
|
|
111
|
+
const resolved = aliasResolver(document);
|
|
112
|
+
for (const { key, value } of document.contents.items) {
|
|
113
|
+
const name = text(key, resolved);
|
|
114
|
+
if (name === 'services') {
|
|
115
|
+
parts.push({
|
|
116
|
+
services: mappingKeys(value, resolved),
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
if (name === 'include') {
|
|
120
|
+
parts.push({
|
|
121
|
+
includes: includeEntries(value, resolved),
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
return parts;
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* The text of a Compose file, or undefined when it is not a regular file or
|
|
129
|
+
* larger than maxFileSize. Only regular files are opened, because opening a
|
|
130
|
+
* pipe or a device can have effects, such as releasing a writer that waits
|
|
131
|
+
* on the pipe or resetting a board on a serial port. The opened file is
|
|
132
|
+
* checked again, in case it was replaced in between, and the flags keep
|
|
133
|
+
* such a replacement from blocking or becoming the controlling terminal. At
|
|
134
|
+
* most one byte more than the limit is read, also from a file that reports
|
|
135
|
+
* a wrong size, as those in /proc do.
|
|
136
|
+
*/
|
|
137
|
+
async function readComposeFile(file) {
|
|
138
|
+
if (!(await stat(file)).isFile())
|
|
139
|
+
return undefined;
|
|
140
|
+
const handle = await open(file, constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOCTTY);
|
|
141
|
+
try {
|
|
142
|
+
if (!(await handle.stat()).isFile())
|
|
143
|
+
return undefined;
|
|
144
|
+
// Only the bytes read are used, so the buffer need not be zeroed.
|
|
145
|
+
const buffer = Buffer.allocUnsafe(maxFileSize + 1);
|
|
146
|
+
let length = 0;
|
|
147
|
+
while (length < buffer.length) {
|
|
148
|
+
const { bytesRead } = await handle.read(buffer, length, buffer.length - length, length);
|
|
149
|
+
if (bytesRead === 0)
|
|
150
|
+
break;
|
|
151
|
+
length += bytesRead;
|
|
152
|
+
}
|
|
153
|
+
return length > maxFileSize
|
|
154
|
+
? undefined
|
|
155
|
+
: buffer.toString('utf8', 0, length);
|
|
156
|
+
}
|
|
157
|
+
finally {
|
|
158
|
+
await handle.close();
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* The parts of a Compose file and of each YAML document in it. A file that
|
|
163
|
+
* is missing, unreadable, not a regular file, larger than maxFileSize, or
|
|
164
|
+
* not valid YAML contributes nothing. Only keys are read, so the service
|
|
165
|
+
* definitions and their aliases are never expanded.
|
|
166
|
+
*/
|
|
167
|
+
async function readParts(file) {
|
|
168
|
+
try {
|
|
169
|
+
const source = await readComposeFile(file);
|
|
170
|
+
if (source === undefined)
|
|
171
|
+
return [];
|
|
172
|
+
// The failsafe schema keeps keys as written, so a service named 1.0 stays
|
|
173
|
+
// `1.0`. Duplicate keys are not looked for: Compose rejects them itself,
|
|
174
|
+
// and the check takes quadratic time.
|
|
175
|
+
const documents = parseAllDocuments(source, { schema: 'failsafe', merge: true, uniqueKeys: false });
|
|
176
|
+
if (documents.some(document => document.errors.length > 0))
|
|
177
|
+
return [];
|
|
178
|
+
return documents.flatMap(documentParts);
|
|
179
|
+
}
|
|
180
|
+
catch {
|
|
181
|
+
return [];
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Returns a function that lists the services of Compose projects in the
|
|
186
|
+
* order they first appear in the projects' files. It follows `include` as
|
|
187
|
+
* Compose does, except for paths with variables and remote includes, whose
|
|
188
|
+
* services it cannot know. Files it cannot read add no services. It reads
|
|
189
|
+
* each file at most once, so one reader serves a whole command.
|
|
190
|
+
*/
|
|
191
|
+
export function serviceOrderReader() {
|
|
192
|
+
const files = new Map();
|
|
193
|
+
const parts = async (file) => {
|
|
194
|
+
const known = files.get(file);
|
|
195
|
+
if (known !== undefined)
|
|
196
|
+
return known;
|
|
197
|
+
const read = readParts(file);
|
|
198
|
+
files.set(file, read);
|
|
199
|
+
return read;
|
|
200
|
+
};
|
|
201
|
+
return async (projects) => {
|
|
202
|
+
const services = new Set();
|
|
203
|
+
const visited = new Set();
|
|
204
|
+
// Compose resolves `include` paths from the directory of the including
|
|
205
|
+
// project: the project directory for the files given with `-f`, and for
|
|
206
|
+
// an included file its entry's `project_directory`, by default the
|
|
207
|
+
// directory of the first included file.
|
|
208
|
+
const addFile = async (file, directory) => {
|
|
209
|
+
if (visited.has(file))
|
|
210
|
+
return;
|
|
211
|
+
visited.add(file);
|
|
212
|
+
for (const part of await parts(file)) {
|
|
213
|
+
if ('services' in part) {
|
|
214
|
+
for (const service of part.services)
|
|
215
|
+
services.add(service);
|
|
216
|
+
continue;
|
|
217
|
+
}
|
|
218
|
+
for (const { paths, projectDirectory } of part.includes) {
|
|
219
|
+
const included = paths.map(path => resolve(directory, path));
|
|
220
|
+
const context = projectDirectory === undefined
|
|
221
|
+
? dirname(included[0])
|
|
222
|
+
: resolve(directory, projectDirectory);
|
|
223
|
+
for (const path of included)
|
|
224
|
+
await addFile(path, context);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
};
|
|
228
|
+
for (const { workingDir, configFiles } of projects) {
|
|
229
|
+
for (const file of configFiles)
|
|
230
|
+
await addFile(resolve(workingDir, file), workingDir);
|
|
231
|
+
}
|
|
232
|
+
return [...services];
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* The position of a service in `order`. Services that `order` does not name
|
|
237
|
+
* share the position after the last one.
|
|
238
|
+
*/
|
|
239
|
+
export function servicePosition(order) {
|
|
240
|
+
const positions = new Map(order.map((service, index) => [service, index]));
|
|
241
|
+
return (service) => positions.get(service) ?? order.length;
|
|
242
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* The state of an environment as `wt ls` shows it. The VS Code extension
|
|
3
|
+
* bundles this file, so both describe environments the same way.
|
|
4
|
+
*/
|
|
5
|
+
const setupKinds = {
|
|
6
|
+
creating: 'busy',
|
|
7
|
+
resetting: 'busy',
|
|
8
|
+
removing: 'busy',
|
|
9
|
+
failed: 'failed',
|
|
10
|
+
};
|
|
11
|
+
const dockerKinds = {
|
|
12
|
+
running: 'running',
|
|
13
|
+
stopped: 'stopped',
|
|
14
|
+
finished: 'finished',
|
|
15
|
+
missing: 'missing',
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* The setup status until the environment is ready, then the summary of its
|
|
19
|
+
* containers. `running (N exited)` counts as running.
|
|
20
|
+
*/
|
|
21
|
+
export function environmentState(status, dockerStatus) {
|
|
22
|
+
if (status !== undefined && status !== null && status !== 'ready')
|
|
23
|
+
return { label: status, kind: setupKinds[status] ?? 'unknown' };
|
|
24
|
+
return { label: dockerStatus, kind: dockerKinds[dockerStatus.split(' ')[0]] ?? 'unknown' };
|
|
25
|
+
}
|
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
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 });
|