worktree-compose 0.2.0 → 1.1.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 +501 -143
- package/SKILL.md +113 -0
- package/dist/cli.js +94 -33
- package/dist/commands/clean.d.ts +2 -1
- package/dist/commands/clean.js +8 -48
- package/dist/commands/doctor.d.ts +3 -0
- package/dist/commands/doctor.js +30 -0
- package/dist/commands/list.d.ts +4 -1
- package/dist/commands/list.js +62 -44
- package/dist/commands/promote.d.ts +3 -1
- package/dist/commands/promote.js +4 -34
- package/dist/commands/prune.d.ts +2 -0
- package/dist/commands/prune.js +7 -0
- package/dist/commands/restart.d.ts +2 -1
- package/dist/commands/restart.js +11 -5
- package/dist/commands/skill.d.ts +4 -0
- package/dist/commands/skill.js +10 -0
- package/dist/commands/start.d.ts +2 -1
- package/dist/commands/start.js +7 -34
- package/dist/commands/stop.d.ts +1 -1
- package/dist/commands/stop.js +6 -23
- package/dist/compose/detect.d.ts +1 -2
- package/dist/compose/detect.js +1 -10
- package/dist/compose/engine.d.ts +61 -0
- package/dist/compose/engine.js +129 -0
- package/dist/compose/isolation.d.ts +26 -0
- package/dist/compose/isolation.js +91 -0
- package/dist/compose/override.d.ts +152 -0
- package/dist/compose/override.js +542 -0
- package/dist/compose/parse.d.ts +12 -0
- package/dist/compose/parse.js +199 -29
- package/dist/compose/status.d.ts +84 -0
- package/dist/compose/status.js +227 -0
- package/dist/compose/types.d.ts +43 -0
- package/dist/config.d.ts +31 -0
- package/dist/config.js +23 -6
- package/dist/context.d.ts +104 -3
- package/dist/context.js +299 -45
- package/dist/core/clean.d.ts +91 -0
- package/dist/core/clean.js +347 -0
- package/dist/core/compose.d.ts +92 -0
- package/dist/core/compose.js +195 -0
- package/dist/core/doctor.d.ts +29 -0
- package/dist/core/doctor.js +342 -0
- package/dist/core/list.d.ts +46 -0
- package/dist/core/list.js +101 -0
- package/dist/core/promote.d.ts +40 -0
- package/dist/core/promote.js +117 -0
- package/dist/core/prune.d.ts +32 -0
- package/dist/core/prune.js +79 -0
- package/dist/core/restart.d.ts +14 -0
- package/dist/core/restart.js +18 -0
- package/dist/core/start.d.ts +33 -0
- package/dist/core/start.js +113 -0
- package/dist/core/stop.d.ts +32 -0
- package/dist/core/stop.js +58 -0
- package/dist/core/teardown.d.ts +123 -0
- package/dist/core/teardown.js +305 -0
- package/dist/core/types.d.ts +15 -0
- package/dist/core/types.js +1 -0
- package/dist/git/promote.d.ts +49 -2
- package/dist/git/promote.js +160 -38
- package/dist/git/repo.d.ts +72 -0
- package/dist/git/repo.js +167 -0
- package/dist/git/status.d.ts +8 -0
- package/dist/git/status.js +25 -0
- package/dist/git/worktree.d.ts +63 -3
- package/dist/git/worktree.js +173 -29
- package/dist/mcp/server.d.ts +2 -0
- package/dist/mcp/server.js +230 -115
- package/dist/ports/allocate.d.ts +39 -5
- package/dist/ports/allocate.js +96 -16
- package/dist/ports/extract.d.ts +12 -0
- package/dist/ports/extract.js +48 -4
- package/dist/ports/types.d.ts +12 -1
- package/dist/selectors.d.ts +10 -0
- package/dist/selectors.js +106 -0
- package/dist/skill.d.ts +13 -0
- package/dist/skill.js +28 -0
- package/dist/state/registry.d.ts +194 -0
- package/dist/state/registry.js +595 -0
- package/dist/sync/env.d.ts +93 -2
- package/dist/sync/env.js +169 -32
- package/dist/sync/files.d.ts +15 -1
- package/dist/sync/files.js +126 -38
- package/dist/utils/exec.d.ts +69 -4
- package/dist/utils/exec.js +221 -15
- package/dist/utils/log.d.ts +37 -0
- package/dist/utils/log.js +68 -4
- package/dist/utils/paths.d.ts +61 -0
- package/dist/utils/paths.js +163 -0
- package/dist/utils/sanitize.d.ts +7 -0
- package/dist/utils/sanitize.js +12 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +3 -0
- package/dist/workspaces/resolve.d.ts +21 -0
- package/dist/workspaces/resolve.js +235 -0
- package/package.json +20 -16
- package/wtc.schema.json +62 -0
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { buildContext, getEnvTargets } from "../context.js";
|
|
4
|
+
import { runSafe, run } from "../utils/exec.js";
|
|
5
|
+
import { isWithin } from "../utils/paths.js";
|
|
6
|
+
import { getDockerfiles, resolveSyncEntries } from "../sync/files.js";
|
|
7
|
+
import { getStatusPaths } from "../git/status.js";
|
|
8
|
+
import { samePath } from "../git/worktree.js";
|
|
9
|
+
import { forgetRecords } from "../state/registry.js";
|
|
10
|
+
import { overridePath, removeOverride } from "../compose/override.js";
|
|
11
|
+
import { reportContextWarnings, throwIfAborted } from "./compose.js";
|
|
12
|
+
import { orphanSkipReason, sweepStaleResources, teardownStack } from "./teardown.js";
|
|
13
|
+
/** Count a clean run's failures (see CleanResult.failures). */
|
|
14
|
+
function countFailures(result) {
|
|
15
|
+
if (result.dryRun)
|
|
16
|
+
return 0;
|
|
17
|
+
const sweep = result.sweep;
|
|
18
|
+
return (result.stacks.filter((s) => !s.ok).length +
|
|
19
|
+
result.removeFailed.length +
|
|
20
|
+
(sweep
|
|
21
|
+
? sweep.containers.failed.length +
|
|
22
|
+
sweep.networks.failed.length +
|
|
23
|
+
sweep.volumes.failed.length +
|
|
24
|
+
(sweep.error ? 1 : 0)
|
|
25
|
+
: 0));
|
|
26
|
+
}
|
|
27
|
+
/** True when `rel` is byte-identical (or the same symlink) in the worktree and in main. */
|
|
28
|
+
function mirrorsMain(repoRoot, wtPath, rel) {
|
|
29
|
+
const ours = path.join(wtPath, rel);
|
|
30
|
+
const theirs = path.join(repoRoot, rel);
|
|
31
|
+
try {
|
|
32
|
+
const a = fs.lstatSync(ours);
|
|
33
|
+
const b = fs.lstatSync(theirs);
|
|
34
|
+
if (a.isSymbolicLink() && b.isSymbolicLink()) {
|
|
35
|
+
return fs.readlinkSync(ours) === fs.readlinkSync(theirs);
|
|
36
|
+
}
|
|
37
|
+
if (!a.isFile() || !b.isFile() || a.size !== b.size)
|
|
38
|
+
return false;
|
|
39
|
+
return fs.readFileSync(ours).equals(fs.readFileSync(theirs));
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
return false;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Which uncommitted paths in a worktree are wtc's own artifacts rather than
|
|
47
|
+
* the user's work:
|
|
48
|
+
* - the env files wtc writes: `<dir>/<envFile>` for the root and each
|
|
49
|
+
* configured workspace, plus whatever the worktree's last `start` wrote
|
|
50
|
+
* (`--env`/`--workspace` may name others) — not every `.env.*` file, so an
|
|
51
|
+
* edited `.env.test` or `apps/x/.env.production` is the user's work;
|
|
52
|
+
* - compose sources (incl. includes), synced Dockerfiles and files under
|
|
53
|
+
* `sync` entries, but only while they are byte-identical to the main
|
|
54
|
+
* checkout's copy, i.e. exactly what start's sync wrote. An edit made in
|
|
55
|
+
* the worktree (or a file only the worktree has) is the user's work. If
|
|
56
|
+
* main changed since the last start this errs towards "dirty", which
|
|
57
|
+
* --force overrides.
|
|
58
|
+
*/
|
|
59
|
+
export function managedPathMatcher(ctx, wtPath, envFiles = []) {
|
|
60
|
+
const toPosix = (p) => p.split(path.sep).join("/");
|
|
61
|
+
const mirrored = new Set();
|
|
62
|
+
for (const src of ctx.composeFile.sourceFiles) {
|
|
63
|
+
mirrored.add(toPosix(path.relative(ctx.repoRoot, src)));
|
|
64
|
+
}
|
|
65
|
+
for (const df of getDockerfiles(ctx.composeFile, ctx.repoRoot)) {
|
|
66
|
+
mirrored.add(toPosix(df));
|
|
67
|
+
}
|
|
68
|
+
const prefixes = resolveSyncEntries(ctx.repoRoot, ctx.config.sync).entries.map(toPosix);
|
|
69
|
+
const envPaths = new Set(envFiles.map(toPosix));
|
|
70
|
+
try {
|
|
71
|
+
for (const t of getEnvTargets(ctx))
|
|
72
|
+
envPaths.add(path.posix.join(toPosix(t.dir), t.envFileName));
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
envPaths.add(ctx.config.envFile ?? ".env");
|
|
76
|
+
}
|
|
77
|
+
return (rel) => {
|
|
78
|
+
const p = rel.replace(/\/+$/, "");
|
|
79
|
+
if (envPaths.has(p))
|
|
80
|
+
return true;
|
|
81
|
+
const synced = mirrored.has(p) || prefixes.some((pre) => p === pre || p.startsWith(`${pre}/`));
|
|
82
|
+
return synced && mirrorsMain(ctx.repoRoot, wtPath, p);
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
/** Uncommitted paths in a worktree that wtc did not put there. */
|
|
86
|
+
export function unmanagedChanges(statusPaths, isManaged) {
|
|
87
|
+
return statusPaths.filter((p) => !isManaged(p));
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Commits that removing the worktree would make unreachable, beyond what
|
|
91
|
+
* `git status` shows:
|
|
92
|
+
* - a detached HEAD with commits no branch, tag or remote reaches (the
|
|
93
|
+
* worktree's HEAD reflog goes with it);
|
|
94
|
+
* - submodule commits not on any remote: the submodules' repositories live
|
|
95
|
+
* in the worktree's admin dir, which `git worktree remove --force`
|
|
96
|
+
* deletes (plain `remove` refuses worktrees with submodules for this
|
|
97
|
+
* reason; wtc needs --force for its own artifacts).
|
|
98
|
+
* Returns a reason, or `null` when nothing would be lost.
|
|
99
|
+
*/
|
|
100
|
+
export function unreachableWork(wt) {
|
|
101
|
+
if (wt.detached) {
|
|
102
|
+
try {
|
|
103
|
+
const sha = run("git", [
|
|
104
|
+
"-C",
|
|
105
|
+
wt.path,
|
|
106
|
+
"rev-list",
|
|
107
|
+
"--max-count=1",
|
|
108
|
+
"HEAD",
|
|
109
|
+
"--not",
|
|
110
|
+
"--branches",
|
|
111
|
+
"--tags",
|
|
112
|
+
"--remotes",
|
|
113
|
+
]);
|
|
114
|
+
if (sha) {
|
|
115
|
+
return `detached HEAD has commits no branch or tag reaches (HEAD ${sha.slice(0, 12)}); save them with 'git -C ${wt.path} branch <name>'`;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
catch (err) {
|
|
119
|
+
return `could not check its detached HEAD (${err instanceof Error ? err.message.split("\n")[0] : String(err)})`;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
const hasSubmodules = (wt.adminDir !== undefined && fs.existsSync(path.join(wt.adminDir, "modules"))) ||
|
|
123
|
+
fs.existsSync(path.join(wt.path, ".gitmodules"));
|
|
124
|
+
if (hasSubmodules) {
|
|
125
|
+
try {
|
|
126
|
+
const out = run("git", [
|
|
127
|
+
"-C",
|
|
128
|
+
wt.path,
|
|
129
|
+
"submodule",
|
|
130
|
+
"foreach",
|
|
131
|
+
"--quiet",
|
|
132
|
+
"--recursive",
|
|
133
|
+
"git rev-list -n1 --all --not --remotes",
|
|
134
|
+
]);
|
|
135
|
+
if (out.trim())
|
|
136
|
+
return "a submodule has commits not on any remote; push them first";
|
|
137
|
+
}
|
|
138
|
+
catch (err) {
|
|
139
|
+
return `could not check its submodules (${err instanceof Error ? err.message.split("\n")[0] : String(err)})`;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
return null;
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Tear down every worktree stack (live and orphaned), remove worktrees that
|
|
146
|
+
* hold no work of their own, sweep leftovers this checkout owns, and forget
|
|
147
|
+
* what was removed. Never removes the main checkout or the worktree it runs
|
|
148
|
+
* from.
|
|
149
|
+
*/
|
|
150
|
+
export async function clean(options, reporter, io) {
|
|
151
|
+
const dryRun = options.dryRun === true;
|
|
152
|
+
// probeStacks: with no registry yet (an upgrade from ≤0.2, or a lost
|
|
153
|
+
// state file) identities are adopted from the running stacks, so teardown
|
|
154
|
+
// targets their real project names instead of positional guesses.
|
|
155
|
+
const ctx = buildContext({}, {
|
|
156
|
+
cwd: io.cwd,
|
|
157
|
+
allowMissingCompose: true,
|
|
158
|
+
probeStacks: true,
|
|
159
|
+
readOnly: dryRun,
|
|
160
|
+
requireMainFor: "clean up worktrees",
|
|
161
|
+
});
|
|
162
|
+
reportContextWarnings(ctx, reporter, { isolation: false });
|
|
163
|
+
const result = {
|
|
164
|
+
dryRun,
|
|
165
|
+
stacks: [],
|
|
166
|
+
removed: [],
|
|
167
|
+
skipped: [],
|
|
168
|
+
removeFailed: [],
|
|
169
|
+
sweep: null,
|
|
170
|
+
forgotten: [],
|
|
171
|
+
failures: 0,
|
|
172
|
+
};
|
|
173
|
+
if (dryRun)
|
|
174
|
+
reporter.info("Dry run: nothing will be changed.");
|
|
175
|
+
let engine = null;
|
|
176
|
+
try {
|
|
177
|
+
engine = ctx.getEngine();
|
|
178
|
+
}
|
|
179
|
+
catch (err) {
|
|
180
|
+
reporter.warn(`${err instanceof Error ? err.message : String(err)} Skipping container teardown; registry records are kept so 'wtc prune' can finish later.`);
|
|
181
|
+
}
|
|
182
|
+
// Worktrees git still lists but wtc cannot manage (locked and missing on
|
|
183
|
+
// disk, or now the main checkout): their stacks and records stay.
|
|
184
|
+
for (const u of ctx.unavailable) {
|
|
185
|
+
const why = u.reason === "missing"
|
|
186
|
+
? "its worktree is locked and missing on disk (unmounted drive?)"
|
|
187
|
+
: "its worktree is now the main checkout";
|
|
188
|
+
result.skipped.push({ path: u.path, reason: why });
|
|
189
|
+
reporter.warn(`Skipping ${u.project}: ${why}.`);
|
|
190
|
+
}
|
|
191
|
+
// 1. Tear down every stack wtc knows about.
|
|
192
|
+
const targets = [
|
|
193
|
+
...ctx.worktrees.map((w) => ({ project: w.project, index: w.index, path: w.path, orphan: null })),
|
|
194
|
+
...ctx.orphans.map((o) => ({ project: o.project, index: o.index, path: o.path, orphan: o })),
|
|
195
|
+
];
|
|
196
|
+
const tornDown = new Set();
|
|
197
|
+
// Orphans whose worktree came back while cleaning (or could not be
|
|
198
|
+
// re-checked): never touched.
|
|
199
|
+
const leftAlone = new Set();
|
|
200
|
+
for (const t of targets) {
|
|
201
|
+
throwIfAborted(io);
|
|
202
|
+
if (!engine) {
|
|
203
|
+
result.stacks.push({ project: t.project, orphan: t.orphan !== null, ok: false, error: "no compose engine" });
|
|
204
|
+
continue;
|
|
205
|
+
}
|
|
206
|
+
if (t.orphan) {
|
|
207
|
+
const why = orphanSkipReason(ctx, t.orphan);
|
|
208
|
+
if (why) {
|
|
209
|
+
leftAlone.add(t.project);
|
|
210
|
+
reporter.warn(`Skipping ${t.project}: ${why}.`);
|
|
211
|
+
continue;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
if (dryRun) {
|
|
215
|
+
reporter.info(`Would stop ${t.project} (down -v --remove-orphans)${t.orphan ? " [removed worktree]" : ""}`);
|
|
216
|
+
result.stacks.push({ project: t.project, orphan: t.orphan !== null, ok: true });
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
219
|
+
reporter.info(`Stopping ${t.project}...`);
|
|
220
|
+
const outcome = await teardownStack(ctx, engine, t, io);
|
|
221
|
+
result.stacks.push({ project: t.project, orphan: t.orphan !== null, ...outcome });
|
|
222
|
+
if (outcome.ok) {
|
|
223
|
+
tornDown.add(t.project);
|
|
224
|
+
}
|
|
225
|
+
else {
|
|
226
|
+
reporter.warn(`Could not stop ${t.project}: ${outcome.error}`);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
// 2. Remove worktrees that hold no work of their own.
|
|
230
|
+
if (!options.keepWorktrees) {
|
|
231
|
+
for (const wt of ctx.worktrees) {
|
|
232
|
+
throwIfAborted(io);
|
|
233
|
+
// In a bare-repo layout the main checkout is a linked worktree: it is
|
|
234
|
+
// the env/config source and the user's primary checkout.
|
|
235
|
+
if (samePath(wt.path, ctx.repo.mainRoot)) {
|
|
236
|
+
result.skipped.push({ path: wt.path, reason: "main checkout" });
|
|
237
|
+
reporter.warn(`Skipping removal of the main checkout: ${wt.path}`);
|
|
238
|
+
continue;
|
|
239
|
+
}
|
|
240
|
+
if (isWithin(wt.path, ctx.cwd) || samePath(wt.path, ctx.repo.currentRoot)) {
|
|
241
|
+
result.skipped.push({ path: wt.path, reason: "current worktree" });
|
|
242
|
+
reporter.warn(`Skipping removal of current worktree: ${wt.path}`);
|
|
243
|
+
continue;
|
|
244
|
+
}
|
|
245
|
+
if (wt.locked && !options.force) {
|
|
246
|
+
result.skipped.push({ path: wt.path, reason: "locked" });
|
|
247
|
+
reporter.warn(`Skipping locked worktree ${wt.path} (unlock it, or use --force).`);
|
|
248
|
+
continue;
|
|
249
|
+
}
|
|
250
|
+
let dirty;
|
|
251
|
+
try {
|
|
252
|
+
dirty = unmanagedChanges(getStatusPaths(wt.path), managedPathMatcher(ctx, wt.path, wt.envFiles));
|
|
253
|
+
}
|
|
254
|
+
catch (err) {
|
|
255
|
+
dirty = [`(git status failed: ${err instanceof Error ? err.message.split("\n")[0] : String(err)})`];
|
|
256
|
+
}
|
|
257
|
+
if (dirty.length > 0 && !options.force) {
|
|
258
|
+
const shown = dirty.slice(0, 5).join(", ") + (dirty.length > 5 ? `, … (${dirty.length} total)` : "");
|
|
259
|
+
result.skipped.push({ path: wt.path, reason: `uncommitted changes: ${shown}` });
|
|
260
|
+
reporter.warn(`Skipping ${wt.path}: uncommitted changes (${shown}). Commit them, or use --force to discard.`);
|
|
261
|
+
continue;
|
|
262
|
+
}
|
|
263
|
+
const unreachable = unreachableWork(wt);
|
|
264
|
+
if (unreachable && !options.force) {
|
|
265
|
+
result.skipped.push({ path: wt.path, reason: unreachable });
|
|
266
|
+
reporter.warn(`Skipping ${wt.path}: ${unreachable} (or use --force to discard).`);
|
|
267
|
+
continue;
|
|
268
|
+
}
|
|
269
|
+
if (dryRun) {
|
|
270
|
+
reporter.info(`Would remove worktree ${wt.path}`);
|
|
271
|
+
result.removed.push(wt.path);
|
|
272
|
+
continue;
|
|
273
|
+
}
|
|
274
|
+
// --force is needed only because of wtc's own artifacts; a second
|
|
275
|
+
// --force is git's way of removing a locked worktree.
|
|
276
|
+
const force = wt.locked ? ["--force", "--force"] : ["--force"];
|
|
277
|
+
try {
|
|
278
|
+
run("git", ["-C", ctx.repoRoot, "worktree", "remove", ...force, "--", wt.path]);
|
|
279
|
+
result.removed.push(wt.path);
|
|
280
|
+
reporter.success(`Removed worktree ${wt.path}`);
|
|
281
|
+
if (unreachable)
|
|
282
|
+
reporter.warn(`Discarded with --force: ${unreachable}.`);
|
|
283
|
+
}
|
|
284
|
+
catch (err) {
|
|
285
|
+
const reason = err instanceof Error ? err.message : String(err);
|
|
286
|
+
result.removeFailed.push({ path: wt.path, reason });
|
|
287
|
+
reporter.warn(`Could not remove ${wt.path}: ${reason}`);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
// 3. Sweep leftovers this checkout owns (and, with --sweep, stale ones
|
|
292
|
+
// whose worktree directory is gone). A request cancelled during the
|
|
293
|
+
// last teardown stops here.
|
|
294
|
+
throwIfAborted(io);
|
|
295
|
+
if (engine) {
|
|
296
|
+
result.sweep = sweepStaleResources(engine.cliArgv, ctx.repoName, {
|
|
297
|
+
dryRun,
|
|
298
|
+
reporter,
|
|
299
|
+
runner: options.sweepRunner,
|
|
300
|
+
registryProjects: targets.map((t) => t.project),
|
|
301
|
+
// A dry run's `down -v` above would remove these first.
|
|
302
|
+
skipProjects: [
|
|
303
|
+
...leftAlone,
|
|
304
|
+
...ctx.unavailable.map((u) => u.project),
|
|
305
|
+
...(dryRun ? targets.map((t) => t.project) : []),
|
|
306
|
+
],
|
|
307
|
+
mainRoot: ctx.repo.mainRoot,
|
|
308
|
+
checkouts: targets.map((t) => t.path),
|
|
309
|
+
sweep: options.sweep === true,
|
|
310
|
+
});
|
|
311
|
+
}
|
|
312
|
+
// 4. Prune git metadata and forget what is gone.
|
|
313
|
+
if (!dryRun) {
|
|
314
|
+
runSafe("git", ["-C", ctx.repoRoot, "worktree", "prune"]);
|
|
315
|
+
const removed = new Set(result.removed);
|
|
316
|
+
const forget = targets.filter((t) => tornDown.has(t.project) && (t.orphan !== null || removed.has(t.path)));
|
|
317
|
+
forgetRecords(ctx.repo.commonDir, forget.map((t) => t.project));
|
|
318
|
+
// A kept worktree keeps its runtime override: its env file still lists it.
|
|
319
|
+
for (const t of forget)
|
|
320
|
+
removeOverride(overridePath(ctx.repo.commonDir, t.project));
|
|
321
|
+
result.forgotten = forget.map((t) => t.path);
|
|
322
|
+
}
|
|
323
|
+
result.failures = countFailures(result);
|
|
324
|
+
const sweep = result.sweep;
|
|
325
|
+
const swept = sweep
|
|
326
|
+
? `${sweep.containers.removed.length} container(s), ${sweep.networks.removed.length} network(s), ${sweep.volumes.removed.length} volume(s)`
|
|
327
|
+
: "nothing (no compose engine)";
|
|
328
|
+
const sweepFailed = sweep
|
|
329
|
+
? sweep.containers.failed.length + sweep.networks.failed.length + sweep.volumes.failed.length
|
|
330
|
+
: 0;
|
|
331
|
+
const kept = sweep ? (options.sweep ? 0 : sweep.stale.length) + sweep.notOwned.length : 0;
|
|
332
|
+
const stopped = result.stacks.filter((s) => s.ok).length;
|
|
333
|
+
const summary = `${dryRun ? "Dry run complete" : result.failures > 0 ? "Cleanup finished with failures" : "Cleanup complete"}: ` +
|
|
334
|
+
`${stopped}/${result.stacks.length} stack(s) ${dryRun ? "to stop" : "stopped"}, ` +
|
|
335
|
+
`${result.removed.length} worktree(s) ${dryRun ? "to remove" : "removed"}` +
|
|
336
|
+
(result.skipped.length > 0 ? ` (${result.skipped.length} skipped)` : "") +
|
|
337
|
+
(result.removeFailed.length > 0 ? ` (${result.removeFailed.length} failed)` : "") +
|
|
338
|
+
`, ${dryRun ? "would sweep" : "swept"} ${swept}` +
|
|
339
|
+
(sweepFailed > 0 ? ` (${sweepFailed} failed)` : "") +
|
|
340
|
+
(kept > 0 ? `, ${kept} leftover(s) kept` : "") +
|
|
341
|
+
".";
|
|
342
|
+
if (result.failures > 0)
|
|
343
|
+
reporter.warn(summary);
|
|
344
|
+
else
|
|
345
|
+
reporter.success(summary);
|
|
346
|
+
return result;
|
|
347
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import type { RunResult } from "../utils/exec.js";
|
|
2
|
+
import type { ComposeEngine } from "../compose/engine.js";
|
|
3
|
+
import type { RemapTargets } from "../compose/override.js";
|
|
4
|
+
import type { PortAllocation } from "../ports/types.js";
|
|
5
|
+
import type { Reporter } from "../utils/log.js";
|
|
6
|
+
import type { WtcContext } from "../context.js";
|
|
7
|
+
import type { CoreIo } from "./types.js";
|
|
8
|
+
/** Variables for a compose call, over the process environment; `undefined` removes one. */
|
|
9
|
+
export type ComposeCallEnv = Record<string, string | undefined>;
|
|
10
|
+
/**
|
|
11
|
+
* Process environment for a compose call on a worktree stack: the project
|
|
12
|
+
* name plus every allocated port, so `${VAR}` interpolation resolves to the
|
|
13
|
+
* worktree's ports no matter which env filename is configured — and the
|
|
14
|
+
* stack's `COMPOSE_FILE` when wtc remaps hardcoded settings at runtime,
|
|
15
|
+
* with the separator it was joined with (both beat a `.env` that says
|
|
16
|
+
* otherwise). Without one, an inherited `COMPOSE_FILE` that wtc wrote (a
|
|
17
|
+
* worktree's `.env` exported by direnv or similar) is removed: it names
|
|
18
|
+
* another stack's files, or an override that is gone.
|
|
19
|
+
*/
|
|
20
|
+
export declare function composeEnv(project: string, allocations: PortAllocation[], composeFile?: string | null, commonDir?: string): ComposeCallEnv;
|
|
21
|
+
export interface StackTarget {
|
|
22
|
+
project: string;
|
|
23
|
+
index: number;
|
|
24
|
+
/** Directory compose runs in: the worktree, or the main checkout for an orphan. */
|
|
25
|
+
dir: string;
|
|
26
|
+
}
|
|
27
|
+
export interface PreparedStack {
|
|
28
|
+
/** The stack's ports, remapped hardcoded ones included. */
|
|
29
|
+
allocations: PortAllocation[];
|
|
30
|
+
/** `COMPOSE_FILE` for the stack's compose calls when wtc's override applies, else null. */
|
|
31
|
+
composeFile: string | null;
|
|
32
|
+
/** Hardcoded settings left as they are in this directory, and why. */
|
|
33
|
+
warnings: string[];
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* What wtc remaps for a stack run from `dir`, without writing anything: the
|
|
37
|
+
* repository's targets minus what the directory's own compose override sets
|
|
38
|
+
* for a service — or nothing when its `.env` sets `COMPOSE_FILE` or
|
|
39
|
+
* `COMPOSE_PATH_SEPARATOR` (a worktree's unmanaged `.env`, with a custom
|
|
40
|
+
* envFile; the repository's own settings were checked with the context).
|
|
41
|
+
*/
|
|
42
|
+
export declare function stackRemap(ctx: WtcContext, dir: string, project: string): {
|
|
43
|
+
targets: RemapTargets | null;
|
|
44
|
+
warnings: string[];
|
|
45
|
+
};
|
|
46
|
+
/**
|
|
47
|
+
* The stack's ports: every variable, plus each hardcoded port in `targets`
|
|
48
|
+
* that can move in this worktree to a port the stack does not already
|
|
49
|
+
* publish (a hardcoded port it keeps, or one inside a range). Returns the
|
|
50
|
+
* targets actually remapped and a warning for each port left as it is.
|
|
51
|
+
*/
|
|
52
|
+
export declare function stackAllocations(ctx: WtcContext, index: number, targets: RemapTargets | null): {
|
|
53
|
+
allocations: PortAllocation[];
|
|
54
|
+
targets: RemapTargets | null;
|
|
55
|
+
warnings: string[];
|
|
56
|
+
};
|
|
57
|
+
/**
|
|
58
|
+
* Ports and compose files for one stack: the `COMPOSE_FILE` list compose
|
|
59
|
+
* would otherwise pick by itself — the compose file, the directory's own
|
|
60
|
+
* compose override if any — followed by wtc's override (see
|
|
61
|
+
* compose/override.ts), or null without one.
|
|
62
|
+
*
|
|
63
|
+
* `start` (`write`) writes the override, after syncing the worktree's
|
|
64
|
+
* compose file from main. `stop` and teardown use the override the stack
|
|
65
|
+
* was started with as it is: rewriting it from main's current compose file
|
|
66
|
+
* could name services the worktree's (older) compose file does not have,
|
|
67
|
+
* which the `COMPOSE_FILE` in the worktree's env file also loads.
|
|
68
|
+
*/
|
|
69
|
+
export declare function prepareStack(ctx: WtcContext, target: StackTarget, opts: {
|
|
70
|
+
write: boolean;
|
|
71
|
+
}): PreparedStack;
|
|
72
|
+
export interface ComposeCallOptions {
|
|
73
|
+
cwd: string;
|
|
74
|
+
env?: ComposeCallEnv;
|
|
75
|
+
live: boolean;
|
|
76
|
+
signal?: AbortSignal;
|
|
77
|
+
onLine?: (line: string) => void;
|
|
78
|
+
}
|
|
79
|
+
/** Run `<compose> -p <project> <args…>` without blocking the event loop. */
|
|
80
|
+
export declare function composeRun(engine: ComposeEngine, project: string, args: string[], opts: ComposeCallOptions): Promise<RunResult>;
|
|
81
|
+
/** Prefix an error with what was being done, keeping CommandError details. */
|
|
82
|
+
export declare function withContext(prefix: string, err: unknown): Error;
|
|
83
|
+
/**
|
|
84
|
+
* Report a context's general warnings (and, when asked, its isolation
|
|
85
|
+
* warnings plus what runtime remapping does).
|
|
86
|
+
*/
|
|
87
|
+
export declare function reportContextWarnings(ctx: WtcContext, reporter: Reporter, opts: {
|
|
88
|
+
isolation: boolean;
|
|
89
|
+
}): void;
|
|
90
|
+
/** Throw if the operation was cancelled (checked between worktrees). */
|
|
91
|
+
export declare function throwIfAborted(io: CoreIo): void;
|
|
92
|
+
export declare const NO_WORKTREES_HINT = "No extra worktrees found. Create one with:\n git worktree add ../my-branch my-branch";
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { CommandError, runAsync } from "../utils/exec.js";
|
|
4
|
+
import { composeArgs, composeBin } from "../compose/engine.js";
|
|
5
|
+
import { composeFileValue, composePathSeparator, envFileComposeFile, envFileValue, findUserOverride, isUserComposeFile, isWtcComposeFile, overridePath, remapIsEmpty, renderOverride, withoutUserOverride, writeOverride, } from "../compose/override.js";
|
|
6
|
+
import { allocateWorktreePorts, allocationEnv } from "../ports/allocate.js";
|
|
7
|
+
import { COMPOSE_FILE_VAR, PROJECT_NAME_VAR } from "../sync/env.js";
|
|
8
|
+
/**
|
|
9
|
+
* Process environment for a compose call on a worktree stack: the project
|
|
10
|
+
* name plus every allocated port, so `${VAR}` interpolation resolves to the
|
|
11
|
+
* worktree's ports no matter which env filename is configured — and the
|
|
12
|
+
* stack's `COMPOSE_FILE` when wtc remaps hardcoded settings at runtime,
|
|
13
|
+
* with the separator it was joined with (both beat a `.env` that says
|
|
14
|
+
* otherwise). Without one, an inherited `COMPOSE_FILE` that wtc wrote (a
|
|
15
|
+
* worktree's `.env` exported by direnv or similar) is removed: it names
|
|
16
|
+
* another stack's files, or an override that is gone.
|
|
17
|
+
*/
|
|
18
|
+
export function composeEnv(project, allocations, composeFile = null, commonDir) {
|
|
19
|
+
const inherited = process.env[COMPOSE_FILE_VAR];
|
|
20
|
+
const files = composeFile
|
|
21
|
+
? { [COMPOSE_FILE_VAR]: composeFile, COMPOSE_PATH_SEPARATOR: composePathSeparator() }
|
|
22
|
+
: commonDir && inherited && isWtcComposeFile(inherited, commonDir)
|
|
23
|
+
? { [COMPOSE_FILE_VAR]: undefined }
|
|
24
|
+
: {};
|
|
25
|
+
return { [PROJECT_NAME_VAR]: project, ...allocationEnv(allocations), ...files };
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* What wtc remaps for a stack run from `dir`, without writing anything: the
|
|
29
|
+
* repository's targets minus what the directory's own compose override sets
|
|
30
|
+
* for a service — or nothing when its `.env` sets `COMPOSE_FILE` or
|
|
31
|
+
* `COMPOSE_PATH_SEPARATOR` (a worktree's unmanaged `.env`, with a custom
|
|
32
|
+
* envFile; the repository's own settings were checked with the context).
|
|
33
|
+
*/
|
|
34
|
+
export function stackRemap(ctx, dir, project) {
|
|
35
|
+
if (!ctx.remap)
|
|
36
|
+
return { targets: null, warnings: [] };
|
|
37
|
+
const separator = separatorConflicts(dir);
|
|
38
|
+
if (separator || isUserComposeFile(envFileComposeFile(path.join(dir, ".env")), ctx.repo.commonDir)) {
|
|
39
|
+
return {
|
|
40
|
+
targets: null,
|
|
41
|
+
warnings: [
|
|
42
|
+
`${project}: its .env sets ${separator ? "COMPOSE_PATH_SEPARATOR" : "COMPOSE_FILE"}, so wtc does not remap hardcoded ports or container_name for it.`,
|
|
43
|
+
],
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
const { targets, warnings } = withoutUserOverride(ctx.remap, dir);
|
|
47
|
+
return { targets: remapIsEmpty(targets) ? null : targets, warnings };
|
|
48
|
+
}
|
|
49
|
+
/** Whether `dir`'s `.env` sets a `COMPOSE_PATH_SEPARATOR` that would split wtc's list differently. */
|
|
50
|
+
function separatorConflicts(dir) {
|
|
51
|
+
const separator = envFileValue(path.join(dir, ".env"), "COMPOSE_PATH_SEPARATOR");
|
|
52
|
+
return !!separator && separator !== composePathSeparator();
|
|
53
|
+
}
|
|
54
|
+
/** Host ports a stack keeps as written: hardcoded ones wtc does not move, ranges whole. */
|
|
55
|
+
function keptHostPorts(mappings, moving) {
|
|
56
|
+
const moved = new Set(moving);
|
|
57
|
+
return mappings
|
|
58
|
+
.filter((m) => m.envVar === null && !moved.has(m))
|
|
59
|
+
.map((m) => [m.defaultPort, m.rangeEnd ?? m.defaultPort]);
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* The stack's ports: every variable, plus each hardcoded port in `targets`
|
|
63
|
+
* that can move in this worktree to a port the stack does not already
|
|
64
|
+
* publish (a hardcoded port it keeps, or one inside a range). Returns the
|
|
65
|
+
* targets actually remapped and a warning for each port left as it is.
|
|
66
|
+
*/
|
|
67
|
+
export function stackAllocations(ctx, index, targets) {
|
|
68
|
+
if (!targets) {
|
|
69
|
+
return { allocations: allocateWorktreePorts(ctx.portMappings, index, ctx.portStride), targets: null, warnings: [] };
|
|
70
|
+
}
|
|
71
|
+
const allocations = allocateWorktreePorts(ctx.portMappings, index, ctx.portStride, targets.ports);
|
|
72
|
+
const stays = new Map();
|
|
73
|
+
// A port that stays is one the stack keeps, which can block another
|
|
74
|
+
// port's move in turn: repeat until nothing more has to stay.
|
|
75
|
+
for (let moving = targets.ports, changed = true; changed; moving = moving.filter((m) => !stays.has(m.defaultPort))) {
|
|
76
|
+
changed = false;
|
|
77
|
+
const kept = keptHostPorts(ctx.portMappings, moving);
|
|
78
|
+
for (const m of moving) {
|
|
79
|
+
if (stays.has(m.defaultPort))
|
|
80
|
+
continue;
|
|
81
|
+
const a = allocations.find((x) => x.defaultPort === m.defaultPort);
|
|
82
|
+
if (!a) {
|
|
83
|
+
stays.set(m.defaultPort, `Service "${m.serviceName}": hardcoded host port ${m.defaultPort} has no free port to move to in worktree ${index} (ports end at 65535), so it stays ${m.defaultPort}.`);
|
|
84
|
+
changed = true;
|
|
85
|
+
}
|
|
86
|
+
else if (kept.some(([from, to]) => a.port >= from && a.port <= to)) {
|
|
87
|
+
// Also when the port is a variable's (same default port, e.g. tcp
|
|
88
|
+
// and udp): the hardcoded entry would publish it a second time.
|
|
89
|
+
stays.set(m.defaultPort, `Service "${m.serviceName}": hardcoded host port ${m.defaultPort} would move to ${a.port}, which this stack already publishes, so it stays ${m.defaultPort}.`);
|
|
90
|
+
changed = true;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
if (stays.size === 0)
|
|
95
|
+
return { allocations, targets, warnings: [] };
|
|
96
|
+
const remaining = { ...targets, ports: targets.ports.filter((m) => !stays.has(m.defaultPort)) };
|
|
97
|
+
return {
|
|
98
|
+
allocations: allocations.filter((a) => a.envVar !== null || !stays.has(a.defaultPort)),
|
|
99
|
+
targets: remapIsEmpty(remaining) ? null : remaining,
|
|
100
|
+
warnings: [...stays.values()],
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Ports and compose files for one stack: the `COMPOSE_FILE` list compose
|
|
105
|
+
* would otherwise pick by itself — the compose file, the directory's own
|
|
106
|
+
* compose override if any — followed by wtc's override (see
|
|
107
|
+
* compose/override.ts), or null without one.
|
|
108
|
+
*
|
|
109
|
+
* `start` (`write`) writes the override, after syncing the worktree's
|
|
110
|
+
* compose file from main. `stop` and teardown use the override the stack
|
|
111
|
+
* was started with as it is: rewriting it from main's current compose file
|
|
112
|
+
* could name services the worktree's (older) compose file does not have,
|
|
113
|
+
* which the `COMPOSE_FILE` in the worktree's env file also loads.
|
|
114
|
+
*/
|
|
115
|
+
export function prepareStack(ctx, target, opts) {
|
|
116
|
+
const file = overridePath(ctx.repo.commonDir, target.project);
|
|
117
|
+
const filesWith = (override) => {
|
|
118
|
+
const userOverride = findUserOverride(target.dir);
|
|
119
|
+
return composeFileValue([
|
|
120
|
+
path.join(target.dir, path.basename(ctx.composeFile.composePath)),
|
|
121
|
+
...(userOverride ? [userOverride] : []),
|
|
122
|
+
override,
|
|
123
|
+
]);
|
|
124
|
+
};
|
|
125
|
+
const remap = stackRemap(ctx, target.dir, target.project);
|
|
126
|
+
const stack = stackAllocations(ctx, target.index, remap.targets);
|
|
127
|
+
const warnings = [...remap.warnings, ...stack.warnings];
|
|
128
|
+
if (!opts.write && fs.existsSync(file)) {
|
|
129
|
+
const composeFile = filesWith(file);
|
|
130
|
+
if (composeFile !== null)
|
|
131
|
+
return { allocations: stack.allocations, composeFile, warnings: [] };
|
|
132
|
+
}
|
|
133
|
+
if (!stack.targets)
|
|
134
|
+
return { allocations: stack.allocations, composeFile: null, warnings };
|
|
135
|
+
const composeFile = filesWith(file);
|
|
136
|
+
if (composeFile === null) {
|
|
137
|
+
return {
|
|
138
|
+
allocations: allocateWorktreePorts(ctx.portMappings, target.index, ctx.portStride),
|
|
139
|
+
composeFile: null,
|
|
140
|
+
warnings: [
|
|
141
|
+
...warnings,
|
|
142
|
+
`A path of ${target.project}'s compose files contains the COMPOSE_FILE separator, so wtc does not remap hardcoded ports or container_name for it.`,
|
|
143
|
+
],
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
// `stop`/teardown of a stack started before wtc remapped (or whose file
|
|
147
|
+
// was deleted) recreate it.
|
|
148
|
+
if (opts.write || !fs.existsSync(file)) {
|
|
149
|
+
writeOverride(file, renderOverride(target.project, ctx.composeFile, stack.targets, stack.allocations));
|
|
150
|
+
}
|
|
151
|
+
return { allocations: stack.allocations, composeFile, warnings };
|
|
152
|
+
}
|
|
153
|
+
/** Run `<compose> -p <project> <args…>` without blocking the event loop. */
|
|
154
|
+
export function composeRun(engine, project, args, opts) {
|
|
155
|
+
const env = { ...process.env, ...opts.env };
|
|
156
|
+
for (const key of Object.keys(env)) {
|
|
157
|
+
if (env[key] === undefined)
|
|
158
|
+
delete env[key];
|
|
159
|
+
}
|
|
160
|
+
return runAsync(composeBin(engine), composeArgs(engine, project, ...args), {
|
|
161
|
+
cwd: opts.cwd,
|
|
162
|
+
env,
|
|
163
|
+
live: opts.live,
|
|
164
|
+
signal: opts.signal,
|
|
165
|
+
onLine: opts.onLine,
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
/** Prefix an error with what was being done, keeping CommandError details. */
|
|
169
|
+
export function withContext(prefix, err) {
|
|
170
|
+
if (err instanceof CommandError) {
|
|
171
|
+
err.message = `${prefix}: ${err.message}`;
|
|
172
|
+
return err;
|
|
173
|
+
}
|
|
174
|
+
return new Error(`${prefix}: ${err instanceof Error ? err.message : String(err)}`);
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Report a context's general warnings (and, when asked, its isolation
|
|
178
|
+
* warnings plus what runtime remapping does).
|
|
179
|
+
*/
|
|
180
|
+
export function reportContextWarnings(ctx, reporter, opts) {
|
|
181
|
+
for (const w of ctx.warnings)
|
|
182
|
+
reporter.warn(w);
|
|
183
|
+
if (opts.isolation) {
|
|
184
|
+
for (const w of ctx.isolationWarnings)
|
|
185
|
+
reporter.warn(w);
|
|
186
|
+
for (const n of ctx.remapNotes)
|
|
187
|
+
reporter.info(n);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
/** Throw if the operation was cancelled (checked between worktrees). */
|
|
191
|
+
export function throwIfAborted(io) {
|
|
192
|
+
if (io.signal?.aborted)
|
|
193
|
+
throw new Error("Cancelled.");
|
|
194
|
+
}
|
|
195
|
+
export const NO_WORKTREES_HINT = "No extra worktrees found. Create one with:\n git worktree add ../my-branch my-branch";
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { CoreIo } from "./types.js";
|
|
2
|
+
export type CheckStatus = "ok" | "warn" | "fail";
|
|
3
|
+
export interface DoctorCheck {
|
|
4
|
+
status: CheckStatus;
|
|
5
|
+
title: string;
|
|
6
|
+
detail?: string;
|
|
7
|
+
hint?: string;
|
|
8
|
+
}
|
|
9
|
+
export interface DoctorResult {
|
|
10
|
+
/** False when any check failed. */
|
|
11
|
+
ok: boolean;
|
|
12
|
+
checks: DoctorCheck[];
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* True when something already listens on `port`. Docker publishes on all
|
|
16
|
+
* interfaces, but local dev servers and Homebrew databases usually bind
|
|
17
|
+
* 127.0.0.1 or ::1 only — and on macOS (BSD sockets, libuv's SO_REUSEADDR)
|
|
18
|
+
* a wildcard bind succeeds next to them, so each address is probed. Only
|
|
19
|
+
* EADDRINUSE counts as busy (no IPv6 → not busy).
|
|
20
|
+
*/
|
|
21
|
+
export declare function isPortBusy(port: number): Promise<boolean>;
|
|
22
|
+
/**
|
|
23
|
+
* Diagnose the setup: git, repo layout, compose file, config, compose
|
|
24
|
+
* engine and daemon, port isolation (including what is remapped at
|
|
25
|
+
* runtime), isolation-breaking compose settings, worktree/registry health,
|
|
26
|
+
* and host ports already taken for stopped stacks. Each check is
|
|
27
|
+
* independent so one failure never hides the others.
|
|
28
|
+
*/
|
|
29
|
+
export declare function doctor(io: CoreIo): Promise<DoctorResult>;
|