worktree-compose 0.1.4 → 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.
Files changed (94) hide show
  1. package/README.md +560 -125
  2. package/SKILL.md +113 -0
  3. package/dist/cli.js +94 -33
  4. package/dist/commands/clean.d.ts +2 -1
  5. package/dist/commands/clean.js +8 -48
  6. package/dist/commands/doctor.d.ts +3 -0
  7. package/dist/commands/doctor.js +30 -0
  8. package/dist/commands/list.d.ts +4 -1
  9. package/dist/commands/list.js +62 -44
  10. package/dist/commands/promote.d.ts +3 -1
  11. package/dist/commands/promote.js +4 -34
  12. package/dist/commands/prune.d.ts +2 -0
  13. package/dist/commands/prune.js +7 -0
  14. package/dist/commands/restart.d.ts +2 -1
  15. package/dist/commands/restart.js +11 -5
  16. package/dist/commands/skill.d.ts +4 -0
  17. package/dist/commands/skill.js +10 -0
  18. package/dist/commands/start.d.ts +2 -1
  19. package/dist/commands/start.js +7 -34
  20. package/dist/commands/stop.d.ts +1 -1
  21. package/dist/commands/stop.js +6 -23
  22. package/dist/compose/detect.d.ts +1 -2
  23. package/dist/compose/detect.js +1 -10
  24. package/dist/compose/engine.d.ts +61 -0
  25. package/dist/compose/engine.js +129 -0
  26. package/dist/compose/isolation.d.ts +15 -0
  27. package/dist/compose/isolation.js +62 -0
  28. package/dist/compose/parse.d.ts +5 -0
  29. package/dist/compose/parse.js +200 -12
  30. package/dist/compose/status.d.ts +84 -0
  31. package/dist/compose/status.js +227 -0
  32. package/dist/compose/types.d.ts +25 -0
  33. package/dist/config.d.ts +38 -0
  34. package/dist/config.js +23 -6
  35. package/dist/context.d.ts +90 -3
  36. package/dist/context.js +293 -20
  37. package/dist/core/clean.d.ts +91 -0
  38. package/dist/core/clean.js +343 -0
  39. package/dist/core/compose.d.ts +30 -0
  40. package/dist/core/compose.js +45 -0
  41. package/dist/core/doctor.d.ts +28 -0
  42. package/dist/core/doctor.js +277 -0
  43. package/dist/core/list.d.ts +42 -0
  44. package/dist/core/list.js +94 -0
  45. package/dist/core/promote.d.ts +40 -0
  46. package/dist/core/promote.js +117 -0
  47. package/dist/core/prune.d.ts +32 -0
  48. package/dist/core/prune.js +75 -0
  49. package/dist/core/restart.d.ts +14 -0
  50. package/dist/core/restart.js +18 -0
  51. package/dist/core/start.d.ts +31 -0
  52. package/dist/core/start.js +99 -0
  53. package/dist/core/stop.d.ts +32 -0
  54. package/dist/core/stop.js +57 -0
  55. package/dist/core/teardown.d.ts +121 -0
  56. package/dist/core/teardown.js +298 -0
  57. package/dist/core/types.d.ts +15 -0
  58. package/dist/core/types.js +1 -0
  59. package/dist/git/promote.d.ts +49 -2
  60. package/dist/git/promote.js +160 -38
  61. package/dist/git/repo.d.ts +72 -0
  62. package/dist/git/repo.js +167 -0
  63. package/dist/git/status.d.ts +8 -0
  64. package/dist/git/status.js +25 -0
  65. package/dist/git/worktree.d.ts +63 -3
  66. package/dist/git/worktree.js +173 -29
  67. package/dist/mcp/server.d.ts +2 -0
  68. package/dist/mcp/server.js +230 -116
  69. package/dist/ports/allocate.d.ts +34 -2
  70. package/dist/ports/allocate.js +69 -4
  71. package/dist/selectors.d.ts +10 -0
  72. package/dist/selectors.js +106 -0
  73. package/dist/skill.d.ts +13 -0
  74. package/dist/skill.js +28 -0
  75. package/dist/state/registry.d.ts +194 -0
  76. package/dist/state/registry.js +595 -0
  77. package/dist/sync/env.d.ts +77 -2
  78. package/dist/sync/env.js +151 -32
  79. package/dist/sync/files.d.ts +16 -1
  80. package/dist/sync/files.js +136 -36
  81. package/dist/utils/exec.d.ts +69 -4
  82. package/dist/utils/exec.js +221 -15
  83. package/dist/utils/log.d.ts +37 -0
  84. package/dist/utils/log.js +68 -4
  85. package/dist/utils/paths.d.ts +61 -0
  86. package/dist/utils/paths.js +163 -0
  87. package/dist/utils/sanitize.d.ts +7 -0
  88. package/dist/utils/sanitize.js +12 -0
  89. package/dist/version.d.ts +1 -0
  90. package/dist/version.js +3 -0
  91. package/dist/workspaces/resolve.d.ts +21 -0
  92. package/dist/workspaces/resolve.js +235 -0
  93. package/package.json +13 -9
  94. package/wtc.schema.json +62 -0
@@ -1,37 +1,10 @@
1
- import { buildContext, filterWorktrees } from "../context.js";
2
- import { allocateWorktreePorts } from "../ports/allocate.js";
3
- import { composeProjectName } from "../utils/sanitize.js";
4
- import { execLive } from "../utils/exec.js";
5
- import { syncWorktreeFiles } from "../sync/files.js";
6
- import { copyBaseEnv, injectPortOverrides } from "../sync/env.js";
7
- import * as log from "../utils/log.js";
1
+ import { startWorktrees } from "../core/start.js";
2
+ import { consoleReporter, print } from "../utils/log.js";
8
3
  import { listCommand } from "./list.js";
9
- export function startCommand(indices) {
10
- const ctx = buildContext();
11
- if (ctx.worktrees.length === 0) {
12
- log.warn("No extra worktrees found. Create one with:\n git worktree add ../my-branch my-branch");
4
+ export async function startCommand(worktrees, options = {}) {
5
+ const result = await startWorktrees({ ...options, worktrees }, consoleReporter, { live: true });
6
+ if (result.started.length === 0)
13
7
  return;
14
- }
15
- const targets = filterWorktrees(ctx.worktrees, indices);
16
- for (const wt of targets) {
17
- const idx = ctx.worktrees.indexOf(wt) + 1;
18
- const project = composeProjectName(ctx.repoName, idx, wt.branch);
19
- const allocations = allocateWorktreePorts(ctx.portMappings, idx);
20
- log.header(`Worktree ${idx}: ${wt.branch}`);
21
- log.info(`Path: ${wt.path}`);
22
- log.info(`Project: ${project}`);
23
- log.info(`Ports: ${allocations.map((a) => `${a.envVar}=${a.port}`).join(" ")}`);
24
- syncWorktreeFiles(ctx.repoRoot, wt.path, ctx.composeFile, ctx.config.sync);
25
- log.success("Synced infrastructure files");
26
- copyBaseEnv(ctx.repoRoot, wt.path);
27
- injectPortOverrides(`${wt.path}/.env`, allocations, ctx.config.envOverrides);
28
- log.success("Injected port overrides into .env");
29
- execLive(`docker compose -p "${project}" up -d --build`, {
30
- cwd: wt.path,
31
- env: { ...process.env, COMPOSE_PROJECT_NAME: project },
32
- });
33
- log.success(`Worktree ${idx} started`);
34
- }
35
- console.log("");
36
- listCommand();
8
+ print("");
9
+ await listCommand({ quiet: true });
37
10
  }
@@ -1 +1 @@
1
- export declare function stopCommand(indices: number[]): void;
1
+ export declare function stopCommand(worktrees: string[]): Promise<void>;
@@ -1,24 +1,7 @@
1
- import { buildContext, filterWorktrees } from "../context.js";
2
- import { composeProjectName } from "../utils/sanitize.js";
3
- import { execLive } from "../utils/exec.js";
4
- import * as log from "../utils/log.js";
5
- export function stopCommand(indices) {
6
- const ctx = buildContext();
7
- if (ctx.worktrees.length === 0) {
8
- log.warn("No worktrees to stop.");
9
- return;
10
- }
11
- const targets = filterWorktrees(ctx.worktrees, indices);
12
- for (const wt of targets) {
13
- const idx = ctx.worktrees.indexOf(wt) + 1;
14
- const project = composeProjectName(ctx.repoName, idx, wt.branch);
15
- log.info(`Stopping ${project}...`);
16
- try {
17
- execLive(`docker compose -p "${project}" down`, { cwd: wt.path });
18
- log.success(`Stopped worktree ${idx} (${wt.branch})`);
19
- }
20
- catch {
21
- log.warn(`Could not stop ${project} (may already be stopped)`);
22
- }
23
- }
1
+ import { stopWorktrees } from "../core/stop.js";
2
+ import { consoleReporter } from "../utils/log.js";
3
+ export async function stopCommand(worktrees) {
4
+ const result = await stopWorktrees({ worktrees }, consoleReporter, { live: true });
5
+ if (result.failures > 0)
6
+ process.exitCode = 1;
24
7
  }
@@ -1,3 +1,2 @@
1
- export declare function getRepoRoot(cwd?: string): string;
2
- export declare function getRepoName(repoRoot: string): string;
1
+ export declare const COMPOSE_FILENAMES: string[];
3
2
  export declare function detectComposeFile(repoRoot: string): string | null;
@@ -1,20 +1,11 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
- import { exec } from "../utils/exec.js";
4
- const COMPOSE_FILENAMES = [
3
+ export const COMPOSE_FILENAMES = [
5
4
  "compose.yaml",
6
5
  "compose.yml",
7
6
  "docker-compose.yaml",
8
7
  "docker-compose.yml",
9
8
  ];
10
- export function getRepoRoot(cwd) {
11
- return exec("git rev-parse --show-toplevel", {
12
- cwd: cwd ?? process.cwd(),
13
- });
14
- }
15
- export function getRepoName(repoRoot) {
16
- return path.basename(repoRoot);
17
- }
18
9
  export function detectComposeFile(repoRoot) {
19
10
  for (const name of COMPOSE_FILENAMES) {
20
11
  const full = path.join(repoRoot, name);
@@ -0,0 +1,61 @@
1
+ import type { WtcConfig } from "../config.js";
2
+ export interface ComposeEngine {
3
+ /** argv prefix for compose, e.g. ["docker","compose"], ["podman","compose"], ["docker-compose"], ["podman-compose"] */
4
+ compose: string[];
5
+ /** Container CLI flavor used for sweeps/status: "docker" | "podman". */
6
+ cli: "docker" | "podman";
7
+ /**
8
+ * argv prefix for container-CLI calls (`ps`, `info`, sweeps): the binary
9
+ * plus any global flags that preceded `compose` (`docker --context colima
10
+ * compose` → `["docker", "--context", "colima"]`), so status and sweeps
11
+ * talk to the same daemon compose does.
12
+ */
13
+ cliArgv: string[];
14
+ /** Human label, e.g. "docker compose". */
15
+ label: string;
16
+ }
17
+ /** Returns true when `<argv> version` runs successfully. */
18
+ export type EngineProbe = (argv: string[]) => boolean;
19
+ /** Returns true when the container daemon behind `cliArgv` answers. */
20
+ export type DaemonProbe = (cliArgv: string[]) => boolean;
21
+ /** Auto-detection order: Compose v2 plugin first, then Podman, then standalone binaries. */
22
+ export declare const ENGINE_CANDIDATES: string[][];
23
+ export declare const NO_ENGINE_MESSAGE: string;
24
+ /**
25
+ * `<cliArgv> info`: talks to the daemon (or podman machine), so it exits
26
+ * non-zero when that is down — unlike `version`, which succeeds client-only.
27
+ */
28
+ export declare function daemonCheckArgs(engine: Pick<ComposeEngine, "cliArgv">): [string, string[]];
29
+ export declare function engineFromArgv(argv: string[]): ComposeEngine;
30
+ /** True when `argv` is exactly one of the known compose commands. */
31
+ export declare function isKnownComposeCommand(argv: string[]): boolean;
32
+ /**
33
+ * Pick the compose command: `WTC_COMPOSE_COMMAND`, then config
34
+ * `composeCommand`, then auto-detection (cached per process). Resolved
35
+ * lazily — only commands that touch containers need it, so `promote` works
36
+ * without Docker installed.
37
+ *
38
+ * `composeCommand` comes from a file committed to the repository, so it may
39
+ * only *choose* one of the known compose tools: an arbitrary argv there
40
+ * would let a cloned repo run any program — even from `wtc doctor` /
41
+ * `wtc_doctor`, which agents treat as read-only — and extra flags such as
42
+ * `docker --config ./dir compose` load repo-shipped CLI plugins. Custom
43
+ * commands belong in `WTC_COMPOSE_COMMAND`, which the user controls.
44
+ *
45
+ * Auto-detection finds the installed candidates (`version` succeeds,
46
+ * which needs no daemon). When more than one is installed it prefers the
47
+ * first whose daemon answers (`info`), so a quit Docker Desktop does not
48
+ * shadow a running Podman; when none answers — or only one is installed —
49
+ * it takes the first installed one.
50
+ */
51
+ export declare function resolveEngine(config: WtcConfig, env?: NodeJS.ProcessEnv, probe?: EngineProbe, daemonProbe?: DaemonProbe): ComposeEngine;
52
+ /** Forget the cached auto-detected engine (tests). */
53
+ export declare function resetEngineCache(): void;
54
+ /** Arguments (after `engine.compose[0]`) for a compose call on `project`. */
55
+ export declare function composeArgs(engine: ComposeEngine, project: string, ...rest: string[]): string[];
56
+ /** The executable for compose calls. */
57
+ export declare function composeBin(engine: ComposeEngine): string;
58
+ /** `[file, args]` for a container-CLI call (`ps`, `volume ls`, …) on the engine's daemon. */
59
+ export declare function cliCall(engine: Pick<ComposeEngine, "cliArgv">, ...args: string[]): [string, string[]];
60
+ /** True for the Compose v2 plugin (`docker compose`, `podman compose`). */
61
+ export declare function isComposePlugin(engine: ComposeEngine): boolean;
@@ -0,0 +1,129 @@
1
+ import path from "node:path";
2
+ import { ENGINE_PROBE_TIMEOUT_MS, runSafe } from "../utils/exec.js";
3
+ /** Auto-detection order: Compose v2 plugin first, then Podman, then standalone binaries. */
4
+ export const ENGINE_CANDIDATES = [
5
+ ["docker", "compose"],
6
+ ["podman", "compose"],
7
+ ["docker-compose"],
8
+ ["podman-compose"],
9
+ ];
10
+ export const NO_ENGINE_MESSAGE = `No container compose tool found. Install Docker with Compose v2, or Podman ` +
11
+ `(podman compose / podman-compose), or set WTC_COMPOSE_COMMAND / "composeCommand".`;
12
+ const defaultProbe = (argv) => runSafe(argv[0], [...argv.slice(1), "version"], { timeoutMs: ENGINE_PROBE_TIMEOUT_MS }) !== null;
13
+ /**
14
+ * `<cliArgv> info`: talks to the daemon (or podman machine), so it exits
15
+ * non-zero when that is down — unlike `version`, which succeeds client-only.
16
+ */
17
+ export function daemonCheckArgs(engine) {
18
+ return cliCall(engine, "info");
19
+ }
20
+ const defaultDaemonProbe = (cliArgv) => {
21
+ const [file, args] = daemonCheckArgs({ cliArgv });
22
+ return runSafe(file, args, { timeoutMs: ENGINE_PROBE_TIMEOUT_MS }) !== null;
23
+ };
24
+ let detected = null;
25
+ export function engineFromArgv(argv) {
26
+ const cli = path.basename(argv[0]).includes("podman") ? "podman" : "docker";
27
+ // `<bin> [global flags…] compose`: everything before the `compose`
28
+ // subcommand also applies to plain container-CLI calls.
29
+ const sub = argv.indexOf("compose", 1);
30
+ const cliArgv = sub > 0 ? argv.slice(0, sub) : [cli];
31
+ return { compose: argv, cli, cliArgv, label: argv.join(" ") };
32
+ }
33
+ function splitCommand(value) {
34
+ return value.trim().split(/\s+/).filter(Boolean);
35
+ }
36
+ function fromConfig(value, source) {
37
+ const argv = typeof value === "string"
38
+ ? splitCommand(value)
39
+ : Array.isArray(value) && value.every((v) => typeof v === "string")
40
+ ? value.filter((v) => v.trim() !== "")
41
+ : null;
42
+ if (!argv || argv.length === 0) {
43
+ throw new Error(`Invalid ${source}: expected a command such as "docker compose" or ["podman", "compose"].`);
44
+ }
45
+ return argv;
46
+ }
47
+ /** True when `argv` is exactly one of the known compose commands. */
48
+ export function isKnownComposeCommand(argv) {
49
+ return ENGINE_CANDIDATES.some((c) => c.length === argv.length && c.every((part, i) => part === argv[i]));
50
+ }
51
+ /**
52
+ * Pick the compose command: `WTC_COMPOSE_COMMAND`, then config
53
+ * `composeCommand`, then auto-detection (cached per process). Resolved
54
+ * lazily — only commands that touch containers need it, so `promote` works
55
+ * without Docker installed.
56
+ *
57
+ * `composeCommand` comes from a file committed to the repository, so it may
58
+ * only *choose* one of the known compose tools: an arbitrary argv there
59
+ * would let a cloned repo run any program — even from `wtc doctor` /
60
+ * `wtc_doctor`, which agents treat as read-only — and extra flags such as
61
+ * `docker --config ./dir compose` load repo-shipped CLI plugins. Custom
62
+ * commands belong in `WTC_COMPOSE_COMMAND`, which the user controls.
63
+ *
64
+ * Auto-detection finds the installed candidates (`version` succeeds,
65
+ * which needs no daemon). When more than one is installed it prefers the
66
+ * first whose daemon answers (`info`), so a quit Docker Desktop does not
67
+ * shadow a running Podman; when none answers — or only one is installed —
68
+ * it takes the first installed one.
69
+ */
70
+ export function resolveEngine(config, env = process.env, probe, daemonProbe) {
71
+ const fromEnv = env.WTC_COMPOSE_COMMAND;
72
+ if (fromEnv !== undefined && fromEnv.trim() !== "") {
73
+ return engineFromArgv(fromConfig(fromEnv, "WTC_COMPOSE_COMMAND"));
74
+ }
75
+ if (config.composeCommand !== undefined) {
76
+ const argv = fromConfig(config.composeCommand, `"composeCommand" config`);
77
+ if (!isKnownComposeCommand(argv)) {
78
+ throw new Error(`"composeCommand" ${JSON.stringify(argv.join(" "))} is not a known compose tool ` +
79
+ `(${ENGINE_CANDIDATES.map((c) => c.join(" ")).join(", ")}). ` +
80
+ `Repository config may only choose one of those; to run a custom command, ` +
81
+ `set WTC_COMPOSE_COMMAND in your environment.`);
82
+ }
83
+ return engineFromArgv(argv);
84
+ }
85
+ const injected = probe !== undefined || daemonProbe !== undefined;
86
+ if (!injected && detected)
87
+ return detected;
88
+ const check = probe ?? defaultProbe;
89
+ // An injected version probe without a daemon probe means "daemons are up".
90
+ const daemonProbeFn = daemonProbe ?? (probe ? () => true : defaultDaemonProbe);
91
+ const installed = ENGINE_CANDIDATES.filter((candidate) => check(candidate)).map(engineFromArgv);
92
+ if (installed.length === 0)
93
+ throw new Error(NO_ENGINE_MESSAGE);
94
+ let chosen = installed[0];
95
+ if (installed.length > 1) {
96
+ // `docker compose` and `docker-compose` share a daemon: ask it once.
97
+ const answers = new Map();
98
+ const daemonUp = (engine) => {
99
+ const key = engine.cliArgv.join("\0");
100
+ if (!answers.has(key))
101
+ answers.set(key, daemonProbeFn(engine.cliArgv));
102
+ return answers.get(key) === true;
103
+ };
104
+ chosen = installed.find(daemonUp) ?? installed[0];
105
+ }
106
+ if (!injected)
107
+ detected = chosen;
108
+ return chosen;
109
+ }
110
+ /** Forget the cached auto-detected engine (tests). */
111
+ export function resetEngineCache() {
112
+ detected = null;
113
+ }
114
+ /** Arguments (after `engine.compose[0]`) for a compose call on `project`. */
115
+ export function composeArgs(engine, project, ...rest) {
116
+ return [...engine.compose.slice(1), "-p", project, ...rest];
117
+ }
118
+ /** The executable for compose calls. */
119
+ export function composeBin(engine) {
120
+ return engine.compose[0];
121
+ }
122
+ /** `[file, args]` for a container-CLI call (`ps`, `volume ls`, …) on the engine's daemon. */
123
+ export function cliCall(engine, ...args) {
124
+ return [engine.cliArgv[0], [...engine.cliArgv.slice(1), ...args]];
125
+ }
126
+ /** True for the Compose v2 plugin (`docker compose`, `podman compose`). */
127
+ export function isComposePlugin(engine) {
128
+ return engine.compose.length >= 2 && engine.compose.includes("compose", 1);
129
+ }
@@ -0,0 +1,15 @@
1
+ import type { PortMapping } from "../ports/types.js";
2
+ import type { ComposeFile } from "./types.js";
3
+ /**
4
+ * Compose settings that defeat per-worktree isolation: a fixed
5
+ * `container_name` (the second stack cannot start), and volumes/networks with
6
+ * a fixed `name:` or `external` (every stack shares them).
7
+ */
8
+ export declare function composeIsolationWarnings(composeFile: ComposeFile): string[];
9
+ /** Raw `host:container` port mappings that cannot be remapped per worktree. */
10
+ export declare function rawPortWarnings(portMappings: PortMapping[]): string[];
11
+ /**
12
+ * Advisory cross-worktree collision warning over the indices actually in use
13
+ * (live worktrees plus orphans that still reserve theirs).
14
+ */
15
+ export declare function portCollisionWarnings(portMappings: PortMapping[], portStride: number, indices: number[]): string[];
@@ -0,0 +1,62 @@
1
+ import { suggestEnvVar } from "../ports/extract.js";
2
+ import { detectCrossWorktreeCollisions, recommendPortStride, } from "../ports/allocate.js";
3
+ import { isProjectScopedName } from "./parse.js";
4
+ /**
5
+ * Compose settings that defeat per-worktree isolation: a fixed
6
+ * `container_name` (the second stack cannot start), and volumes/networks with
7
+ * a fixed `name:` or `external` (every stack shares them).
8
+ */
9
+ export function composeIsolationWarnings(composeFile) {
10
+ const warnings = [];
11
+ for (const svc of composeFile.services) {
12
+ if (svc.containerName && !isProjectScopedName(svc.containerName)) {
13
+ warnings.push(`Service "${svc.name}" sets container_name "${svc.containerName}" — every worktree stack would use the same name and the second one fails to start. Remove container_name.`);
14
+ }
15
+ }
16
+ for (const v of composeFile.sharedVolumes) {
17
+ warnings.push(`Volume "${v.key}" has a fixed name/external — it is shared by every worktree stack (not isolated).`);
18
+ }
19
+ for (const n of composeFile.sharedNetworks) {
20
+ warnings.push(`Network "${n.key}" has a fixed name/external — it is shared by every worktree stack (not isolated).`);
21
+ }
22
+ return warnings;
23
+ }
24
+ /** Raw `host:container` port mappings that cannot be remapped per worktree. */
25
+ export function rawPortWarnings(portMappings) {
26
+ return portMappings
27
+ .filter((m) => m.envVar === null)
28
+ .map((p) => `Service "${p.serviceName}" uses a raw port mapping (${p.raw}). ` +
29
+ `To enable port isolation, change it to: "\${${suggestEnvVar(p.serviceName)}:-${p.defaultPort}}:${p.containerPort}"`);
30
+ }
31
+ /**
32
+ * Advisory cross-worktree collision warning over the indices actually in use
33
+ * (live worktrees plus orphans that still reserve theirs).
34
+ */
35
+ export function portCollisionWarnings(portMappings, portStride, indices) {
36
+ const inUse = [...new Set(indices)];
37
+ if (inUse.length < 2)
38
+ return [];
39
+ // Collision detection is advisory; an allocation failure here must never
40
+ // abort the command that triggered the warning.
41
+ let collisions;
42
+ try {
43
+ collisions = detectCrossWorktreeCollisions(portMappings, portStride, inUse);
44
+ }
45
+ catch {
46
+ return [];
47
+ }
48
+ if (collisions.length === 0)
49
+ return [];
50
+ const examples = collisions
51
+ .slice(0, 3)
52
+ .map((c) => `${c.port} (wt${c.a.worktreeIndex}/${c.a.serviceName} ↔ wt${c.b.worktreeIndex}/${c.b.serviceName})`)
53
+ .join(", ");
54
+ const recommended = recommendPortStride(portMappings, Math.max(...inUse));
55
+ const fix = recommended > 0
56
+ ? `Set "portStride": ${recommended} in .wtcrc.json (or package.json#wtc) to resolve.`
57
+ : `No single portStride resolves this — check for services sharing the same default port.`;
58
+ return [
59
+ `Cross-worktree port collisions detected with portStride=${portStride} ` +
60
+ `across worktrees ${inUse.sort((a, b) => a - b).join(", ")}: ${collisions.length} collision(s), e.g. ${examples}. ${fix}`,
61
+ ];
62
+ }
@@ -1,2 +1,7 @@
1
1
  import type { ComposeFile } from "./types.js";
2
+ /**
3
+ * A name built from `${COMPOSE_PROJECT_NAME}` is still per-stack: wtc sets
4
+ * that variable for every worktree (process env and root env file).
5
+ */
6
+ export declare function isProjectScopedName(name: string): boolean;
2
7
  export declare function parseComposeFile(composePath: string): ComposeFile;
@@ -1,4 +1,5 @@
1
1
  import fs from "node:fs";
2
+ import path from "node:path";
2
3
  import { parse as parseYaml } from "yaml";
3
4
  function parseServicePorts(ports) {
4
5
  if (!Array.isArray(ports))
@@ -26,6 +27,7 @@ function parseServiceBuild(build) {
26
27
  return {
27
28
  context: typeof obj.context === "string" ? obj.context : undefined,
28
29
  dockerfile: typeof obj.dockerfile === "string" ? obj.dockerfile : undefined,
30
+ ...(typeof obj.dockerfile_inline === "string" ? { inline: true } : {}),
29
31
  };
30
32
  }
31
33
  return undefined;
@@ -38,18 +40,204 @@ function parseEnvFile(envFile) {
38
40
  }
39
41
  return undefined;
40
42
  }
41
- export function parseComposeFile(composePath) {
42
- const raw = fs.readFileSync(composePath, "utf-8");
43
- const doc = parseYaml(raw, { uniqueKeys: false });
44
- if (!doc || typeof doc !== "object" || !("services" in doc)) {
45
- return { services: [], composePath };
43
+ function parseServicesObject(doc, sourcePath) {
44
+ if (!("services" in doc) || !doc.services || typeof doc.services !== "object") {
45
+ return [];
46
46
  }
47
47
  const servicesObj = doc.services;
48
- const services = Object.entries(servicesObj).map(([name, svc]) => ({
49
- name,
50
- ports: parseServicePorts(svc.ports),
51
- build: parseServiceBuild(svc.build),
52
- envFile: parseEnvFile(svc.env_file),
53
- }));
54
- return { services, composePath };
48
+ return Object.entries(servicesObj).map(([name, svc]) => {
49
+ // An empty service definition (`foo:` with no body) parses to null.
50
+ const s = svc ?? {};
51
+ return {
52
+ name,
53
+ ports: parseServicePorts(s.ports),
54
+ build: parseServiceBuild(s.build),
55
+ envFile: parseEnvFile(s.env_file),
56
+ ...(typeof s.container_name === "string" && s.container_name
57
+ ? { containerName: s.container_name }
58
+ : {}),
59
+ sourcePath,
60
+ };
61
+ });
62
+ }
63
+ /**
64
+ * Top-level `volumes:` / `networks:` entries. Only `name:` and `external`
65
+ * matter to wtc: either one takes the resource out of the project scope, so
66
+ * every worktree stack would share it.
67
+ */
68
+ function parseResources(section) {
69
+ const out = new Map();
70
+ if (!section || typeof section !== "object" || Array.isArray(section)) {
71
+ return out;
72
+ }
73
+ for (const [key, raw] of Object.entries(section)) {
74
+ const def = raw && typeof raw === "object" ? raw : {};
75
+ // `external: true`, or the legacy `external: { name: x }` form.
76
+ const external = def.external === true ||
77
+ (typeof def.external === "object" && def.external !== null);
78
+ const legacyName = typeof def.external === "object" && def.external !== null
79
+ ? def.external.name
80
+ : undefined;
81
+ const name = typeof def.name === "string" && def.name
82
+ ? def.name
83
+ : typeof legacyName === "string" && legacyName
84
+ ? legacyName
85
+ : undefined;
86
+ out.set(key, { ...(name ? { name } : {}), external });
87
+ }
88
+ return out;
89
+ }
90
+ /** Later definitions override earlier ones field by field, like services. */
91
+ function mergeResources(into, from) {
92
+ for (const [key, def] of from) {
93
+ const existing = into.get(key);
94
+ into.set(key, existing
95
+ ? { name: def.name ?? existing.name, external: def.external || existing.external }
96
+ : def);
97
+ }
98
+ }
99
+ /**
100
+ * A name built from `${COMPOSE_PROJECT_NAME}` is still per-stack: wtc sets
101
+ * that variable for every worktree (process env and root env file).
102
+ */
103
+ export function isProjectScopedName(name) {
104
+ return /\$\{?COMPOSE_PROJECT_NAME\b/.test(name);
105
+ }
106
+ function sharedOnly(defs) {
107
+ const out = [];
108
+ for (const [key, def] of defs) {
109
+ if (!def.external && (!def.name || isProjectScopedName(def.name)))
110
+ continue;
111
+ out.push({ key, ...(def.name ? { name: def.name } : {}), external: def.external });
112
+ }
113
+ return out;
114
+ }
115
+ /**
116
+ * Normalize a top-level `include:` value into a list of resolved absolute
117
+ * paths. Each entry is a string path or a long-form object whose `path` is a
118
+ * string or list of strings. Paths resolve relative to the directory of the
119
+ * file currently being parsed.
120
+ */
121
+ function normalizeIncludes(include, parentPath) {
122
+ if (!Array.isArray(include))
123
+ return [];
124
+ const dir = path.dirname(parentPath);
125
+ const out = [];
126
+ for (const entry of include) {
127
+ let paths = [];
128
+ if (typeof entry === "string") {
129
+ paths = [entry];
130
+ }
131
+ else if (entry && typeof entry === "object" && "path" in entry) {
132
+ const p = entry.path;
133
+ if (typeof p === "string") {
134
+ paths = [p];
135
+ }
136
+ else if (Array.isArray(p)) {
137
+ paths = p.filter((s) => typeof s === "string");
138
+ }
139
+ }
140
+ for (const p of paths)
141
+ out.push(path.resolve(dir, p));
142
+ }
143
+ return out;
144
+ }
145
+ /**
146
+ * Combine two definitions of the same service. Docker Compose deep-merges
147
+ * same-named services across included/overriding files rather than replacing
148
+ * them wholesale, so a later definition that omits `ports` must NOT discard the
149
+ * earlier one's ports — otherwise that service silently loses its per-worktree
150
+ * port isolation. We merge the fields wtc relies on: ports are unioned (deduped
151
+ * by raw mapping so the allocator never sees a duplicate), while build/envFile
152
+ * fall back to the base when the override doesn't set them. sourcePath stays
153
+ * aligned with whichever file actually declared `build`, so getDockerfiles
154
+ * resolves the context relative to the right directory.
155
+ */
156
+ function mergeService(base, override) {
157
+ const ports = [...base.ports];
158
+ for (const p of override.ports) {
159
+ if (!ports.includes(p))
160
+ ports.push(p);
161
+ }
162
+ const sourcePath = override.build !== undefined
163
+ ? override.sourcePath
164
+ : base.build !== undefined
165
+ ? base.sourcePath
166
+ : override.sourcePath;
167
+ return {
168
+ name: override.name,
169
+ ports,
170
+ build: override.build ?? base.build,
171
+ envFile: override.envFile ?? base.envFile,
172
+ ...((override.containerName ?? base.containerName)
173
+ ? { containerName: override.containerName ?? base.containerName }
174
+ : {}),
175
+ sourcePath,
176
+ };
177
+ }
178
+ /**
179
+ * Fold services in declaration order (included first, in include order, then
180
+ * local), deep-merging any later definition of an already-seen service name
181
+ * onto the earlier one. Replaces a previous wholesale last-writer-wins merge,
182
+ * which silently dropped the base's ports when an override redefined a service
183
+ * without repeating them.
184
+ */
185
+ function foldServices(services) {
186
+ const byName = new Map();
187
+ for (const svc of services) {
188
+ const existing = byName.get(svc.name);
189
+ byName.set(svc.name, existing ? mergeService(existing, svc) : svc);
190
+ }
191
+ return [...byName.values()];
192
+ }
193
+ function parseRecursive(filePath, st) {
194
+ if (!fs.existsSync(filePath)) {
195
+ console.warn(`wtc: included compose file not found, skipping: ${filePath}`);
196
+ return [];
197
+ }
198
+ // Key on the realpath so symlinked duplicates and cycles are caught.
199
+ const key = fs.realpathSync.native(filePath);
200
+ if (st.seen.has(key))
201
+ return [];
202
+ st.seen.add(key);
203
+ const raw = fs.readFileSync(filePath, "utf-8");
204
+ let doc;
205
+ try {
206
+ doc = parseYaml(raw, { uniqueKeys: false });
207
+ }
208
+ catch (err) {
209
+ throw new Error(`Invalid YAML in ${filePath}: ${err instanceof Error ? err.message : String(err)}`);
210
+ }
211
+ if (!doc || typeof doc !== "object")
212
+ return [];
213
+ st.sourceFiles.push(key);
214
+ // Recurse into includes first so local services can override included ones.
215
+ let included = [];
216
+ if ("include" in doc) {
217
+ for (const inc of normalizeIncludes(doc.include, filePath)) {
218
+ included = included.concat(parseRecursive(inc, st));
219
+ }
220
+ }
221
+ const record = doc;
222
+ mergeResources(st.volumes, parseResources(record.volumes));
223
+ mergeResources(st.networks, parseResources(record.networks));
224
+ const local = parseServicesObject(record, key);
225
+ return foldServices([...included, ...local]);
226
+ }
227
+ export function parseComposeFile(composePath) {
228
+ const abs = path.resolve(composePath);
229
+ const st = {
230
+ seen: new Set(),
231
+ sourceFiles: [],
232
+ volumes: new Map(),
233
+ networks: new Map(),
234
+ };
235
+ const services = parseRecursive(abs, st);
236
+ return {
237
+ services,
238
+ composePath: abs,
239
+ sourceFiles: st.sourceFiles,
240
+ sharedVolumes: sharedOnly(st.volumes),
241
+ sharedNetworks: sharedOnly(st.networks),
242
+ };
55
243
  }