worktree-compose 0.2.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +458 -140
- 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 +15 -0
- package/dist/compose/isolation.js +62 -0
- package/dist/compose/parse.d.ts +5 -0
- package/dist/compose/parse.js +89 -11
- package/dist/compose/status.d.ts +84 -0
- package/dist/compose/status.js +227 -0
- package/dist/compose/types.d.ts +20 -0
- package/dist/config.d.ts +31 -0
- package/dist/config.js +23 -6
- package/dist/context.d.ts +89 -3
- package/dist/context.js +278 -45
- package/dist/core/clean.d.ts +91 -0
- package/dist/core/clean.js +343 -0
- package/dist/core/compose.d.ts +30 -0
- package/dist/core/compose.js +45 -0
- package/dist/core/doctor.d.ts +28 -0
- package/dist/core/doctor.js +277 -0
- package/dist/core/list.d.ts +42 -0
- package/dist/core/list.js +94 -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 +75 -0
- package/dist/core/restart.d.ts +14 -0
- package/dist/core/restart.js +18 -0
- package/dist/core/start.d.ts +31 -0
- package/dist/core/start.js +99 -0
- package/dist/core/stop.d.ts +32 -0
- package/dist/core/stop.js +57 -0
- package/dist/core/teardown.d.ts +121 -0
- package/dist/core/teardown.js +298 -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 +14 -3
- package/dist/ports/allocate.js +20 -4
- 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 +77 -2
- package/dist/sync/env.js +151 -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 +18 -14
- package/wtc.schema.json +62 -0
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { StartOptions, StartResult } from "./start.js";
|
|
2
|
+
import type { Reporter } from "../utils/log.js";
|
|
3
|
+
import type { CoreIo } from "./types.js";
|
|
4
|
+
/**
|
|
5
|
+
* Stop then start (`compose stop`, then start's sync/inject + `up -d
|
|
6
|
+
* --remove-orphans`): unchanged services are simply started again, changed
|
|
7
|
+
* ones are recreated by compose — which carries their anonymous volumes
|
|
8
|
+
* over, unlike the old `down` + `up`, which brought image-declared volumes
|
|
9
|
+
* back empty — and containers of services removed from the compose file
|
|
10
|
+
* go away, as `down` used to make them. Env options and selectors are
|
|
11
|
+
* validated while every worktree is still running, so a typo never leaves
|
|
12
|
+
* stacks stopped.
|
|
13
|
+
*/
|
|
14
|
+
export declare function restartWorktrees(options: StartOptions, reporter: Reporter, io: CoreIo): Promise<StartResult>;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { preflightEnvOptions } from "../context.js";
|
|
2
|
+
import { startWorktrees } from "./start.js";
|
|
3
|
+
import { stopWorktrees } from "./stop.js";
|
|
4
|
+
/**
|
|
5
|
+
* Stop then start (`compose stop`, then start's sync/inject + `up -d
|
|
6
|
+
* --remove-orphans`): unchanged services are simply started again, changed
|
|
7
|
+
* ones are recreated by compose — which carries their anonymous volumes
|
|
8
|
+
* over, unlike the old `down` + `up`, which brought image-declared volumes
|
|
9
|
+
* back empty — and containers of services removed from the compose file
|
|
10
|
+
* go away, as `down` used to make them. Env options and selectors are
|
|
11
|
+
* validated while every worktree is still running, so a typo never leaves
|
|
12
|
+
* stacks stopped.
|
|
13
|
+
*/
|
|
14
|
+
export async function restartWorktrees(options, reporter, io) {
|
|
15
|
+
preflightEnvOptions(options, io.cwd, { requireMainFor: "restart worktree stacks" });
|
|
16
|
+
await stopWorktrees({ worktrees: options.worktrees, quiet: true }, reporter, io);
|
|
17
|
+
return startWorktrees({ ...options, removeOrphans: true }, reporter, io);
|
|
18
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { EnvCliOptions } from "../context.js";
|
|
2
|
+
import type { WorktreeSelector } from "../selectors.js";
|
|
3
|
+
import type { Reporter } from "../utils/log.js";
|
|
4
|
+
import type { CoreIo } from "./types.js";
|
|
5
|
+
export interface StartOptions extends EnvCliOptions {
|
|
6
|
+
/** Worktrees to start (index, branch, dir name, path, "."); empty = all. */
|
|
7
|
+
worktrees?: WorktreeSelector[];
|
|
8
|
+
/** Pass `--build` to `compose up` (default true). */
|
|
9
|
+
build?: boolean;
|
|
10
|
+
/**
|
|
11
|
+
* Pass `--remove-orphans` to `compose up` (restart): containers of
|
|
12
|
+
* services the compose file no longer declares would otherwise keep
|
|
13
|
+
* running — and holding their ports — after the restart.
|
|
14
|
+
*/
|
|
15
|
+
removeOrphans?: boolean;
|
|
16
|
+
}
|
|
17
|
+
export interface StartedWorktree {
|
|
18
|
+
index: number;
|
|
19
|
+
branch: string;
|
|
20
|
+
path: string;
|
|
21
|
+
project: string;
|
|
22
|
+
ports: Record<string, number>;
|
|
23
|
+
}
|
|
24
|
+
export interface StartResult {
|
|
25
|
+
started: StartedWorktree[];
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Sync infra files, inject ports + project name into env files, and run
|
|
29
|
+
* `compose up -d` for each selected worktree. Stops at the first failure.
|
|
30
|
+
*/
|
|
31
|
+
export declare function startWorktrees(options: StartOptions, reporter: Reporter, io: CoreIo): Promise<StartResult>;
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { buildContext, getEnvTargets } from "../context.js";
|
|
4
|
+
import { samePath } from "../git/worktree.js";
|
|
5
|
+
import { recordEnvFiles } from "../state/registry.js";
|
|
6
|
+
import { allocateWorktreePorts } from "../ports/allocate.js";
|
|
7
|
+
import { syncWorktreeFiles } from "../sync/files.js";
|
|
8
|
+
import { findEnvSource, injectPortOverrides, prepareEnvFile } from "../sync/env.js";
|
|
9
|
+
import { selectWorktrees } from "../selectors.js";
|
|
10
|
+
import { composeEnv, composeRun, NO_WORKTREES_HINT, reportContextWarnings, throwIfAborted, withContext, } from "./compose.js";
|
|
11
|
+
/**
|
|
12
|
+
* Sync infra files, inject ports + project name into env files, and run
|
|
13
|
+
* `compose up -d` for each selected worktree. Stops at the first failure.
|
|
14
|
+
*/
|
|
15
|
+
export async function startWorktrees(options, reporter, io) {
|
|
16
|
+
const ctx = buildContext(options, { cwd: io.cwd, probeStacks: true, requireMainFor: "start worktree stacks" });
|
|
17
|
+
reportContextWarnings(ctx, reporter, { isolation: true });
|
|
18
|
+
if (ctx.worktrees.length === 0) {
|
|
19
|
+
reporter.warn(NO_WORKTREES_HINT);
|
|
20
|
+
return { started: [] };
|
|
21
|
+
}
|
|
22
|
+
const targets = selectWorktrees(ctx.worktrees, options.worktrees, ctx.cwd);
|
|
23
|
+
const envTargets = getEnvTargets(ctx);
|
|
24
|
+
const engine = ctx.getEngine();
|
|
25
|
+
const build = options.build !== false;
|
|
26
|
+
const started = [];
|
|
27
|
+
for (const wt of targets) {
|
|
28
|
+
throwIfAborted(io);
|
|
29
|
+
// Never treat the env/config source as a worktree, and never recreate a
|
|
30
|
+
// missing checkout just to run compose in it.
|
|
31
|
+
if (samePath(wt.path, ctx.repoRoot)) {
|
|
32
|
+
throw new Error(`Worktree ${wt.index} (${wt.branch}) is the main checkout (${ctx.repoRoot}); wtc does not start it as a worktree.`);
|
|
33
|
+
}
|
|
34
|
+
if (!fs.existsSync(path.join(wt.path, ".git"))) {
|
|
35
|
+
throw new Error(`Worktree ${wt.index} (${wt.branch}) is missing on disk (${wt.path}). Remount it, or run 'git worktree prune' and 'wtc prune'.`);
|
|
36
|
+
}
|
|
37
|
+
const allocations = allocateWorktreePorts(ctx.portMappings, wt.index, ctx.portStride);
|
|
38
|
+
reporter.header(`Worktree ${wt.index}: ${wt.branch}`);
|
|
39
|
+
reporter.info(`Path: ${wt.path}`);
|
|
40
|
+
reporter.info(`Project: ${wt.project}`);
|
|
41
|
+
reporter.info(`Ports: ${allocations.map((a) => `${a.envVar}=${a.port}`).join(" ") || "(none)"}`);
|
|
42
|
+
const syncWarnings = syncWorktreeFiles(ctx.repoRoot, wt.path, ctx.composeFile, ctx.config.sync);
|
|
43
|
+
// Skipped sync entries were already reported with the context warnings.
|
|
44
|
+
for (const w of syncWarnings)
|
|
45
|
+
if (!ctx.warnings.includes(w))
|
|
46
|
+
reporter.warn(w);
|
|
47
|
+
reporter.success("Synced infrastructure files");
|
|
48
|
+
const injected = [];
|
|
49
|
+
for (const target of envTargets) {
|
|
50
|
+
const envWarnings = [];
|
|
51
|
+
const envPath = prepareEnvFile(ctx.repoRoot, wt.path, target, envWarnings);
|
|
52
|
+
for (const w of envWarnings)
|
|
53
|
+
reporter.warn(w);
|
|
54
|
+
if (!envPath) {
|
|
55
|
+
if (envWarnings.length === 0) {
|
|
56
|
+
reporter.warn(`No ${target.envFileName} (or .env.example) found for ${target.label}; skipped`);
|
|
57
|
+
}
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
const injection = injectPortOverrides(envPath, allocations, target.overrides, {
|
|
61
|
+
projectName: wt.project,
|
|
62
|
+
writeProjectName: target.dir === "",
|
|
63
|
+
root: wt.path,
|
|
64
|
+
source: findEnvSource(ctx.repoRoot, target) ?? undefined,
|
|
65
|
+
});
|
|
66
|
+
for (const w of injection.warnings)
|
|
67
|
+
reporter.warn(w);
|
|
68
|
+
injected.push(path.relative(wt.path, envPath));
|
|
69
|
+
}
|
|
70
|
+
if (injected.length > 0) {
|
|
71
|
+
reporter.success(`Injected port overrides into ${injected.join(", ")}`);
|
|
72
|
+
}
|
|
73
|
+
// Remember exactly which env files wtc wrote (before compose runs: they
|
|
74
|
+
// are written even if `up` fails), so clean treats only those as wtc's
|
|
75
|
+
// own changes.
|
|
76
|
+
recordEnvFiles(ctx.repo.commonDir, wt.path, injected);
|
|
77
|
+
try {
|
|
78
|
+
await composeRun(engine, wt.project, ["up", "-d", ...(build ? ["--build"] : []), ...(options.removeOrphans ? ["--remove-orphans"] : [])], {
|
|
79
|
+
cwd: wt.path,
|
|
80
|
+
env: composeEnv(wt.project, allocations),
|
|
81
|
+
live: io.live,
|
|
82
|
+
signal: io.signal,
|
|
83
|
+
onLine: io.onOutput,
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
catch (err) {
|
|
87
|
+
throw withContext(`Failed to start worktree ${wt.index} (${wt.branch})`, err);
|
|
88
|
+
}
|
|
89
|
+
reporter.success(`Worktree ${wt.index} started`);
|
|
90
|
+
started.push({
|
|
91
|
+
index: wt.index,
|
|
92
|
+
branch: wt.branch,
|
|
93
|
+
path: wt.path,
|
|
94
|
+
project: wt.project,
|
|
95
|
+
ports: Object.fromEntries(allocations.map((a) => [a.envVar, a.port])),
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
return { started };
|
|
99
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { WorktreeSelector } from "../selectors.js";
|
|
2
|
+
import type { Reporter } from "../utils/log.js";
|
|
3
|
+
import type { CoreIo } from "./types.js";
|
|
4
|
+
export interface StopOptions {
|
|
5
|
+
/** Worktrees to stop (index, branch, dir name, path, "."); empty = all. */
|
|
6
|
+
worktrees?: WorktreeSelector[];
|
|
7
|
+
/** Skip context warnings (restart reports them once, from start). */
|
|
8
|
+
quiet?: boolean;
|
|
9
|
+
}
|
|
10
|
+
export interface StopResult {
|
|
11
|
+
stopped: {
|
|
12
|
+
index: number;
|
|
13
|
+
branch: string;
|
|
14
|
+
project: string;
|
|
15
|
+
}[];
|
|
16
|
+
failed: {
|
|
17
|
+
index: number;
|
|
18
|
+
branch: string;
|
|
19
|
+
project: string;
|
|
20
|
+
error: string;
|
|
21
|
+
}[];
|
|
22
|
+
/** Stacks that could not be stopped (non-zero → exit 1 / MCP isError). */
|
|
23
|
+
failures: number;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* `compose stop` for each selected worktree; one failure does not stop the
|
|
27
|
+
* rest. Containers are stopped, not removed: data in volumes declared only
|
|
28
|
+
* by an image (postgres, redis… without a named volume) lives in anonymous
|
|
29
|
+
* volumes that a `down` + `up` would replace with empty ones. `wtc start`
|
|
30
|
+
* resumes the same containers; `clean`/`prune` remove everything.
|
|
31
|
+
*/
|
|
32
|
+
export declare function stopWorktrees(options: StopOptions, reporter: Reporter, io: CoreIo): Promise<StopResult>;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { buildContext } from "../context.js";
|
|
2
|
+
import { allocateWorktreePorts } from "../ports/allocate.js";
|
|
3
|
+
import { selectWorktrees } from "../selectors.js";
|
|
4
|
+
import { composeEnv, composeRun, reportContextWarnings, throwIfAborted } from "./compose.js";
|
|
5
|
+
/**
|
|
6
|
+
* `compose stop` for each selected worktree; one failure does not stop the
|
|
7
|
+
* rest. Containers are stopped, not removed: data in volumes declared only
|
|
8
|
+
* by an image (postgres, redis… without a named volume) lives in anonymous
|
|
9
|
+
* volumes that a `down` + `up` would replace with empty ones. `wtc start`
|
|
10
|
+
* resumes the same containers; `clean`/`prune` remove everything.
|
|
11
|
+
*/
|
|
12
|
+
export async function stopWorktrees(options, reporter, io) {
|
|
13
|
+
// Probe like start and list: with a lost or corrupt registry, worktrees
|
|
14
|
+
// then adopt their running stacks' identities instead of positional
|
|
15
|
+
// names that never existed (`compose stop` on those is a silent no-op).
|
|
16
|
+
// The probe runs `ps` only when some worktree has no record.
|
|
17
|
+
const ctx = buildContext({}, { cwd: io.cwd, probeStacks: true });
|
|
18
|
+
if (!options.quiet)
|
|
19
|
+
reportContextWarnings(ctx, reporter, { isolation: false });
|
|
20
|
+
const result = { stopped: [], failed: [], failures: 0 };
|
|
21
|
+
if (ctx.worktrees.length === 0) {
|
|
22
|
+
reporter.warn("No worktrees to stop.");
|
|
23
|
+
return result;
|
|
24
|
+
}
|
|
25
|
+
const targets = selectWorktrees(ctx.worktrees, options.worktrees, ctx.cwd);
|
|
26
|
+
const engine = ctx.getEngine();
|
|
27
|
+
for (const wt of targets) {
|
|
28
|
+
throwIfAborted(io);
|
|
29
|
+
reporter.info(`Stopping ${wt.project}...`);
|
|
30
|
+
const entry = { index: wt.index, branch: wt.branch, project: wt.project };
|
|
31
|
+
let env;
|
|
32
|
+
try {
|
|
33
|
+
env = composeEnv(wt.project, allocateWorktreePorts(ctx.portMappings, wt.index, ctx.portStride));
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
env = undefined;
|
|
37
|
+
}
|
|
38
|
+
try {
|
|
39
|
+
await composeRun(engine, wt.project, ["stop"], {
|
|
40
|
+
cwd: wt.path,
|
|
41
|
+
env,
|
|
42
|
+
live: io.live,
|
|
43
|
+
signal: io.signal,
|
|
44
|
+
onLine: io.onOutput,
|
|
45
|
+
});
|
|
46
|
+
reporter.success(`Stopped worktree ${wt.index} (${wt.branch})`);
|
|
47
|
+
result.stopped.push(entry);
|
|
48
|
+
}
|
|
49
|
+
catch (err) {
|
|
50
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
51
|
+
reporter.warn(`Could not stop ${wt.project}: ${message}`);
|
|
52
|
+
result.failed.push({ ...entry, error: message });
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
result.failures = result.failed.length;
|
|
56
|
+
return result;
|
|
57
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import type { ComposeEngine } from "../compose/engine.js";
|
|
2
|
+
import type { Reporter } from "../utils/log.js";
|
|
3
|
+
import type { WtcContext } from "../context.js";
|
|
4
|
+
import type { WorktreeRecord } from "../state/registry.js";
|
|
5
|
+
import type { CoreIo } from "./types.js";
|
|
6
|
+
export interface TeardownTarget {
|
|
7
|
+
project: string;
|
|
8
|
+
index: number;
|
|
9
|
+
/** Worktree directory (may no longer exist for orphans). */
|
|
10
|
+
path: string;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Anonymous volumes (image-declared `VOLUME`s with no named volume in the
|
|
14
|
+
* compose file) mounted by a project's containers. A container recreated
|
|
15
|
+
* by `up` carries its anonymous volume over, and such a carried-over volume
|
|
16
|
+
* survives `down -v`; collecting them first lets teardown remove them too.
|
|
17
|
+
* Best effort: any failure yields an empty list.
|
|
18
|
+
*/
|
|
19
|
+
export declare function anonymousVolumes(engine: ComposeEngine, project: string): string[];
|
|
20
|
+
/**
|
|
21
|
+
* `compose -p P down -v --remove-orphans`. Runs from the worktree when it
|
|
22
|
+
* still exists (so declared volumes/networks are resolved from its compose
|
|
23
|
+
* file), otherwise from the main checkout. Fallbacks, in order:
|
|
24
|
+
* - plain `down -v` from the same directory (podman-compose < 1.0.6 rejects
|
|
25
|
+
* `--remove-orphans`, which would make every teardown fail);
|
|
26
|
+
* - for the Compose v2 plugin only, `down -v --remove-orphans` from an
|
|
27
|
+
* empty directory: it tears a project down by its labels alone when the
|
|
28
|
+
* compose file no longer parses. Standalone docker-compose v1 and
|
|
29
|
+
* podman-compose always need a compose file, so that retry cannot help.
|
|
30
|
+
* Anonymous volumes the containers mounted are removed afterwards.
|
|
31
|
+
*/
|
|
32
|
+
export declare function teardownStack(ctx: WtcContext, engine: ComposeEngine, target: TeardownTarget, io: CoreIo): Promise<{
|
|
33
|
+
ok: boolean;
|
|
34
|
+
error?: string;
|
|
35
|
+
}>;
|
|
36
|
+
/**
|
|
37
|
+
* Re-check an orphan right before tearing it down, with a fresh `git
|
|
38
|
+
* worktree list`: another wtc process (or `git worktree repair` / a moved
|
|
39
|
+
* directory coming back) may have made its worktree live again since the
|
|
40
|
+
* context was built, and `down -v` would then destroy a live stack's data.
|
|
41
|
+
* Same identity rules as reconcile: a record is live when a worktree holds
|
|
42
|
+
* its id, or sits at its path without a conflicting id (a new worktree at a
|
|
43
|
+
* reused path is not the old one, so the orphan can still be pruned).
|
|
44
|
+
* Returns null when the orphan is still gone, else why it must be skipped.
|
|
45
|
+
*/
|
|
46
|
+
export declare function orphanSkipReason(ctx: WtcContext, record: WorktreeRecord): string | null;
|
|
47
|
+
/** Runs a container CLI command; throws on failure. Injectable for tests. */
|
|
48
|
+
export type SweepRunner = (file: string, args: string[]) => string;
|
|
49
|
+
export interface SweepBucket {
|
|
50
|
+
removed: string[];
|
|
51
|
+
failed: string[];
|
|
52
|
+
}
|
|
53
|
+
export interface SweepResult {
|
|
54
|
+
/** Removed (or, in a dry run, to be removed) resources, and failed removals. */
|
|
55
|
+
containers: SweepBucket;
|
|
56
|
+
networks: SweepBucket;
|
|
57
|
+
volumes: SweepBucket;
|
|
58
|
+
/**
|
|
59
|
+
* Resources of `<repo>-wt-<n>-` stacks whose working directory no longer
|
|
60
|
+
* exists (typically left by wtc ≤0.2). Removed only with `sweep`; kept
|
|
61
|
+
* and listed otherwise.
|
|
62
|
+
*/
|
|
63
|
+
stale: string[];
|
|
64
|
+
/**
|
|
65
|
+
* Resources named like this repo's worktree stacks that this checkout
|
|
66
|
+
* cannot prove it owns: another checkout's stack (same directory name),
|
|
67
|
+
* or nothing left to attribute them by (no labels, no containers). Never
|
|
68
|
+
* removed.
|
|
69
|
+
*/
|
|
70
|
+
notOwned: string[];
|
|
71
|
+
/** Set when a listing failed (engine unreachable). */
|
|
72
|
+
error?: string;
|
|
73
|
+
}
|
|
74
|
+
export interface SweepOptions {
|
|
75
|
+
dryRun?: boolean;
|
|
76
|
+
runner?: SweepRunner;
|
|
77
|
+
reporter?: Reporter;
|
|
78
|
+
/** Projects of this repository's registry records (live and orphaned): owned outright. */
|
|
79
|
+
registryProjects?: string[];
|
|
80
|
+
/**
|
|
81
|
+
* Projects to leave alone this run: in a dry run those step 1 would tear
|
|
82
|
+
* down (`down -v` removes them first), and orphans whose worktree came
|
|
83
|
+
* back while cleaning.
|
|
84
|
+
*/
|
|
85
|
+
skipProjects?: string[];
|
|
86
|
+
/** The main checkout: a stack that ran from it (or below it) is this repository's. */
|
|
87
|
+
mainRoot?: string;
|
|
88
|
+
/**
|
|
89
|
+
* Current worktree paths plus every registry path: a stack whose
|
|
90
|
+
* `working_dir` is exactly one of them is this repository's.
|
|
91
|
+
*/
|
|
92
|
+
checkouts?: string[];
|
|
93
|
+
/**
|
|
94
|
+
* `clean --sweep`: also remove `<repo>-wt-<n>-` stacks whose working
|
|
95
|
+
* directory no longer exists on disk (stale ≤0.2 leftovers). A stack
|
|
96
|
+
* whose directory exists is never removed this way — it may be another
|
|
97
|
+
* checkout's.
|
|
98
|
+
*/
|
|
99
|
+
sweep?: boolean;
|
|
100
|
+
/** Whether a directory exists (tests). */
|
|
101
|
+
dirExists?: (dir: string) => boolean;
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Remove leftover containers, networks and volumes of this repository's
|
|
105
|
+
* worktree stacks — never another checkout's.
|
|
106
|
+
*
|
|
107
|
+
* A name like `<repo>-wt-<n>-…` proves nothing: the prefix is the checkout
|
|
108
|
+
* directory's basename, which a second clone (or an unrelated repo also
|
|
109
|
+
* called `api`) shares. Ownership comes from compose's labels instead. A
|
|
110
|
+
* project is *owned* when it is in this repository's registry, or when it
|
|
111
|
+
* is a `<repo>-wt-<n>-` project one of whose containers ran
|
|
112
|
+
* (`project.working_dir`) from the main checkout (or below it), a current
|
|
113
|
+
* worktree, or a registry path. Only resources whose project label is owned
|
|
114
|
+
* are removed, one at a time (a volume still in use cannot discard the rest).
|
|
115
|
+
*
|
|
116
|
+
* Name-matching projects that are not owned are kept and listed, in two
|
|
117
|
+
* groups: *stale* ones, whose working directory no longer exists (removed
|
|
118
|
+
* with `sweep`), and the rest — whose directory exists (another checkout),
|
|
119
|
+
* or which have nothing to attribute them by — which are never removed.
|
|
120
|
+
*/
|
|
121
|
+
export declare function sweepStaleResources(cliArgv: string[], repoName: string, opts?: SweepOptions): SweepResult;
|
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { ENGINE_PROBE_TIMEOUT_MS, run, runSafe } from "../utils/exec.js";
|
|
5
|
+
import { isWithin } from "../utils/paths.js";
|
|
6
|
+
import { sanitize, worktreeResourcePattern } from "../utils/sanitize.js";
|
|
7
|
+
import { allocateWorktreePorts } from "../ports/allocate.js";
|
|
8
|
+
import { cliCall, isComposePlugin } from "../compose/engine.js";
|
|
9
|
+
import { field, labelsOf, parseJsonListing, parsePsContainers, PROJECT_LABELS, } from "../compose/status.js";
|
|
10
|
+
import { samePath } from "../git/worktree.js";
|
|
11
|
+
import { listRepoWorktrees } from "../git/repo.js";
|
|
12
|
+
import { recordIsLive } from "../state/registry.js";
|
|
13
|
+
import { composeEnv, composeRun } from "./compose.js";
|
|
14
|
+
/** Anonymous volumes are named by a 64-hex id; named volumes never are. */
|
|
15
|
+
const ANONYMOUS_VOLUME = /^[0-9a-f]{64}$/;
|
|
16
|
+
/**
|
|
17
|
+
* Anonymous volumes (image-declared `VOLUME`s with no named volume in the
|
|
18
|
+
* compose file) mounted by a project's containers. A container recreated
|
|
19
|
+
* by `up` carries its anonymous volume over, and such a carried-over volume
|
|
20
|
+
* survives `down -v`; collecting them first lets teardown remove them too.
|
|
21
|
+
* Best effort: any failure yields an empty list.
|
|
22
|
+
*/
|
|
23
|
+
export function anonymousVolumes(engine, project) {
|
|
24
|
+
const opts = { timeoutMs: ENGINE_PROBE_TIMEOUT_MS };
|
|
25
|
+
const [psFile, psArgs] = cliCall(engine, "ps", "-a", "-q", "--filter", `label=com.docker.compose.project=${project}`);
|
|
26
|
+
const ids = (runSafe(psFile, psArgs, opts) ?? "")
|
|
27
|
+
.split("\n")
|
|
28
|
+
.map((l) => l.trim())
|
|
29
|
+
.filter((id) => /^[0-9a-f]{6,64}$/i.test(id));
|
|
30
|
+
if (ids.length === 0)
|
|
31
|
+
return [];
|
|
32
|
+
const [inspectFile, inspectArgs] = cliCall(engine, "inspect", "--format", "{{json .Mounts}}", ...ids);
|
|
33
|
+
const names = new Set();
|
|
34
|
+
for (const line of (runSafe(inspectFile, inspectArgs, opts) ?? "").split("\n")) {
|
|
35
|
+
try {
|
|
36
|
+
const mounts = JSON.parse(line);
|
|
37
|
+
if (!Array.isArray(mounts))
|
|
38
|
+
continue;
|
|
39
|
+
for (const m of mounts) {
|
|
40
|
+
const mount = m;
|
|
41
|
+
const name = String(field(mount, "Name") ?? "");
|
|
42
|
+
if (String(field(mount, "Type") ?? "") === "volume" && ANONYMOUS_VOLUME.test(name)) {
|
|
43
|
+
names.add(name);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
// Not JSON (empty line, unexpected output): ignore.
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return [...names];
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* `compose -p P down -v --remove-orphans`. Runs from the worktree when it
|
|
55
|
+
* still exists (so declared volumes/networks are resolved from its compose
|
|
56
|
+
* file), otherwise from the main checkout. Fallbacks, in order:
|
|
57
|
+
* - plain `down -v` from the same directory (podman-compose < 1.0.6 rejects
|
|
58
|
+
* `--remove-orphans`, which would make every teardown fail);
|
|
59
|
+
* - for the Compose v2 plugin only, `down -v --remove-orphans` from an
|
|
60
|
+
* empty directory: it tears a project down by its labels alone when the
|
|
61
|
+
* compose file no longer parses. Standalone docker-compose v1 and
|
|
62
|
+
* podman-compose always need a compose file, so that retry cannot help.
|
|
63
|
+
* Anonymous volumes the containers mounted are removed afterwards.
|
|
64
|
+
*/
|
|
65
|
+
export async function teardownStack(ctx, engine, target, io) {
|
|
66
|
+
let env;
|
|
67
|
+
try {
|
|
68
|
+
env = composeEnv(target.project, allocateWorktreePorts(ctx.portMappings, target.index, ctx.portStride));
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
env = undefined;
|
|
72
|
+
}
|
|
73
|
+
const cwd = fs.existsSync(target.path) ? target.path : ctx.repoRoot;
|
|
74
|
+
const anonymous = anonymousVolumes(engine, target.project);
|
|
75
|
+
const call = { env, live: io.live, signal: io.signal, onLine: io.onOutput };
|
|
76
|
+
const attempts = [
|
|
77
|
+
{ args: ["down", "-v", "--remove-orphans"], dir: () => cwd },
|
|
78
|
+
{ args: ["down", "-v"], dir: () => cwd },
|
|
79
|
+
];
|
|
80
|
+
if (isComposePlugin(engine)) {
|
|
81
|
+
attempts.push({
|
|
82
|
+
args: ["down", "-v", "--remove-orphans"],
|
|
83
|
+
dir: () => fs.mkdtempSync(path.join(os.tmpdir(), "wtc-down-")),
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
let firstError = null;
|
|
87
|
+
for (const attempt of attempts) {
|
|
88
|
+
if (io.signal?.aborted)
|
|
89
|
+
break;
|
|
90
|
+
const dir = attempt.dir();
|
|
91
|
+
try {
|
|
92
|
+
await composeRun(engine, target.project, attempt.args, { ...call, cwd: dir });
|
|
93
|
+
for (const volume of anonymous) {
|
|
94
|
+
const [file, args] = cliCall(engine, "volume", "rm", volume);
|
|
95
|
+
runSafe(file, args, { timeoutMs: ENGINE_PROBE_TIMEOUT_MS });
|
|
96
|
+
}
|
|
97
|
+
return { ok: true };
|
|
98
|
+
}
|
|
99
|
+
catch (err) {
|
|
100
|
+
firstError ??= err;
|
|
101
|
+
}
|
|
102
|
+
finally {
|
|
103
|
+
if (dir !== cwd)
|
|
104
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return {
|
|
108
|
+
ok: false,
|
|
109
|
+
error: firstError instanceof Error ? firstError.message : String(firstError ?? "cancelled"),
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Re-check an orphan right before tearing it down, with a fresh `git
|
|
114
|
+
* worktree list`: another wtc process (or `git worktree repair` / a moved
|
|
115
|
+
* directory coming back) may have made its worktree live again since the
|
|
116
|
+
* context was built, and `down -v` would then destroy a live stack's data.
|
|
117
|
+
* Same identity rules as reconcile: a record is live when a worktree holds
|
|
118
|
+
* its id, or sits at its path without a conflicting id (a new worktree at a
|
|
119
|
+
* reused path is not the old one, so the orphan can still be pruned).
|
|
120
|
+
* Returns null when the orphan is still gone, else why it must be skipped.
|
|
121
|
+
*/
|
|
122
|
+
export function orphanSkipReason(ctx, record) {
|
|
123
|
+
let listed;
|
|
124
|
+
try {
|
|
125
|
+
listed = listRepoWorktrees(ctx.repo);
|
|
126
|
+
}
|
|
127
|
+
catch (err) {
|
|
128
|
+
return `could not re-check its worktree (${err instanceof Error ? err.message.split("\n")[0] : String(err)})`;
|
|
129
|
+
}
|
|
130
|
+
return recordIsLive(record, listed) ? `its worktree (${record.path}) exists again; run 'wtc list' to see it` : null;
|
|
131
|
+
}
|
|
132
|
+
const defaultRunner = (file, args) => run(file, args, { timeoutMs: ENGINE_PROBE_TIMEOUT_MS });
|
|
133
|
+
const KINDS = [
|
|
134
|
+
{
|
|
135
|
+
key: "containers",
|
|
136
|
+
label: "container",
|
|
137
|
+
list: ["ps", "-a", "--format", "json"],
|
|
138
|
+
remove: (id) => ["rm", "-f", id],
|
|
139
|
+
},
|
|
140
|
+
{
|
|
141
|
+
key: "networks",
|
|
142
|
+
label: "network",
|
|
143
|
+
list: ["network", "ls", "--format", "json"],
|
|
144
|
+
remove: (id) => ["network", "rm", id],
|
|
145
|
+
},
|
|
146
|
+
{
|
|
147
|
+
key: "volumes",
|
|
148
|
+
label: "volume",
|
|
149
|
+
list: ["volume", "ls", "--format", "json"],
|
|
150
|
+
remove: (id) => ["volume", "rm", id],
|
|
151
|
+
},
|
|
152
|
+
];
|
|
153
|
+
function parseResources(kind, output) {
|
|
154
|
+
if (kind.key === "containers") {
|
|
155
|
+
return parsePsContainers(output).map((c) => ({
|
|
156
|
+
id: c.id || c.name,
|
|
157
|
+
name: c.name,
|
|
158
|
+
project: c.project,
|
|
159
|
+
}));
|
|
160
|
+
}
|
|
161
|
+
return parseJsonListing(output).map((entry) => {
|
|
162
|
+
const labels = labelsOf(entry);
|
|
163
|
+
const name = String(field(entry, "Name") ?? "");
|
|
164
|
+
// Volumes are removed by name; networks by id when there is one.
|
|
165
|
+
const id = kind.key === "networks" ? String(field(entry, "ID") ?? "") || name : name;
|
|
166
|
+
return { id, name, project: PROJECT_LABELS.map((l) => labels[l]).find(Boolean) ?? null };
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Remove leftover containers, networks and volumes of this repository's
|
|
171
|
+
* worktree stacks — never another checkout's.
|
|
172
|
+
*
|
|
173
|
+
* A name like `<repo>-wt-<n>-…` proves nothing: the prefix is the checkout
|
|
174
|
+
* directory's basename, which a second clone (or an unrelated repo also
|
|
175
|
+
* called `api`) shares. Ownership comes from compose's labels instead. A
|
|
176
|
+
* project is *owned* when it is in this repository's registry, or when it
|
|
177
|
+
* is a `<repo>-wt-<n>-` project one of whose containers ran
|
|
178
|
+
* (`project.working_dir`) from the main checkout (or below it), a current
|
|
179
|
+
* worktree, or a registry path. Only resources whose project label is owned
|
|
180
|
+
* are removed, one at a time (a volume still in use cannot discard the rest).
|
|
181
|
+
*
|
|
182
|
+
* Name-matching projects that are not owned are kept and listed, in two
|
|
183
|
+
* groups: *stale* ones, whose working directory no longer exists (removed
|
|
184
|
+
* with `sweep`), and the rest — whose directory exists (another checkout),
|
|
185
|
+
* or which have nothing to attribute them by — which are never removed.
|
|
186
|
+
*/
|
|
187
|
+
export function sweepStaleResources(cliArgv, repoName, opts = {}) {
|
|
188
|
+
const runner = opts.runner ?? defaultRunner;
|
|
189
|
+
const dirExists = opts.dirExists ?? ((dir) => fs.existsSync(dir));
|
|
190
|
+
// An empty prefix (a repo name with no ASCII letters/digits) would match
|
|
191
|
+
// every repository's `wt-<n>-` stacks: no name-based matching at all then.
|
|
192
|
+
const namePattern = sanitize(repoName) ? worktreeResourcePattern(repoName) : null;
|
|
193
|
+
const nameMatches = (name) => !!name && !!namePattern && namePattern.test(name);
|
|
194
|
+
const skip = new Set(opts.skipProjects ?? []);
|
|
195
|
+
const result = {
|
|
196
|
+
containers: { removed: [], failed: [] },
|
|
197
|
+
networks: { removed: [], failed: [] },
|
|
198
|
+
volumes: { removed: [], failed: [] },
|
|
199
|
+
stale: [],
|
|
200
|
+
notOwned: [],
|
|
201
|
+
};
|
|
202
|
+
const listings = new Map();
|
|
203
|
+
const containerDirs = new Map();
|
|
204
|
+
for (const kind of KINDS) {
|
|
205
|
+
try {
|
|
206
|
+
const output = runner(cliArgv[0], [...cliArgv.slice(1), ...kind.list]);
|
|
207
|
+
listings.set(kind.key, parseResources(kind, output));
|
|
208
|
+
if (kind.key === "containers") {
|
|
209
|
+
for (const c of parsePsContainers(output)) {
|
|
210
|
+
if (!c.project || !c.workingDir)
|
|
211
|
+
continue;
|
|
212
|
+
const dirs = containerDirs.get(c.project) ?? new Set();
|
|
213
|
+
dirs.add(c.workingDir);
|
|
214
|
+
containerDirs.set(c.project, dirs);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
catch (err) {
|
|
219
|
+
result.error = err instanceof Error ? err.message : String(err);
|
|
220
|
+
opts.reporter?.warn(`Could not list ${kind.label}s: ${result.error.split("\n")[0]}`);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
// Attribute `<repo>-wt-<n>-` projects by where their containers ran.
|
|
224
|
+
const owned = new Set(opts.registryProjects ?? []);
|
|
225
|
+
const stale = new Set();
|
|
226
|
+
const real = (p) => {
|
|
227
|
+
try {
|
|
228
|
+
return fs.realpathSync.native(p);
|
|
229
|
+
}
|
|
230
|
+
catch {
|
|
231
|
+
return path.resolve(p);
|
|
232
|
+
}
|
|
233
|
+
};
|
|
234
|
+
const mainRoot = opts.mainRoot;
|
|
235
|
+
const ours = (dir) => (mainRoot !== undefined && (isWithin(mainRoot, dir) || isWithin(real(mainRoot), real(dir)))) ||
|
|
236
|
+
(opts.checkouts ?? []).some((c) => samePath(c, dir));
|
|
237
|
+
for (const [project, dirs] of containerDirs) {
|
|
238
|
+
if (owned.has(project) || !nameMatches(project))
|
|
239
|
+
continue;
|
|
240
|
+
if ([...dirs].some(ours))
|
|
241
|
+
owned.add(project);
|
|
242
|
+
else if (![...dirs].some(dirExists))
|
|
243
|
+
stale.add(project);
|
|
244
|
+
}
|
|
245
|
+
const groupOf = (r) => {
|
|
246
|
+
if (r.project !== null && owned.has(r.project))
|
|
247
|
+
return "owned";
|
|
248
|
+
if (!nameMatches(r.name) && !nameMatches(r.project))
|
|
249
|
+
return null;
|
|
250
|
+
return r.project !== null && stale.has(r.project) ? "stale" : "notOwned";
|
|
251
|
+
};
|
|
252
|
+
for (const kind of KINDS) {
|
|
253
|
+
for (const r of listings.get(kind.key) ?? []) {
|
|
254
|
+
if (r.project !== null && skip.has(r.project))
|
|
255
|
+
continue;
|
|
256
|
+
const group = groupOf(r);
|
|
257
|
+
if (group === null)
|
|
258
|
+
continue;
|
|
259
|
+
const label = `${kind.label} ${r.name}`;
|
|
260
|
+
if (group === "notOwned") {
|
|
261
|
+
result.notOwned.push(label);
|
|
262
|
+
continue;
|
|
263
|
+
}
|
|
264
|
+
if (group === "stale") {
|
|
265
|
+
result.stale.push(label);
|
|
266
|
+
if (!opts.sweep)
|
|
267
|
+
continue;
|
|
268
|
+
}
|
|
269
|
+
const why = group === "stale" ? " (its worktree directory is gone)" : "";
|
|
270
|
+
if (opts.dryRun) {
|
|
271
|
+
opts.reporter?.info(`Would remove leftover ${label}${why}`);
|
|
272
|
+
result[kind.key].removed.push(r.name);
|
|
273
|
+
continue;
|
|
274
|
+
}
|
|
275
|
+
try {
|
|
276
|
+
runner(cliArgv[0], [...cliArgv.slice(1), ...kind.remove(r.id)]);
|
|
277
|
+
result[kind.key].removed.push(r.name);
|
|
278
|
+
opts.reporter?.info(`Removed leftover ${label}${why}`);
|
|
279
|
+
}
|
|
280
|
+
catch (err) {
|
|
281
|
+
result[kind.key].failed.push(r.name);
|
|
282
|
+
const reason = err instanceof Error ? err.message.split("\n").slice(-1)[0] : String(err);
|
|
283
|
+
opts.reporter?.warn(`Could not remove ${label}: ${reason}`);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
if (result.stale.length > 0 && !opts.sweep) {
|
|
288
|
+
opts.reporter?.warn(`Kept ${result.stale.length} leftover resource(s) of worktree stacks whose directory no longer exists ` +
|
|
289
|
+
`(e.g. left by wtc ≤0.2): ${result.stale.join(", ")}. ` +
|
|
290
|
+
`Remove them with 'wtc clean --sweep' (preview with --dry-run).`);
|
|
291
|
+
}
|
|
292
|
+
if (result.notOwned.length > 0) {
|
|
293
|
+
opts.reporter?.warn(`Kept ${result.notOwned.length} resource(s) named like this repo's worktree stacks that this checkout ` +
|
|
294
|
+
`does not own (another checkout with the same directory name, or nothing to attribute them by): ` +
|
|
295
|
+
`${result.notOwned.join(", ")}. wtc never removes these; remove them yourself if they are yours.`);
|
|
296
|
+
}
|
|
297
|
+
return result;
|
|
298
|
+
}
|