worktree-compose 1.1.2 → 2.0.1
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 +2 -2
- package/README.md +31 -16
- package/SKILL.md +73 -76
- package/dist/cli.js +85 -10
- package/dist/commands/down.d.ts +2 -0
- package/dist/commands/down.js +7 -0
- package/dist/commands/list.d.ts +2 -0
- package/dist/commands/list.js +43 -6
- package/dist/commands/passthrough.d.ts +13 -0
- package/dist/commands/passthrough.js +27 -0
- package/dist/commands/stop.d.ts +3 -1
- package/dist/commands/stop.js +2 -2
- package/dist/compose/detect.d.ts +19 -0
- package/dist/compose/detect.js +56 -0
- package/dist/compose/isolation.d.ts +20 -7
- package/dist/compose/isolation.js +88 -36
- package/dist/compose/override.d.ts +54 -4
- package/dist/compose/override.js +179 -52
- package/dist/compose/parse.d.ts +11 -0
- package/dist/compose/parse.js +260 -13
- package/dist/compose/status.d.ts +14 -0
- package/dist/compose/status.js +58 -1
- package/dist/compose/types.d.ts +56 -0
- package/dist/config.d.ts +33 -0
- package/dist/context.d.ts +26 -0
- package/dist/context.js +140 -29
- package/dist/core/clean.d.ts +3 -1
- package/dist/core/clean.js +8 -3
- package/dist/core/compose.d.ts +87 -13
- package/dist/core/compose.js +282 -57
- package/dist/core/doctor.d.ts +2 -8
- package/dist/core/doctor.js +116 -79
- package/dist/core/down.d.ts +37 -0
- package/dist/core/down.js +54 -0
- package/dist/core/health.d.ts +90 -0
- package/dist/core/health.js +198 -0
- package/dist/core/list.d.ts +53 -6
- package/dist/core/list.js +144 -58
- package/dist/core/passthrough.d.ts +69 -0
- package/dist/core/passthrough.js +216 -0
- package/dist/core/promote.d.ts +4 -2
- package/dist/core/promote.js +5 -3
- package/dist/core/restart.d.ts +3 -3
- package/dist/core/restart.js +6 -5
- package/dist/core/seed.d.ts +50 -0
- package/dist/core/seed.js +245 -0
- package/dist/core/shared.d.ts +63 -0
- package/dist/core/shared.js +194 -0
- package/dist/core/start.d.ts +32 -5
- package/dist/core/start.js +297 -49
- package/dist/core/stop.d.ts +3 -1
- package/dist/core/stop.js +6 -3
- package/dist/core/teardown.d.ts +5 -2
- package/dist/core/teardown.js +33 -8
- package/dist/core/types.d.ts +2 -0
- package/dist/git/promote.d.ts +11 -3
- package/dist/git/promote.js +19 -5
- package/dist/mcp/server.js +154 -28
- package/dist/ports/allocate.d.ts +35 -23
- package/dist/ports/allocate.js +108 -58
- package/dist/ports/probe.d.ts +11 -0
- package/dist/ports/probe.js +40 -0
- package/dist/ports/types.d.ts +5 -0
- package/dist/selectors.d.ts +17 -0
- package/dist/selectors.js +19 -0
- package/dist/state/registry.d.ts +23 -3
- package/dist/state/registry.js +57 -17
- package/dist/sync/env.d.ts +42 -2
- package/dist/sync/env.js +79 -8
- package/dist/sync/envsync.d.ts +91 -0
- package/dist/sync/envsync.js +338 -0
- package/dist/sync/files.d.ts +87 -5
- package/dist/sync/files.js +343 -18
- package/dist/utils/paths.d.ts +2 -0
- package/dist/utils/paths.js +9 -0
- package/package.json +1 -1
- package/wtc.schema.json +155 -13
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { buildContext } from "../context.js";
|
|
3
|
+
import { composeArgs, composeBin } from "../compose/engine.js";
|
|
4
|
+
import { CommandError, tailLines } from "../utils/exec.js";
|
|
5
|
+
import { selectScope, selectWorktrees } from "../selectors.js";
|
|
6
|
+
import { composeEnv, mainStackDirs, prepareStack } from "./compose.js";
|
|
7
|
+
/**
|
|
8
|
+
* The stack a command addresses: the named worktree's, else the one the
|
|
9
|
+
* command runs in. From the main checkout a worktree must be named.
|
|
10
|
+
*/
|
|
11
|
+
export function resolveStackCall(worktree, io, opts = {}) {
|
|
12
|
+
// Reading logs changes nothing: no identity is recorded and no file written.
|
|
13
|
+
const ctx = buildContext({}, { cwd: io.cwd, probeStacks: true, readOnly: opts.readOnly });
|
|
14
|
+
let wt;
|
|
15
|
+
if (worktree !== undefined && String(worktree).trim() !== "") {
|
|
16
|
+
[wt] = selectWorktrees(ctx.worktrees, [worktree], ctx.cwd);
|
|
17
|
+
}
|
|
18
|
+
else {
|
|
19
|
+
const scope = selectScope(ctx.worktrees, undefined, ctx.cwd);
|
|
20
|
+
if (!scope.implicit) {
|
|
21
|
+
throw new Error(`Not inside a worktree: say which stack with --worktree <index | branch | directory | path>. ` +
|
|
22
|
+
`Worktrees: ${ctx.worktrees.map((w) => `${w.index}:${w.branch}`).join(", ") || "none"}.`);
|
|
23
|
+
}
|
|
24
|
+
wt = scope.implicit;
|
|
25
|
+
}
|
|
26
|
+
// The compose files the stack was started with (runtime override included).
|
|
27
|
+
const stack = prepareStack(ctx, { project: wt.project, index: wt.index, dir: wt.path }, { write: false, readOnly: opts.readOnly });
|
|
28
|
+
return {
|
|
29
|
+
engine: ctx.getEngine(),
|
|
30
|
+
worktree: wt,
|
|
31
|
+
env: composeEnv(wt.project, stack.allocations, stack.composeFile, ctx.repo.commonDir, ctx.customComposeRoots),
|
|
32
|
+
mainDirs: mainStackDirs(ctx),
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
/** Compose's own options that take a value (`wtc compose --ansi never down`). */
|
|
36
|
+
const COMPOSE_VALUE_OPTIONS = new Set([
|
|
37
|
+
"--ansi",
|
|
38
|
+
"--env-file",
|
|
39
|
+
"-f",
|
|
40
|
+
"--file",
|
|
41
|
+
"--parallel",
|
|
42
|
+
"--profile",
|
|
43
|
+
"--progress",
|
|
44
|
+
"--project-directory",
|
|
45
|
+
"-p",
|
|
46
|
+
"--project-name",
|
|
47
|
+
]);
|
|
48
|
+
/** The compose command in `args` (`down`, `ps`…), past compose's own options, and whether it is a dry run. */
|
|
49
|
+
export function composeSubcommand(args) {
|
|
50
|
+
let dryRun = false;
|
|
51
|
+
for (let i = 0; i < args.length; i++) {
|
|
52
|
+
const arg = args[i];
|
|
53
|
+
if (!arg.startsWith("-"))
|
|
54
|
+
return { command: arg, dryRun };
|
|
55
|
+
if (arg === "--dry-run" || arg === "--dry-run=true")
|
|
56
|
+
dryRun = true;
|
|
57
|
+
if (COMPOSE_VALUE_OPTIONS.has(arg))
|
|
58
|
+
i++;
|
|
59
|
+
}
|
|
60
|
+
return { command: null, dryRun };
|
|
61
|
+
}
|
|
62
|
+
function processEnv(env) {
|
|
63
|
+
const out = { ...process.env, ...env };
|
|
64
|
+
for (const key of Object.keys(out))
|
|
65
|
+
if (out[key] === undefined)
|
|
66
|
+
delete out[key];
|
|
67
|
+
return out;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Run `compose -p <project> <args…>` attached to the terminal and return
|
|
71
|
+
* its exit code: the command's own result, passed through as it is.
|
|
72
|
+
*/
|
|
73
|
+
export function runAttached(call, args) {
|
|
74
|
+
return new Promise((resolve, reject) => {
|
|
75
|
+
const child = spawn(composeBin(call.engine), composeArgs(call.engine, call.worktree.project, ...args), {
|
|
76
|
+
cwd: call.worktree.path,
|
|
77
|
+
env: processEnv(call.env),
|
|
78
|
+
stdio: "inherit",
|
|
79
|
+
windowsHide: true,
|
|
80
|
+
});
|
|
81
|
+
// Ctrl-C reaches the child through the terminal: let it finish and report its own exit code.
|
|
82
|
+
const ignore = () => { };
|
|
83
|
+
process.on("SIGINT", ignore);
|
|
84
|
+
child.on("error", (err) => {
|
|
85
|
+
process.off("SIGINT", ignore);
|
|
86
|
+
reject(err);
|
|
87
|
+
});
|
|
88
|
+
child.on("close", (code, signal) => {
|
|
89
|
+
process.off("SIGINT", ignore);
|
|
90
|
+
resolve(code ?? (signal ? 130 : 1));
|
|
91
|
+
});
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
const CAPTURE_BYTES = 128 * 1024;
|
|
95
|
+
/** How long a stopped command gets to exit before it is killed, and again before the call gives up on it. */
|
|
96
|
+
const KILL_GRACE_MS = 5000;
|
|
97
|
+
/**
|
|
98
|
+
* Run `compose -p <project> <args…>` and capture the end of its output
|
|
99
|
+
* (for the MCP server, whose stdout is the protocol). A non-zero exit is a
|
|
100
|
+
* result, not an error; only a command that could not run at all, timed
|
|
101
|
+
* out, or was cancelled throws.
|
|
102
|
+
*/
|
|
103
|
+
export function runCaptured(call, args, opts = {}) {
|
|
104
|
+
const maxLines = opts.maxLines ?? 200;
|
|
105
|
+
const grace = opts.killGraceMs ?? KILL_GRACE_MS;
|
|
106
|
+
const file = composeBin(call.engine);
|
|
107
|
+
const argv = composeArgs(call.engine, call.worktree.project, ...args);
|
|
108
|
+
const command = [file, ...argv].join(" ");
|
|
109
|
+
return new Promise((resolve, reject) => {
|
|
110
|
+
if (opts.signal?.aborted) {
|
|
111
|
+
reject(new CommandError(command, null, "", "Command cancelled"));
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
const child = spawn(file, argv, {
|
|
115
|
+
cwd: call.worktree.path,
|
|
116
|
+
env: processEnv(call.env),
|
|
117
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
118
|
+
windowsHide: true,
|
|
119
|
+
});
|
|
120
|
+
let text = "";
|
|
121
|
+
let truncated = false;
|
|
122
|
+
const collect = (chunk) => {
|
|
123
|
+
text += chunk;
|
|
124
|
+
if (text.length > CAPTURE_BYTES * 2) {
|
|
125
|
+
text = text.slice(-CAPTURE_BYTES);
|
|
126
|
+
truncated = true;
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
child.stdout?.setEncoding("utf-8");
|
|
130
|
+
child.stderr?.setEncoding("utf-8");
|
|
131
|
+
child.stdout?.on("data", collect);
|
|
132
|
+
child.stderr?.on("data", collect);
|
|
133
|
+
let stopReason = null;
|
|
134
|
+
let settled = false;
|
|
135
|
+
let killTimer = null;
|
|
136
|
+
const stop = (reason) => {
|
|
137
|
+
if (stopReason)
|
|
138
|
+
return;
|
|
139
|
+
stopReason = reason;
|
|
140
|
+
child.kill("SIGTERM");
|
|
141
|
+
// A child that ignores the signal, or whose own child keeps the pipes open,
|
|
142
|
+
// would leave the caller waiting for good: kill it, then stop waiting.
|
|
143
|
+
killTimer = setTimeout(() => {
|
|
144
|
+
child.kill("SIGKILL");
|
|
145
|
+
child.stdout?.destroy();
|
|
146
|
+
child.stderr?.destroy();
|
|
147
|
+
killTimer = setTimeout(() => {
|
|
148
|
+
if (settled)
|
|
149
|
+
return;
|
|
150
|
+
settled = true;
|
|
151
|
+
done();
|
|
152
|
+
reject(new CommandError(command, null, tailLines(text, maxLines), reason));
|
|
153
|
+
}, grace);
|
|
154
|
+
killTimer.unref();
|
|
155
|
+
}, grace);
|
|
156
|
+
killTimer.unref();
|
|
157
|
+
};
|
|
158
|
+
const onAbort = () => stop("Command cancelled");
|
|
159
|
+
opts.signal?.addEventListener("abort", onAbort, { once: true });
|
|
160
|
+
const timer = opts.timeoutMs !== undefined
|
|
161
|
+
? setTimeout(() => stop(`Command timed out after ${Math.round(opts.timeoutMs / 1000)}s`), opts.timeoutMs)
|
|
162
|
+
: null;
|
|
163
|
+
const done = () => {
|
|
164
|
+
if (timer)
|
|
165
|
+
clearTimeout(timer);
|
|
166
|
+
if (killTimer)
|
|
167
|
+
clearTimeout(killTimer);
|
|
168
|
+
opts.signal?.removeEventListener("abort", onAbort);
|
|
169
|
+
};
|
|
170
|
+
child.on("error", (err) => {
|
|
171
|
+
if (settled)
|
|
172
|
+
return;
|
|
173
|
+
settled = true;
|
|
174
|
+
done();
|
|
175
|
+
reject(new CommandError(command, null, "", err.message));
|
|
176
|
+
});
|
|
177
|
+
child.on("close", (code) => {
|
|
178
|
+
if (settled)
|
|
179
|
+
return;
|
|
180
|
+
settled = true;
|
|
181
|
+
done();
|
|
182
|
+
const lines = text.trim().split("\n");
|
|
183
|
+
if (lines.length > maxLines)
|
|
184
|
+
truncated = true;
|
|
185
|
+
const output = tailLines(text, maxLines);
|
|
186
|
+
if (stopReason) {
|
|
187
|
+
reject(new CommandError(command, null, output, stopReason));
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
resolve({ exitCode: code ?? 1, output, truncated });
|
|
191
|
+
});
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
/** A service name is a name: one that starts with `-` would be read by compose as an option. */
|
|
195
|
+
export function assertServiceName(service) {
|
|
196
|
+
if (!service || service.startsWith("-")) {
|
|
197
|
+
throw new Error(`Invalid service name ${JSON.stringify(service)}: give the compose service's name (see 'wtc list').`);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
/** `exec` arguments: no TTY allocation unless the terminal is interactive. */
|
|
201
|
+
export function execArgs(service, command, interactive) {
|
|
202
|
+
assertServiceName(service);
|
|
203
|
+
return ["exec", ...(interactive ? [] : ["-T"]), service, ...command];
|
|
204
|
+
}
|
|
205
|
+
export function logsArgs(options) {
|
|
206
|
+
(options.services ?? []).forEach(assertServiceName);
|
|
207
|
+
return [
|
|
208
|
+
"logs",
|
|
209
|
+
"--no-color",
|
|
210
|
+
"--tail",
|
|
211
|
+
String(options.tail ?? 100),
|
|
212
|
+
...(options.since ? ["--since", options.since] : []),
|
|
213
|
+
...(options.follow ? ["--follow"] : []),
|
|
214
|
+
...(options.services ?? []),
|
|
215
|
+
];
|
|
216
|
+
}
|
package/dist/core/promote.d.ts
CHANGED
|
@@ -34,7 +34,9 @@ export declare class PromoteConflictError extends Error {
|
|
|
34
34
|
}
|
|
35
35
|
/**
|
|
36
36
|
* Copy a worktree's changes (committed, staged, unstaged, untracked) into the
|
|
37
|
-
* checkout wtc runs from, as uncommitted changes.
|
|
38
|
-
*
|
|
37
|
+
* checkout wtc runs from, as uncommitted changes. What wtc itself put into
|
|
38
|
+
* the worktree is left out: env files it wrote, and untracked copies of the
|
|
39
|
+
* compose files. The branch's own changes to its compose and env files
|
|
40
|
+
* promote like any other.
|
|
39
41
|
*/
|
|
40
42
|
export declare function promoteWorktree(options: PromoteOptions, reporter: Reporter, io: CoreIo): Promise<PromoteResult>;
|
package/dist/core/promote.js
CHANGED
|
@@ -51,8 +51,10 @@ export class PromoteConflictError extends Error {
|
|
|
51
51
|
}
|
|
52
52
|
/**
|
|
53
53
|
* Copy a worktree's changes (committed, staged, unstaged, untracked) into the
|
|
54
|
-
* checkout wtc runs from, as uncommitted changes.
|
|
55
|
-
*
|
|
54
|
+
* checkout wtc runs from, as uncommitted changes. What wtc itself put into
|
|
55
|
+
* the worktree is left out: env files it wrote, and untracked copies of the
|
|
56
|
+
* compose files. The branch's own changes to its compose and env files
|
|
57
|
+
* promote like any other.
|
|
56
58
|
*/
|
|
57
59
|
export async function promoteWorktree(options, reporter, io) {
|
|
58
60
|
const ctx = buildContext({}, { cwd: io.cwd, allowMissingCompose: true });
|
|
@@ -73,7 +75,7 @@ export async function promoteWorktree(options, reporter, io) {
|
|
|
73
75
|
excludes.add(rel.split(path.sep).join("/"));
|
|
74
76
|
}
|
|
75
77
|
const mergeBase = getMergeBase(target, wt.path);
|
|
76
|
-
const files = getChangedFiles(target, wt.path, excludes, mergeBase);
|
|
78
|
+
const files = getChangedFiles(target, wt.path, excludes, mergeBase, new Set(wt.envFiles ?? []));
|
|
77
79
|
const result = {
|
|
78
80
|
worktree: { index: wt.index, branch: wt.branch, path: wt.path },
|
|
79
81
|
target,
|
package/dist/core/restart.d.ts
CHANGED
|
@@ -7,8 +7,8 @@ import type { CoreIo } from "./types.js";
|
|
|
7
7
|
* ones are recreated by compose — which carries their anonymous volumes
|
|
8
8
|
* over, unlike the old `down` + `up`, which brought image-declared volumes
|
|
9
9
|
* back empty — and containers of services removed from the compose file
|
|
10
|
-
* go away, as `down` used to make them. Env options and
|
|
11
|
-
* validated while every worktree is still running,
|
|
12
|
-
* stacks stopped.
|
|
10
|
+
* go away, as `down` used to make them. Env options, selectors and the
|
|
11
|
+
* service selection are validated while every worktree is still running,
|
|
12
|
+
* so a typo never leaves stacks stopped.
|
|
13
13
|
*/
|
|
14
14
|
export declare function restartWorktrees(options: StartOptions, reporter: Reporter, io: CoreIo): Promise<StartResult>;
|
package/dist/core/restart.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { preflightEnvOptions } from "../context.js";
|
|
2
|
-
import { startWorktrees } from "./start.js";
|
|
2
|
+
import { preflightServices, startWorktrees } from "./start.js";
|
|
3
3
|
import { stopWorktrees } from "./stop.js";
|
|
4
4
|
/**
|
|
5
5
|
* Stop then start (`compose stop`, then start's sync/inject + `up -d
|
|
@@ -7,12 +7,13 @@ import { stopWorktrees } from "./stop.js";
|
|
|
7
7
|
* ones are recreated by compose — which carries their anonymous volumes
|
|
8
8
|
* over, unlike the old `down` + `up`, which brought image-declared volumes
|
|
9
9
|
* back empty — and containers of services removed from the compose file
|
|
10
|
-
* go away, as `down` used to make them. Env options and
|
|
11
|
-
* validated while every worktree is still running,
|
|
12
|
-
* stacks stopped.
|
|
10
|
+
* go away, as `down` used to make them. Env options, selectors and the
|
|
11
|
+
* service selection are validated while every worktree is still running,
|
|
12
|
+
* so a typo never leaves stacks stopped.
|
|
13
13
|
*/
|
|
14
14
|
export async function restartWorktrees(options, reporter, io) {
|
|
15
15
|
preflightEnvOptions(options, io.cwd, { requireMainFor: "restart worktree stacks" });
|
|
16
|
-
|
|
16
|
+
preflightServices(options, io);
|
|
17
|
+
await stopWorktrees({ worktrees: options.worktrees, all: options.all, quiet: true }, reporter, io);
|
|
17
18
|
return startWorktrees({ ...options, removeOrphans: true }, reporter, io);
|
|
18
19
|
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import type { ComposeEngine } from "../compose/engine.js";
|
|
2
|
+
import type { PsContainer } from "../compose/status.js";
|
|
3
|
+
import type { ComposeFile } from "../compose/types.js";
|
|
4
|
+
import type { Reporter } from "../utils/log.js";
|
|
5
|
+
/** Image of the throwaway container that copies a volume (needs `sh` and `cp -a`). */
|
|
6
|
+
export declare function helperImage(env?: NodeJS.ProcessEnv): string;
|
|
7
|
+
/** The name compose gives a project by default: its directory's, lower-cased, without what compose drops. */
|
|
8
|
+
export declare function defaultProjectName(dir: string): string;
|
|
9
|
+
/**
|
|
10
|
+
* The names compose would give the main checkout's stack, most
|
|
11
|
+
* authoritative first: its `COMPOSE_PROJECT_NAME`, the compose file's own
|
|
12
|
+
* `name:`, then the name compose derives from the directory.
|
|
13
|
+
*/
|
|
14
|
+
export declare function expectedMainProjects(mainDirs: string[], declaredName?: string): string[];
|
|
15
|
+
/**
|
|
16
|
+
* Compose projects the main checkout's stack may run as: the project of any
|
|
17
|
+
* container that ran from its directory, then the names compose would give
|
|
18
|
+
* it (see `expectedMainProjects`).
|
|
19
|
+
*/
|
|
20
|
+
export declare function mainProjectNames(containers: PsContainer[], mainDirs: string[], worktreeProjects: ReadonlySet<string>, declaredName?: string): string[];
|
|
21
|
+
export interface SeedInput {
|
|
22
|
+
engine: ComposeEngine;
|
|
23
|
+
project: string;
|
|
24
|
+
composeFile: ComposeFile;
|
|
25
|
+
/** `true`: every volume of the project; or the volume keys to copy. */
|
|
26
|
+
volumes: true | string[];
|
|
27
|
+
/**
|
|
28
|
+
* The volumes the services this start brings up mount: only those are
|
|
29
|
+
* copied. A shared service's volume, or one of a service left out, would
|
|
30
|
+
* be copied for nothing — and its containers paused for it.
|
|
31
|
+
*/
|
|
32
|
+
mounted?: ReadonlySet<string>;
|
|
33
|
+
mainDirs: string[];
|
|
34
|
+
/** The main compose file's own `name:`, when it sets one. */
|
|
35
|
+
mainProjectName?: string;
|
|
36
|
+
worktreeProjects: ReadonlySet<string>;
|
|
37
|
+
containers: PsContainer[];
|
|
38
|
+
reporter: Reporter;
|
|
39
|
+
signal?: AbortSignal;
|
|
40
|
+
}
|
|
41
|
+
export interface SeedResult {
|
|
42
|
+
seeded: string[];
|
|
43
|
+
warnings: string[];
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Copy the main checkout stack's volumes into the worktree stack's, for
|
|
47
|
+
* each volume the worktree stack does not have yet. Never touches a volume
|
|
48
|
+
* that exists.
|
|
49
|
+
*/
|
|
50
|
+
export declare function seedVolumes(input: SeedInput): Promise<SeedResult>;
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { ENGINE_PROBE_TIMEOUT_MS, run, runAsync, runSafe } from "../utils/exec.js";
|
|
3
|
+
import { cliCall } from "../compose/engine.js";
|
|
4
|
+
import { field, labelsOf, parseJsonListing, PROJECT_LABELS } from "../compose/status.js";
|
|
5
|
+
import { samePath } from "../git/worktree.js";
|
|
6
|
+
import { envFileValue } from "../compose/override.js";
|
|
7
|
+
/**
|
|
8
|
+
* Warm starts. A new worktree stack begins with empty volumes: an empty
|
|
9
|
+
* database to create, migrate and seed, dependency caches to refill. With
|
|
10
|
+
* `seedVolumes`, the first start copies the main checkout stack's named
|
|
11
|
+
* volumes into the new stack's instead, so it comes up with the data and
|
|
12
|
+
* caches the main checkout already has.
|
|
13
|
+
*
|
|
14
|
+
* A volume is copied only when the worktree stack does not have it yet;
|
|
15
|
+
* afterwards the two are independent. The copy runs in a throwaway
|
|
16
|
+
* container. Containers writing to the source volume are paused for the
|
|
17
|
+
* copy, so what is copied is a consistent snapshot (the state a database
|
|
18
|
+
* recovers from after a power cut), and resumed right after.
|
|
19
|
+
*/
|
|
20
|
+
const VOLUME_LABEL = "com.docker.compose.volume";
|
|
21
|
+
/** Image of the throwaway container that copies a volume (needs `sh` and `cp -a`). */
|
|
22
|
+
export function helperImage(env = process.env) {
|
|
23
|
+
return env.WTC_HELPER_IMAGE?.trim() || "busybox:stable";
|
|
24
|
+
}
|
|
25
|
+
/** The name compose gives a project by default: its directory's, lower-cased, without what compose drops. */
|
|
26
|
+
export function defaultProjectName(dir) {
|
|
27
|
+
return path
|
|
28
|
+
.basename(path.resolve(dir))
|
|
29
|
+
.toLowerCase()
|
|
30
|
+
.replace(/[^a-z0-9_-]/g, "")
|
|
31
|
+
.replace(/^[_-]+/, "");
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* The names compose would give the main checkout's stack, most
|
|
35
|
+
* authoritative first: its `COMPOSE_PROJECT_NAME`, the compose file's own
|
|
36
|
+
* `name:`, then the name compose derives from the directory.
|
|
37
|
+
*/
|
|
38
|
+
export function expectedMainProjects(mainDirs, declaredName) {
|
|
39
|
+
const names = [];
|
|
40
|
+
for (const dir of mainDirs) {
|
|
41
|
+
const fromEnv = envFileValue(path.join(dir, ".env"), "COMPOSE_PROJECT_NAME");
|
|
42
|
+
if (fromEnv)
|
|
43
|
+
names.push(fromEnv);
|
|
44
|
+
}
|
|
45
|
+
if (declaredName)
|
|
46
|
+
names.push(declaredName);
|
|
47
|
+
for (const dir of mainDirs) {
|
|
48
|
+
const derived = defaultProjectName(dir);
|
|
49
|
+
if (derived)
|
|
50
|
+
names.push(derived);
|
|
51
|
+
}
|
|
52
|
+
return [...new Set(names)];
|
|
53
|
+
}
|
|
54
|
+
/** Compose projects of containers that ran from the main checkout's directories. */
|
|
55
|
+
function observedMainProjects(containers, mainDirs, worktreeProjects) {
|
|
56
|
+
const names = new Set();
|
|
57
|
+
for (const c of containers) {
|
|
58
|
+
if (!c.project || !c.workingDir || worktreeProjects.has(c.project))
|
|
59
|
+
continue;
|
|
60
|
+
if (mainDirs.some((dir) => samePath(dir, c.workingDir)))
|
|
61
|
+
names.add(c.project);
|
|
62
|
+
}
|
|
63
|
+
return [...names];
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Compose projects the main checkout's stack may run as: the project of any
|
|
67
|
+
* container that ran from its directory, then the names compose would give
|
|
68
|
+
* it (see `expectedMainProjects`).
|
|
69
|
+
*/
|
|
70
|
+
export function mainProjectNames(containers, mainDirs, worktreeProjects, declaredName) {
|
|
71
|
+
return [
|
|
72
|
+
...new Set([
|
|
73
|
+
...observedMainProjects(containers, mainDirs, worktreeProjects),
|
|
74
|
+
...expectedMainProjects(mainDirs, declaredName),
|
|
75
|
+
]),
|
|
76
|
+
].filter((n) => !worktreeProjects.has(n));
|
|
77
|
+
}
|
|
78
|
+
function listVolumes(engine) {
|
|
79
|
+
const [file, args] = cliCall(engine, "volume", "ls", "--format", "json");
|
|
80
|
+
return parseJsonListing(run(file, args, { timeoutMs: ENGINE_PROBE_TIMEOUT_MS })).map((v) => {
|
|
81
|
+
const labels = labelsOf(v);
|
|
82
|
+
return {
|
|
83
|
+
name: String(field(v, "Name") ?? ""),
|
|
84
|
+
project: PROJECT_LABELS.map((l) => labels[l]).find(Boolean) ?? null,
|
|
85
|
+
key: labels[VOLUME_LABEL] ?? null,
|
|
86
|
+
};
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
/** How long one volume's copy may take (an image pull included) before it is given up and its writers resumed. */
|
|
90
|
+
const SEED_COPY_TIMEOUT_MS = 30 * 60 * 1000;
|
|
91
|
+
/**
|
|
92
|
+
* Copy the main checkout stack's volumes into the worktree stack's, for
|
|
93
|
+
* each volume the worktree stack does not have yet. Never touches a volume
|
|
94
|
+
* that exists.
|
|
95
|
+
*/
|
|
96
|
+
export async function seedVolumes(input) {
|
|
97
|
+
const result = { seeded: [], warnings: [] };
|
|
98
|
+
const declared = input.composeFile.projectVolumes ?? [];
|
|
99
|
+
const wanted = [...new Set(input.volumes === true ? declared : input.volumes)];
|
|
100
|
+
for (const key of wanted) {
|
|
101
|
+
if (!declared.includes(key)) {
|
|
102
|
+
result.warnings.push(`"seedVolumes" names "${key}", which is not a volume of the compose file's own (or has a fixed name); skipped.`);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
const keys = wanted.filter((key) => declared.includes(key) && (!input.mounted || input.mounted.has(key)));
|
|
106
|
+
if (keys.length === 0)
|
|
107
|
+
return result;
|
|
108
|
+
let volumes;
|
|
109
|
+
try {
|
|
110
|
+
volumes = listVolumes(input.engine);
|
|
111
|
+
}
|
|
112
|
+
catch (err) {
|
|
113
|
+
result.warnings.push(`Could not list volumes to seed from: ${err instanceof Error ? err.message.split("\n")[0] : String(err)}`);
|
|
114
|
+
return result;
|
|
115
|
+
}
|
|
116
|
+
const existing = new Set(volumes.map((v) => v.name));
|
|
117
|
+
// Where the main checkout's stack was seen running comes first; a name compose
|
|
118
|
+
// would only give it by default never outranks that.
|
|
119
|
+
const observed = observedMainProjects(input.containers, input.mainDirs, input.worktreeProjects);
|
|
120
|
+
const tiers = [
|
|
121
|
+
observed,
|
|
122
|
+
...expectedMainProjects(input.mainDirs, input.mainProjectName)
|
|
123
|
+
.filter((n) => !input.worktreeProjects.has(n) && !observed.includes(n))
|
|
124
|
+
.map((n) => [n]),
|
|
125
|
+
];
|
|
126
|
+
const sourcesOf = (key) => {
|
|
127
|
+
for (const tier of tiers) {
|
|
128
|
+
const found = volumes.filter((v) => v.key === key && v.project !== null && tier.includes(v.project));
|
|
129
|
+
if (found.length > 0)
|
|
130
|
+
return found;
|
|
131
|
+
}
|
|
132
|
+
return [];
|
|
133
|
+
};
|
|
134
|
+
for (const key of keys) {
|
|
135
|
+
if (input.signal?.aborted)
|
|
136
|
+
break;
|
|
137
|
+
const dst = `${input.project}_${key}`;
|
|
138
|
+
if (existing.has(dst))
|
|
139
|
+
continue;
|
|
140
|
+
const sources = sourcesOf(key);
|
|
141
|
+
if (sources.length === 0)
|
|
142
|
+
continue; // the main checkout has no such volume: nothing to copy
|
|
143
|
+
if (sources.length > 1) {
|
|
144
|
+
result.warnings.push(`Volume "${key}" exists in several stacks run from the main checkout (${sources.map((s) => s.name).join(", ")}): ` +
|
|
145
|
+
`not seeded, because wtc does not guess which one to copy. The stack starts with an empty one.`);
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
const src = sources[0];
|
|
149
|
+
const stillPaused = [];
|
|
150
|
+
const pausedNotes = () => stillPaused.map((id) => {
|
|
151
|
+
const [file, args] = cliCall(input.engine, "unpause", id);
|
|
152
|
+
return `Container ${id} of the main checkout's stack is still paused after copying "${key}": resume it with '${[file, ...args].join(" ")}'.`;
|
|
153
|
+
});
|
|
154
|
+
try {
|
|
155
|
+
await copyVolume(input, src.name, dst, key, stillPaused);
|
|
156
|
+
result.seeded.push(key);
|
|
157
|
+
}
|
|
158
|
+
catch (err) {
|
|
159
|
+
// A partly filled volume would look seeded next time, and the stack would start on it: it must go.
|
|
160
|
+
const [file, args] = cliCall(input.engine, "volume", "rm", "-f", dst);
|
|
161
|
+
if (runSafe(file, args, { timeoutMs: ENGINE_PROBE_TIMEOUT_MS }) === null) {
|
|
162
|
+
throw new Error([
|
|
163
|
+
`Could not seed volume "${key}" from ${src.name} (${lastErrorLine(err)}), and could not remove the partly filled ${dst}. ` +
|
|
164
|
+
`Remove it ('${[file, ...args].join(" ")}'), then start again.`,
|
|
165
|
+
...pausedNotes(),
|
|
166
|
+
].join(" "));
|
|
167
|
+
}
|
|
168
|
+
result.warnings.push(`Could not seed volume "${key}" from ${src.name}: ${lastErrorLine(err)}. The stack starts with an empty one.`);
|
|
169
|
+
}
|
|
170
|
+
result.warnings.push(...pausedNotes());
|
|
171
|
+
}
|
|
172
|
+
return result;
|
|
173
|
+
}
|
|
174
|
+
/** The line of a failed command's output that says what went wrong (docker ends with a usage hint). */
|
|
175
|
+
function lastErrorLine(err) {
|
|
176
|
+
const lines = (err instanceof Error ? err.message : String(err))
|
|
177
|
+
.split("\n")
|
|
178
|
+
.map((l) => l.trim())
|
|
179
|
+
.filter((l) => l && !/^Run '.* --help' for more information/.test(l) && !/^See '.* --help'/.test(l));
|
|
180
|
+
return lines[lines.length - 1] ?? "unknown error";
|
|
181
|
+
}
|
|
182
|
+
async function copyVolume(input, src, dst, key,
|
|
183
|
+
/** Filled with the containers that could not be resumed. */
|
|
184
|
+
stillPaused) {
|
|
185
|
+
const { engine, project } = input;
|
|
186
|
+
const opts = { timeoutMs: ENGINE_PROBE_TIMEOUT_MS };
|
|
187
|
+
const [createFile, createArgs] = cliCall(engine, "volume", "create", "--label", `com.docker.compose.project=${project}`, "--label", `${VOLUME_LABEL}=${key}`, dst);
|
|
188
|
+
run(createFile, createArgs, opts);
|
|
189
|
+
// Containers writing to the source are paused, so the copy is one moment's state.
|
|
190
|
+
const [psFile, psArgs] = cliCall(engine, "ps", "-q", "--filter", `volume=${src}`, "--filter", "status=running");
|
|
191
|
+
const listed = runSafe(psFile, psArgs, opts);
|
|
192
|
+
// Copying while something may still write would be a seed nobody can trust.
|
|
193
|
+
if (listed === null)
|
|
194
|
+
throw new Error("could not list the containers that write to it");
|
|
195
|
+
const writers = listed.split("\n").map((l) => l.trim()).filter(Boolean);
|
|
196
|
+
// An image that is certainly on this machine: the one of a container that mounts the
|
|
197
|
+
// volume. The helper image is the fallback (it may have to be pulled).
|
|
198
|
+
const [imgFile, imgArgs] = cliCall(engine, "ps", "-a", "--filter", `volume=${src}`, "--format", "{{.Image}}");
|
|
199
|
+
const images = [
|
|
200
|
+
...new Set([
|
|
201
|
+
...(runSafe(imgFile, imgArgs, opts) ?? "").split("\n").map((l) => l.trim()).filter(Boolean),
|
|
202
|
+
helperImage(),
|
|
203
|
+
]),
|
|
204
|
+
];
|
|
205
|
+
const paused = [];
|
|
206
|
+
try {
|
|
207
|
+
for (const id of writers) {
|
|
208
|
+
const [file, args] = cliCall(engine, "pause", id);
|
|
209
|
+
if (runSafe(file, args, opts) === null)
|
|
210
|
+
throw new Error(`could not pause container ${id}, which writes to it`);
|
|
211
|
+
paused.push(id);
|
|
212
|
+
}
|
|
213
|
+
input.reporter.info(`Seeding volume ${key} from the main checkout (${src})...`);
|
|
214
|
+
let failure = null;
|
|
215
|
+
for (const image of images) {
|
|
216
|
+
const [runFile, runArgs] = cliCall(engine, "run", "--rm", "--network", "none",
|
|
217
|
+
// Root, whatever user the image runs as: ownership must be copied as it is.
|
|
218
|
+
"--user", "0:0", "--entrypoint", "sh", "-v", `${src}:/from:ro`, "-v", `${dst}:/to`, image, "-c", "cp -a /from/. /to/");
|
|
219
|
+
try {
|
|
220
|
+
await runAsync(runFile, runArgs, { signal: input.signal, timeoutMs: SEED_COPY_TIMEOUT_MS });
|
|
221
|
+
failure = null;
|
|
222
|
+
break;
|
|
223
|
+
}
|
|
224
|
+
catch (err) {
|
|
225
|
+
// No shell in that image, or it could not be pulled: try the next one.
|
|
226
|
+
failure = err;
|
|
227
|
+
if (input.signal?.aborted)
|
|
228
|
+
break;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
if (failure)
|
|
232
|
+
throw failure;
|
|
233
|
+
}
|
|
234
|
+
finally {
|
|
235
|
+
for (const id of paused) {
|
|
236
|
+
const [file, args] = cliCall(engine, "unpause", id);
|
|
237
|
+
if (runSafe(file, args, opts) !== null)
|
|
238
|
+
continue;
|
|
239
|
+
// The main checkout's database must not stay frozen over one failed call: once more.
|
|
240
|
+
await new Promise((resolve) => setTimeout(resolve, 500));
|
|
241
|
+
if (runSafe(file, args, opts) === null)
|
|
242
|
+
stillPaused.push(id);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { ComposeEngine } from "../compose/engine.js";
|
|
2
|
+
import type { OverrideExtras } from "../compose/override.js";
|
|
3
|
+
import type { PsContainer } from "../compose/status.js";
|
|
4
|
+
import type { ComposeFile } from "../compose/types.js";
|
|
5
|
+
/**
|
|
6
|
+
* Shared services. A heavy stack — a search cluster, a queue, an analytics
|
|
7
|
+
* database — is too much to run once per worktree. A service listed in the
|
|
8
|
+
* config's `shared` runs once, in the main checkout's stack; each worktree
|
|
9
|
+
* stack leaves it out and reaches the main one under the same name:
|
|
10
|
+
*
|
|
11
|
+
* - in the worktree stack the service gets a profile nothing enables, and
|
|
12
|
+
* is dropped from every `depends_on`, so compose neither starts it nor
|
|
13
|
+
* waits for it;
|
|
14
|
+
* - after `up`, the main checkout's container is connected to the worktree
|
|
15
|
+
* stack's networks with the service name (and its `container_name`) as
|
|
16
|
+
* aliases, so `kafka:9092` in a worktree container is the shared broker;
|
|
17
|
+
* - before the stack's networks are removed, it is disconnected again.
|
|
18
|
+
*
|
|
19
|
+
* Whatever lives in a shared service is shared too: that is the point,
|
|
20
|
+
* and the reason a database usually stays per-worktree.
|
|
21
|
+
*/
|
|
22
|
+
/** What a stack's override needs for the shared services its compose file declares. */
|
|
23
|
+
export declare function sharedExtras(composeFile: ComposeFile, shared: ReadonlySet<string>): Pick<OverrideExtras, "shared" | "dependsOn">;
|
|
24
|
+
/** Running containers of the main checkout's own stack, by service. */
|
|
25
|
+
export declare function mainStackContainers(containers: PsContainer[], mainDirs: string[], worktreeProjects: ReadonlySet<string>): Map<string, PsContainer[]>;
|
|
26
|
+
export interface SharedLinkInput {
|
|
27
|
+
engine: ComposeEngine;
|
|
28
|
+
project: string;
|
|
29
|
+
composeFile: ComposeFile;
|
|
30
|
+
shared: ReadonlySet<string>;
|
|
31
|
+
/** Directories the main checkout's stack may run from (its root; the compose file's directory). */
|
|
32
|
+
mainDirs: string[];
|
|
33
|
+
/** The main compose file's own `name:`, when it sets one. */
|
|
34
|
+
mainProjectName?: string;
|
|
35
|
+
/** Compose projects of this repository's worktree stacks (never the main checkout's). */
|
|
36
|
+
worktreeProjects: ReadonlySet<string>;
|
|
37
|
+
/** Lists the engine's containers (tests replace it). */
|
|
38
|
+
list?: () => PsContainer[];
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* The stack's networks by the key the compose file gives them, as the
|
|
42
|
+
* engine reports them (compose labels each network with its project and
|
|
43
|
+
* key): a network may carry a name of its own (`name:
|
|
44
|
+
* ${COMPOSE_PROJECT_NAME}-backend`). Empty when the listing fails.
|
|
45
|
+
*/
|
|
46
|
+
export declare function stackNetworkNames(engine: ComposeEngine, project: string): Map<string, string>;
|
|
47
|
+
/**
|
|
48
|
+
* Connect the main checkout's shared containers to a worktree stack's
|
|
49
|
+
* networks. Returns what was linked and a warning for each shared service
|
|
50
|
+
* the stack cannot reach.
|
|
51
|
+
*/
|
|
52
|
+
export declare function linkSharedServices(input: SharedLinkInput): {
|
|
53
|
+
linked: string[];
|
|
54
|
+
warnings: string[];
|
|
55
|
+
};
|
|
56
|
+
/**
|
|
57
|
+
* Disconnect the main checkout's containers from a stack's networks, so
|
|
58
|
+
* the networks can be removed with the stack: the shared containers
|
|
59
|
+
* `linkSharedServices` connected. A container of any other project stays
|
|
60
|
+
* as it is — wtc did not connect it, and the engine then says what holds
|
|
61
|
+
* the network. Best effort; returns how many connections were removed.
|
|
62
|
+
*/
|
|
63
|
+
export declare function unlinkSharedServices(engine: ComposeEngine, project: string, mainDirs: string[]): number;
|