worktree-compose 1.0.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.
@@ -1,21 +1,40 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
- import { parse as parseYaml } from "yaml";
3
+ import { parseDocument } from "yaml";
4
+ /** The `host:container` string wtc reads a `ports:` entry as, or null (no published port). */
5
+ export function portEntryString(p) {
6
+ if (typeof p === "string")
7
+ return p;
8
+ if (typeof p === "number")
9
+ return String(p);
10
+ if (typeof p === "object" && p !== null) {
11
+ const obj = p;
12
+ if (obj.published != null && obj.target != null) {
13
+ return `${obj.published}:${obj.target}`;
14
+ }
15
+ }
16
+ return null;
17
+ }
4
18
  function parseServicePorts(ports) {
5
19
  if (!Array.isArray(ports))
6
20
  return [];
7
21
  return ports.flatMap((p) => {
8
- if (typeof p === "string")
9
- return [p];
10
- if (typeof p === "number")
11
- return [String(p)];
12
- if (typeof p === "object" && p !== null) {
13
- const obj = p;
14
- if (obj.published != null && obj.target != null) {
15
- return [`${obj.published}:${obj.target}`];
16
- }
17
- }
18
- return [];
22
+ const s = portEntryString(p);
23
+ return s === null ? [] : [s];
24
+ });
25
+ }
26
+ /** Key for deduplicating `ports:` entries across files (same written value). */
27
+ function entryKey(entry) {
28
+ return JSON.stringify(entry) ?? String(entry);
29
+ }
30
+ function uniqueEntries(entries) {
31
+ const seen = new Set();
32
+ return entries.filter((e) => {
33
+ const key = entryKey(e);
34
+ if (seen.has(key))
35
+ return false;
36
+ seen.add(key);
37
+ return true;
19
38
  });
20
39
  }
21
40
  function parseServiceBuild(build) {
@@ -40,7 +59,47 @@ function parseEnvFile(envFile) {
40
59
  }
41
60
  return undefined;
42
61
  }
43
- function parseServicesObject(doc, sourcePath) {
62
+ /** Network names a service joins: the keys of the map form, or the list form. */
63
+ function parseServiceNetworks(networks) {
64
+ if (Array.isArray(networks))
65
+ return networks.filter((n) => typeof n === "string");
66
+ if (networks && typeof networks === "object")
67
+ return Object.keys(networks);
68
+ return undefined;
69
+ }
70
+ /** `extends: base` or `extends: { service, file }`. */
71
+ function parseExtends(ext) {
72
+ if (typeof ext === "string" && ext)
73
+ return { service: ext };
74
+ if (ext && typeof ext === "object") {
75
+ const o = ext;
76
+ if (typeof o.service === "string" && o.service) {
77
+ return { service: o.service, ...(typeof o.file === "string" && o.file ? { file: o.file } : {}) };
78
+ }
79
+ }
80
+ return undefined;
81
+ }
82
+ /**
83
+ * Container names a service joins by name: `network_mode`, `ipc` or `pid`
84
+ * set to `container:<name>`, and `volumes_from: [container:<name>[:ro]]`.
85
+ */
86
+ export function parseContainerRefs(s) {
87
+ const refs = [];
88
+ const add = (v) => {
89
+ if (typeof v === "string" && v.startsWith("container:")) {
90
+ const name = v.slice("container:".length).split(":")[0];
91
+ if (name)
92
+ refs.push(name);
93
+ }
94
+ };
95
+ add(s.network_mode);
96
+ add(s.ipc);
97
+ add(s.pid);
98
+ if (Array.isArray(s.volumes_from))
99
+ s.volumes_from.forEach(add);
100
+ return refs;
101
+ }
102
+ function parseServicesObject(doc, sourcePath, tagOf = () => undefined) {
44
103
  if (!("services" in doc) || !doc.services || typeof doc.services !== "object") {
45
104
  return [];
46
105
  }
@@ -48,12 +107,27 @@ function parseServicesObject(doc, sourcePath) {
48
107
  return Object.entries(servicesObj).map(([name, svc]) => {
49
108
  // An empty service definition (`foo:` with no body) parses to null.
50
109
  const s = svc ?? {};
110
+ const portsTag = tagOf(name, "ports");
111
+ // `!reset` clears the attribute whatever its payload says.
112
+ const portsReset = portsTag === "!reset";
113
+ const nameReset = tagOf(name, "container_name") === "!reset";
114
+ const networks = parseServiceNetworks(s.networks);
115
+ const extendsFrom = parseExtends(s.extends);
116
+ const containerRefs = parseContainerRefs(s);
51
117
  return {
52
118
  name,
53
- ports: parseServicePorts(s.ports),
119
+ ports: portsReset ? [] : parseServicePorts(s.ports),
120
+ portEntries: portsReset ? [] : Array.isArray(s.ports) ? uniqueEntries(s.ports) : [],
121
+ ...(portsTag === "!override" || portsReset ? { portsReplace: true } : {}),
122
+ ...(s.extends != null ? { extends: true } : {}),
123
+ ...(extendsFrom ? { extendsFrom } : {}),
124
+ ...(containerRefs.length > 0 ? { containerRefs } : {}),
125
+ ...(networks ? { networks } : {}),
126
+ ...(s.network_mode != null ? { networkMode: true } : {}),
54
127
  build: parseServiceBuild(s.build),
55
128
  envFile: parseEnvFile(s.env_file),
56
- ...(typeof s.container_name === "string" && s.container_name
129
+ ...(nameReset ? { containerNameReset: true } : {}),
130
+ ...(!nameReset && typeof s.container_name === "string" && s.container_name
57
131
  ? { containerName: s.container_name }
58
132
  : {}),
59
133
  sourcePath,
@@ -154,24 +228,41 @@ function normalizeIncludes(include, parentPath) {
154
228
  * resolves the context relative to the right directory.
155
229
  */
156
230
  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);
231
+ // `ports: !override` / `!reset` in the later file replaces the list.
232
+ const ports = override.portsReplace ? [...override.ports] : [...base.ports];
233
+ if (!override.portsReplace) {
234
+ for (const p of override.ports) {
235
+ if (!ports.includes(p))
236
+ ports.push(p);
237
+ }
161
238
  }
162
239
  const sourcePath = override.build !== undefined
163
240
  ? override.sourcePath
164
241
  : base.build !== undefined
165
242
  ? base.sourcePath
166
243
  : override.sourcePath;
244
+ const containerName = override.containerNameReset
245
+ ? override.containerName
246
+ : (override.containerName ?? base.containerName);
247
+ const networks = [...new Set([...(base.networks ?? []), ...(override.networks ?? [])])];
167
248
  return {
168
249
  name: override.name,
169
250
  ports,
251
+ portEntries: override.portsReplace
252
+ ? (override.portEntries ?? [])
253
+ : uniqueEntries([...(base.portEntries ?? []), ...(override.portEntries ?? [])]),
254
+ ...(base.portsReplace || override.portsReplace ? { portsReplace: true } : {}),
255
+ ...(base.extends || override.extends ? { extends: true } : {}),
256
+ ...((override.extendsFrom ?? base.extendsFrom) ? { extendsFrom: override.extendsFrom ?? base.extendsFrom } : {}),
257
+ ...(base.containerRefs || override.containerRefs
258
+ ? { containerRefs: [...new Set([...(base.containerRefs ?? []), ...(override.containerRefs ?? [])])] }
259
+ : {}),
260
+ ...(base.networks || override.networks ? { networks } : {}),
261
+ ...(base.networkMode || override.networkMode ? { networkMode: true } : {}),
170
262
  build: override.build ?? base.build,
171
263
  envFile: override.envFile ?? base.envFile,
172
- ...((override.containerName ?? base.containerName)
173
- ? { containerName: override.containerName ?? base.containerName }
174
- : {}),
264
+ ...(containerName ? { containerName } : {}),
265
+ ...(override.containerNameReset ? { containerNameReset: true } : {}),
175
266
  sourcePath,
176
267
  };
177
268
  }
@@ -201,15 +292,16 @@ function parseRecursive(filePath, st) {
201
292
  return [];
202
293
  st.seen.add(key);
203
294
  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)}`);
295
+ // Merge keys (`<<: *anchor`) resolved as compose resolves them; compose's
296
+ // own tags (`!reset`, `!override`) kept on the nodes, without warnings.
297
+ const document = parseDocument(raw, { uniqueKeys: false, merge: true });
298
+ if (document.errors.length > 0) {
299
+ throw new Error(`Invalid YAML in ${filePath}: ${document.errors[0].message}`);
210
300
  }
301
+ const doc = document.toJS();
211
302
  if (!doc || typeof doc !== "object")
212
303
  return [];
304
+ const tagOf = (service, k) => document.getIn(["services", service, k], true)?.tag;
213
305
  st.sourceFiles.push(key);
214
306
  // Recurse into includes first so local services can override included ones.
215
307
  let included = [];
@@ -221,7 +313,7 @@ function parseRecursive(filePath, st) {
221
313
  const record = doc;
222
314
  mergeResources(st.volumes, parseResources(record.volumes));
223
315
  mergeResources(st.networks, parseResources(record.networks));
224
- const local = parseServicesObject(record, key);
316
+ const local = parseServicesObject(record, key, tagOf);
225
317
  return foldServices([...included, ...local]);
226
318
  }
227
319
  export function parseComposeFile(composePath) {
@@ -1,6 +1,29 @@
1
1
  export interface ComposeService {
2
2
  name: string;
3
3
  ports: string[];
4
+ /**
5
+ * Every `ports:` entry as written (string, number, or long-form object),
6
+ * merged across files like `ports`. A runtime override that replaces the
7
+ * list must reproduce the entries it does not remap exactly.
8
+ */
9
+ portEntries?: unknown[];
10
+ /** `ports: !override` / `!reset`: the list replaces earlier files' lists instead of adding to them. */
11
+ portsReplace?: boolean;
12
+ /** The service uses `extends:`, so it may inherit ports wtc cannot see. */
13
+ extends?: boolean;
14
+ /** What `extends:` names: a service, in another file when `file` is set. */
15
+ extendsFrom?: {
16
+ service: string;
17
+ file?: string;
18
+ };
19
+ /** Container names the service joins by name (`network_mode: container:<name>`, `volumes_from`, …). */
20
+ containerRefs?: string[];
21
+ /** Networks the service joins (absent: only the project's `default`). */
22
+ networks?: string[];
23
+ /** The service sets `network_mode` (host, none, another container…): no networks of its own. */
24
+ networkMode?: boolean;
25
+ /** `container_name: !reset` in a later file dropped any earlier name. */
26
+ containerNameReset?: boolean;
4
27
  build?: {
5
28
  context?: string;
6
29
  dockerfile?: string;
package/dist/context.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { ComposeEngine } from "./compose/engine.js";
2
+ import type { RemapTargets } from "./compose/override.js";
2
3
  import type { PsContainer, StackProbe } from "./compose/status.js";
3
4
  import type { ComposeFile } from "./compose/types.js";
4
5
  import type { PortMapping } from "./ports/types.js";
@@ -37,6 +38,12 @@ export interface BuildContextOptions {
37
38
  * of treating the current checkout as the main one.
38
39
  */
39
40
  requireMainFor?: string;
41
+ /**
42
+ * Decide runtime remapping of hardcoded ports and container_name (see
43
+ * compose/override.ts), which may probe the engine. Implied by
44
+ * `probeStacks`; set it for other commands that run compose on stacks.
45
+ */
46
+ resolveRemap?: boolean;
40
47
  }
41
48
  export interface WtcContext {
42
49
  repo: RepoInfo;
@@ -65,6 +72,14 @@ export interface WtcContext {
65
72
  warnings: string[];
66
73
  /** Settings that break isolation between worktree stacks. */
67
74
  isolationWarnings: string[];
75
+ /**
76
+ * Hardcoded host ports and fixed container names wtc remaps at runtime
77
+ * (only with `probeStacks` / `resolveRemap`); null when there are none or
78
+ * the engine cannot (the reason is among the isolation warnings).
79
+ */
80
+ remap: RemapTargets | null;
81
+ /** What runtime remapping does, for `wtc start` (informational). */
82
+ remapNotes: string[];
68
83
  /** Stack states (only with `probeStacks`). */
69
84
  stacks: StackProbe | null;
70
85
  /** Resolve the compose engine (lazily; throws when none is available). */
package/dist/context.js CHANGED
@@ -3,7 +3,8 @@ import { detectComposeFile } from "./compose/detect.js";
3
3
  import { parseComposeFile } from "./compose/parse.js";
4
4
  import { resolveEngine } from "./compose/engine.js";
5
5
  import { createStackProbe } from "./compose/status.js";
6
- import { composeIsolationWarnings, portCollisionWarnings, rawPortWarnings, } from "./compose/isolation.js";
6
+ import { composeIsolationWarnings, portCollisionWarnings, rawPortWarnings, remapNotes, } from "./compose/isolation.js";
7
+ import { decideRemap } from "./compose/override.js";
7
8
  import { extractPortMappings } from "./ports/extract.js";
8
9
  import { loadConfig } from "./config.js";
9
10
  import { assertMainCheckout, getRepoInfo, listRepoWorktrees } from "./git/repo.js";
@@ -12,7 +13,7 @@ import { hasRecord, peekState, reconcileWorktrees } from "./state/registry.js";
12
13
  import { escapeRegExp, sanitize } from "./utils/sanitize.js";
13
14
  import { resolveWorkspaces } from "./workspaces/resolve.js";
14
15
  import { resolveSyncEntries } from "./sync/files.js";
15
- import { DEFAULT_ENV_FILE } from "./sync/env.js";
16
+ import { DEFAULT_ENV_FILE, findEnvSource } from "./sync/env.js";
16
17
  function emptyComposeFile(composePath) {
17
18
  return {
18
19
  services: [],
@@ -151,14 +152,32 @@ export function buildContext(cli = {}, opts = {}) {
151
152
  warnings.push(`The main checkout ${u.path} was worktree ${u.index} (${u.project}) before it became the main checkout; ` +
152
153
  `wtc leaves that stack alone (stop or remove it yourself if you no longer need it).`);
153
154
  }
155
+ const decision = opts.probeStacks || opts.resolveRemap
156
+ ? decideRemap({
157
+ composeFile,
158
+ mappings: portMappings,
159
+ mainRoot: repoRoot,
160
+ commonDir: repo.commonDir,
161
+ envFiles: [
162
+ findEnvSource(repoRoot, { dir: "", label: "root", envFileName: config.envFile ?? DEFAULT_ENV_FILE }),
163
+ path.join(repoRoot, DEFAULT_ENV_FILE),
164
+ ],
165
+ envOverrides: config.envOverrides,
166
+ engine: getEngine,
167
+ })
168
+ : { targets: null, problem: null, warnings: [] };
169
+ const remap = decision.targets;
170
+ const remapped = remap?.ports ?? [];
154
171
  const isolationWarnings = [
155
- ...rawPortWarnings(portMappings),
156
- ...composeIsolationWarnings(composeFile),
172
+ ...(decision.problem ? [decision.problem] : []),
173
+ ...decision.warnings,
174
+ ...rawPortWarnings(portMappings, remapped),
175
+ ...composeIsolationWarnings(composeFile, new Set(remap?.containerNames.map((c) => c.service))),
157
176
  ...portCollisionWarnings(portMappings, portStride, [
158
177
  ...reconciled.worktrees.map((w) => w.index),
159
178
  ...reconciled.orphans.map((o) => o.index),
160
179
  ...reconciled.unavailable.map((u) => u.index),
161
- ]),
180
+ ], remapped),
162
181
  ];
163
182
  return {
164
183
  repo,
@@ -176,6 +195,8 @@ export function buildContext(cli = {}, opts = {}) {
176
195
  prunable,
177
196
  warnings,
178
197
  isolationWarnings,
198
+ remap,
199
+ remapNotes: remap ? remapNotes(remap, portMappings) : [],
179
200
  stacks,
180
201
  getEngine,
181
202
  };
@@ -7,6 +7,7 @@ import { getDockerfiles, resolveSyncEntries } from "../sync/files.js";
7
7
  import { getStatusPaths } from "../git/status.js";
8
8
  import { samePath } from "../git/worktree.js";
9
9
  import { forgetRecords } from "../state/registry.js";
10
+ import { overridePath, removeOverride } from "../compose/override.js";
10
11
  import { reportContextWarnings, throwIfAborted } from "./compose.js";
11
12
  import { orphanSkipReason, sweepStaleResources, teardownStack } from "./teardown.js";
12
13
  /** Count a clean run's failures (see CleanResult.failures). */
@@ -314,6 +315,9 @@ export async function clean(options, reporter, io) {
314
315
  const removed = new Set(result.removed);
315
316
  const forget = targets.filter((t) => tornDown.has(t.project) && (t.orphan !== null || removed.has(t.path)));
316
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));
317
321
  result.forgotten = forget.map((t) => t.path);
318
322
  }
319
323
  result.failures = countFailures(result);
@@ -1,18 +1,77 @@
1
1
  import type { RunResult } from "../utils/exec.js";
2
2
  import type { ComposeEngine } from "../compose/engine.js";
3
+ import type { RemapTargets } from "../compose/override.js";
3
4
  import type { PortAllocation } from "../ports/types.js";
4
5
  import type { Reporter } from "../utils/log.js";
5
6
  import type { WtcContext } from "../context.js";
6
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>;
7
10
  /**
8
11
  * Process environment for a compose call on a worktree stack: the project
9
12
  * name plus every allocated port, so `${VAR}` interpolation resolves to the
10
- * worktree's ports no matter which env filename is configured.
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.
11
19
  */
12
- export declare function composeEnv(project: string, allocations: PortAllocation[]): Record<string, string>;
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;
13
72
  export interface ComposeCallOptions {
14
73
  cwd: string;
15
- env?: Record<string, string>;
74
+ env?: ComposeCallEnv;
16
75
  live: boolean;
17
76
  signal?: AbortSignal;
18
77
  onLine?: (line: string) => void;
@@ -21,7 +80,10 @@ export interface ComposeCallOptions {
21
80
  export declare function composeRun(engine: ComposeEngine, project: string, args: string[], opts: ComposeCallOptions): Promise<RunResult>;
22
81
  /** Prefix an error with what was being done, keeping CommandError details. */
23
82
  export declare function withContext(prefix: string, err: unknown): Error;
24
- /** Report a context's general warnings (and isolation warnings when asked). */
83
+ /**
84
+ * Report a context's general warnings (and, when asked, its isolation
85
+ * warnings plus what runtime remapping does).
86
+ */
25
87
  export declare function reportContextWarnings(ctx: WtcContext, reporter: Reporter, opts: {
26
88
  isolation: boolean;
27
89
  }): void;
@@ -1,20 +1,165 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
1
3
  import { CommandError, runAsync } from "../utils/exec.js";
2
4
  import { composeArgs, composeBin } from "../compose/engine.js";
3
- import { allocationEnv } from "../ports/allocate.js";
4
- import { PROJECT_NAME_VAR } from "../sync/env.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";
5
8
  /**
6
9
  * Process environment for a compose call on a worktree stack: the project
7
10
  * name plus every allocated port, so `${VAR}` interpolation resolves to the
8
- * worktree's ports no matter which env filename is configured.
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.
9
17
  */
10
- export function composeEnv(project, allocations) {
11
- return { [PROJECT_NAME_VAR]: project, ...allocationEnv(allocations) };
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 };
12
152
  }
13
153
  /** Run `<compose> -p <project> <args…>` without blocking the event loop. */
14
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
+ }
15
160
  return runAsync(composeBin(engine), composeArgs(engine, project, ...args), {
16
161
  cwd: opts.cwd,
17
- env: { ...process.env, ...opts.env },
162
+ env,
18
163
  live: opts.live,
19
164
  signal: opts.signal,
20
165
  onLine: opts.onLine,
@@ -28,13 +173,18 @@ export function withContext(prefix, err) {
28
173
  }
29
174
  return new Error(`${prefix}: ${err instanceof Error ? err.message : String(err)}`);
30
175
  }
31
- /** Report a context's general warnings (and isolation warnings when asked). */
176
+ /**
177
+ * Report a context's general warnings (and, when asked, its isolation
178
+ * warnings plus what runtime remapping does).
179
+ */
32
180
  export function reportContextWarnings(ctx, reporter, opts) {
33
181
  for (const w of ctx.warnings)
34
182
  reporter.warn(w);
35
183
  if (opts.isolation) {
36
184
  for (const w of ctx.isolationWarnings)
37
185
  reporter.warn(w);
186
+ for (const n of ctx.remapNotes)
187
+ reporter.info(n);
38
188
  }
39
189
  }
40
190
  /** Throw if the operation was cancelled (checked between worktrees). */
@@ -21,8 +21,9 @@ export interface DoctorResult {
21
21
  export declare function isPortBusy(port: number): Promise<boolean>;
22
22
  /**
23
23
  * Diagnose the setup: git, repo layout, compose file, config, compose
24
- * engine and daemon, port isolation, isolation-breaking compose settings,
25
- * worktree/registry health, and host ports already taken for stopped stacks.
26
- * Each check is independent so one failure never hides the others.
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.
27
28
  */
28
29
  export declare function doctor(io: CoreIo): Promise<DoctorResult>;