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.
@@ -10,14 +10,64 @@ export function allocatePort(defaultPort, worktreeIndex, portStride = 1) {
10
10
  }
11
11
  return port;
12
12
  }
13
- export function allocateWorktreePorts(mappings, worktreeIndex, portStride = 1) {
14
- const overridable = mappings.filter((m) => m.envVar !== null);
15
- const allocations = overridable.map((m) => ({
16
- serviceName: m.serviceName,
17
- envVar: m.envVar,
18
- port: allocatePort(m.defaultPort, worktreeIndex, portStride),
19
- containerPort: m.containerPort,
20
- }));
13
+ /**
14
+ * The mappings that get a host port of their own: each `${VAR:-port}`
15
+ * mapping (an exact repeat, e.g. the same variable for tcp and udp, only
16
+ * once), then each hardcoded mapping in `remapped` (remapped at runtime,
17
+ * see compose/override.ts) whose default port is not already covered — the
18
+ * allocated port depends only on the default port, so `53:53/tcp` and
19
+ * `53:53/udp` share one.
20
+ */
21
+ export function allocatableMappings(mappings, remapped = []) {
22
+ const out = [];
23
+ const declared = new Set();
24
+ const defaults = new Set();
25
+ for (const m of mappings) {
26
+ const key = `${m.envVar}\0${m.defaultPort}`;
27
+ if (m.envVar === null || declared.has(key))
28
+ continue;
29
+ declared.add(key);
30
+ defaults.add(m.defaultPort);
31
+ out.push(m);
32
+ }
33
+ for (const m of remapped) {
34
+ if (m.envVar !== null || m.range || defaults.has(m.defaultPort))
35
+ continue;
36
+ defaults.add(m.defaultPort);
37
+ out.push(m);
38
+ }
39
+ return out;
40
+ }
41
+ /** `allocatePort`, or null for a hardcoded mapping whose port has nowhere to move (it stays as it is). */
42
+ function allocateOrKeep(m, worktreeIndex, portStride) {
43
+ if (m.envVar !== null)
44
+ return allocatePort(m.defaultPort, worktreeIndex, portStride);
45
+ try {
46
+ return allocatePort(m.defaultPort, worktreeIndex, portStride);
47
+ }
48
+ catch {
49
+ return null;
50
+ }
51
+ }
52
+ /**
53
+ * Ports for one worktree: every `${VAR:-port}` mapping, plus the hardcoded
54
+ * mappings in `remapped` (envVar null). A hardcoded port that cannot be
55
+ * moved within range (e.g. 65500) gets no allocation and stays as it is;
56
+ * a variable's port that cannot throws, as before.
57
+ */
58
+ export function allocateWorktreePorts(mappings, worktreeIndex, portStride = 1, remapped = []) {
59
+ const allocations = allocatableMappings(mappings, remapped).flatMap((m) => {
60
+ const port = allocateOrKeep(m, worktreeIndex, portStride);
61
+ return port === null
62
+ ? []
63
+ : [{
64
+ serviceName: m.serviceName,
65
+ envVar: m.envVar,
66
+ port,
67
+ containerPort: m.containerPort,
68
+ defaultPort: m.defaultPort,
69
+ }];
70
+ });
21
71
  const seen = new Set();
22
72
  for (const a of allocations) {
23
73
  if (seen.has(a.port)) {
@@ -36,7 +86,19 @@ export function allocateWorktreePorts(mappings, worktreeIndex, portStride = 1) {
36
86
  * environment.
37
87
  */
38
88
  export function allocationEnv(allocations) {
39
- return Object.fromEntries(allocations.map((a) => [a.envVar, String(a.port)]));
89
+ return Object.fromEntries(allocations.flatMap((a) => (a.envVar === null ? [] : [[a.envVar, String(a.port)]])));
90
+ }
91
+ /**
92
+ * How a port is named in output (`wtc list`, `ports` in JSON and MCP): its
93
+ * variable, or `<service>:<default port>` for a hardcoded port remapped at
94
+ * runtime — no variable holds that one.
95
+ */
96
+ export function portLabel(a) {
97
+ return a.envVar ?? `${a.serviceName}:${a.defaultPort}`;
98
+ }
99
+ /** `{ label: port }` for output. */
100
+ export function portsByLabel(allocations) {
101
+ return Object.fromEntries(allocations.map((a) => [portLabel(a), a.port]));
40
102
  }
41
103
  /**
42
104
  * Detect cross-worktree port collisions for a given stride. `worktrees` is
@@ -44,8 +106,8 @@ export function allocationEnv(allocations) {
44
106
  * indices can have gaps (e.g. 2, 3, 7), and only the ones actually assigned
45
107
  * can collide. Returns one entry per colliding allocation.
46
108
  */
47
- export function detectCrossWorktreeCollisions(mappings, portStride, worktrees) {
48
- const overridable = mappings.filter((m) => m.envVar !== null);
109
+ export function detectCrossWorktreeCollisions(mappings, portStride, worktrees, remapped = []) {
110
+ const overridable = allocatableMappings(mappings, remapped);
49
111
  const seen = new Map();
50
112
  const collisions = [];
51
113
  const indices = Array.isArray(worktrees)
@@ -53,7 +115,9 @@ export function detectCrossWorktreeCollisions(mappings, portStride, worktrees) {
53
115
  : Array.from({ length: worktrees }, (_, i) => i + 1);
54
116
  for (const w of indices) {
55
117
  for (const m of overridable) {
56
- const port = allocatePort(m.defaultPort, w, portStride);
118
+ const port = allocateOrKeep(m, w, portStride);
119
+ if (port === null)
120
+ continue;
57
121
  const prev = seen.get(port);
58
122
  if (prev) {
59
123
  collisions.push({
@@ -76,11 +140,11 @@ const STRIDE_SEARCH_CAP = 4096;
76
140
  * no stride within the search cap works — which signals duplicate default
77
141
  * ports within a worktree, a case the per-worktree dedup guard already rejects.
78
142
  */
79
- export function recommendPortStride(mappings, worktreeCount) {
143
+ export function recommendPortStride(mappings, worktreeCount, remapped = []) {
80
144
  const horizon = Math.max(worktreeCount, 100);
81
145
  for (let s = 1; s <= STRIDE_SEARCH_CAP; s++) {
82
146
  try {
83
- if (detectCrossWorktreeCollisions(mappings, s, horizon).length === 0) {
147
+ if (detectCrossWorktreeCollisions(mappings, s, horizon, remapped).length === 0) {
84
148
  return s;
85
149
  }
86
150
  }
@@ -1,4 +1,16 @@
1
1
  import type { ComposeService } from "../compose/types.js";
2
2
  import type { PortMapping } from "./types.js";
3
+ /**
4
+ * Split a `ports:` string into its `:`-separated segments, keeping `${…}`
5
+ * interpolations whole. The protocol suffix (`/tcp`) is stripped first.
6
+ */
7
+ export declare function portSegments(raw: string): string[];
3
8
  export declare function extractPortMappings(services: ComposeService[]): PortMapping[];
4
9
  export declare function suggestEnvVar(serviceName: string): string;
10
+ /**
11
+ * A variable name to suggest for each hardcoded mapping: `<SERVICE>_PORT`,
12
+ * or `<SERVICE>_<CONTAINER>_PORT` for a service's further ports, never one
13
+ * the compose file already uses (two ports sharing a name would get the
14
+ * same value).
15
+ */
16
+ export declare function suggestEnvVars(mappings: PortMapping[]): Map<PortMapping, string>;
@@ -2,7 +2,11 @@ const ENV_VAR_PATTERN = /^\$\{([A-Z_][A-Z0-9_]*):-(\d+)\}$/;
2
2
  function stripProtocol(port) {
3
3
  return port.replace(/\/(tcp|udp|sctp)$/i, "");
4
4
  }
5
- function splitPortString(raw) {
5
+ /**
6
+ * Split a `ports:` string into its `:`-separated segments, keeping `${…}`
7
+ * interpolations whole. The protocol suffix (`/tcp`) is stripped first.
8
+ */
9
+ export function portSegments(raw) {
6
10
  const cleaned = stripProtocol(raw);
7
11
  const segments = [];
8
12
  let current = "";
@@ -32,6 +36,10 @@ function splitPortString(raw) {
32
36
  current += ch;
33
37
  }
34
38
  segments.push(current);
39
+ return segments;
40
+ }
41
+ function splitPortString(raw) {
42
+ const segments = portSegments(raw);
35
43
  if (segments.length === 1)
36
44
  return null;
37
45
  if (segments.length === 2)
@@ -46,9 +54,20 @@ function resolveEnvVar(segment) {
46
54
  return null;
47
55
  return { envVar: match[1], defaultPort: parseInt(match[2], 10) };
48
56
  }
57
+ /** `8000-8010`: a port range, which no single allocated port can replace. */
58
+ function rangeOf(segment) {
59
+ const m = /^\s*(\d+)\s*-\s*(\d+)\s*$/.exec(segment);
60
+ return m ? [Number(m[1]), Number(m[2])] : null;
61
+ }
62
+ /**
63
+ * A port number, or the first port of a range. Anything else — `${VAR}`
64
+ * without a default, `8000-${END:-8010}` — is null: its numeric prefix is
65
+ * not the port compose publishes.
66
+ */
49
67
  function resolvePort(segment) {
50
- const n = parseInt(segment, 10);
51
- return isNaN(n) ? null : n;
68
+ if (/^\s*\d+\s*$/.test(segment))
69
+ return Number(segment.trim());
70
+ return rangeOf(segment)?.[0] ?? null;
52
71
  }
53
72
  export function extractPortMappings(services) {
54
73
  const mappings = [];
@@ -73,13 +92,17 @@ export function extractPortMappings(services) {
73
92
  }
74
93
  else {
75
94
  const hostPort = resolvePort(split.host);
76
- if (hostPort !== null) {
95
+ const hostRange = rangeOf(split.host);
96
+ // Host port 0 asks the engine for any free port: it never collides.
97
+ if (hostPort !== null && hostPort !== 0) {
77
98
  mappings.push({
78
99
  serviceName: svc.name,
79
100
  envVar: null,
80
101
  defaultPort: hostPort,
81
102
  containerPort,
82
103
  raw,
104
+ ...(hostRange || rangeOf(split.container) ? { range: true } : {}),
105
+ ...(hostRange ? { rangeEnd: hostRange[1] } : {}),
83
106
  });
84
107
  }
85
108
  }
@@ -90,3 +113,24 @@ export function extractPortMappings(services) {
90
113
  export function suggestEnvVar(serviceName) {
91
114
  return `${serviceName.toUpperCase().replace(/[^A-Z0-9]/g, "_")}_PORT`;
92
115
  }
116
+ /**
117
+ * A variable name to suggest for each hardcoded mapping: `<SERVICE>_PORT`,
118
+ * or `<SERVICE>_<CONTAINER>_PORT` for a service's further ports, never one
119
+ * the compose file already uses (two ports sharing a name would get the
120
+ * same value).
121
+ */
122
+ export function suggestEnvVars(mappings) {
123
+ const taken = new Set(mappings.flatMap((m) => (m.envVar ? [m.envVar] : [])));
124
+ const out = new Map();
125
+ for (const m of mappings) {
126
+ if (m.envVar !== null)
127
+ continue;
128
+ const base = suggestEnvVar(m.serviceName);
129
+ let name = taken.has(base) ? base.replace(/_PORT$/, `_${m.containerPort}_PORT`) : base;
130
+ for (let n = 2; taken.has(name); n++)
131
+ name = `${base}_${n}`;
132
+ taken.add(name);
133
+ out.set(m, name);
134
+ }
135
+ return out;
136
+ }
@@ -1,13 +1,24 @@
1
1
  export interface PortMapping {
2
2
  serviceName: string;
3
+ /** `VAR` of a `${VAR:-port}` host port; null for a hardcoded host port. */
3
4
  envVar: string | null;
4
5
  defaultPort: number;
5
6
  containerPort: number;
6
7
  raw: string;
8
+ /** A host port range (`8000-8010:8000-8010`): never remapped. */
9
+ range?: boolean;
10
+ /** Last host port of a range (`defaultPort` is the first). */
11
+ rangeEnd?: number;
7
12
  }
8
13
  export interface PortAllocation {
9
14
  serviceName: string;
10
- envVar: string;
15
+ /**
16
+ * The variable the compose file reads this host port from, or null for a
17
+ * hardcoded host port that wtc remaps at runtime (no variable exists).
18
+ */
19
+ envVar: string | null;
11
20
  port: number;
12
21
  containerPort: number;
22
+ /** The host port the compose file publishes in the main checkout. */
23
+ defaultPort: number;
13
24
  }
@@ -25,6 +25,12 @@ export interface InjectOptions {
25
25
  * started instead of creating a new one named after the directory.
26
26
  */
27
27
  writeProjectName?: boolean;
28
+ /**
29
+ * Also write `COMPOSE_FILE=<value>` (root target only, when wtc remaps
30
+ * hardcoded ports or container names at runtime), so `docker compose`
31
+ * run by hand inside the worktree loads the same override wtc used.
32
+ */
33
+ composeFile?: string;
28
34
  /**
29
35
  * Directory the env file must stay inside (the worktree root). Defaults to
30
36
  * the file's own directory, which still protects the final component.
@@ -33,10 +39,20 @@ export interface InjectOptions {
33
39
  /** The pristine env source this file was copied from; never written, even via a hard link. */
34
40
  source?: string;
35
41
  }
42
+ /** Name of the compose file list variable (runtime remapping). */
43
+ export declare const COMPOSE_FILE_VAR = "COMPOSE_FILE";
44
+ /**
45
+ * A value compose reads back exactly, `$` included: single-quoted dotenv
46
+ * values are literal; one with a `'` in it is double-quoted, with `\`, `"`
47
+ * and `$` escaped (compose reads `\$` as a literal `$`).
48
+ */
49
+ export declare function literalEnvValue(value: string): string;
36
50
  /**
37
- * All keys that should be written for a target: the project name (root
38
- * target), allocated ports, then the target's overrides (already
39
- * interpolated). Overrides win on key conflicts.
51
+ * All keys that should be written for a target: the project name and
52
+ * compose file list (root target), allocated port variables, then the
53
+ * target's overrides (already interpolated). Overrides win on key
54
+ * conflicts. A remapped hardcoded port has no variable, so nothing is
55
+ * written for it.
40
56
  */
41
57
  export declare function buildOverrideEntries(allocations: PortAllocation[], overrides?: Record<string, string>, opts?: InjectOptions): Record<string, string>;
42
58
  export declare function buildOverrideBlock(allocations: PortAllocation[], envOverrides?: Record<string, string>): string;
package/dist/sync/env.js CHANGED
@@ -26,10 +26,24 @@ export function resolveOverrideValue(value, values) {
26
26
  }
27
27
  return result;
28
28
  }
29
+ /** Name of the compose file list variable (runtime remapping). */
30
+ export const COMPOSE_FILE_VAR = "COMPOSE_FILE";
29
31
  /**
30
- * All keys that should be written for a target: the project name (root
31
- * target), allocated ports, then the target's overrides (already
32
- * interpolated). Overrides win on key conflicts.
32
+ * A value compose reads back exactly, `$` included: single-quoted dotenv
33
+ * values are literal; one with a `'` in it is double-quoted, with `\`, `"`
34
+ * and `$` escaped (compose reads `\$` as a literal `$`).
35
+ */
36
+ export function literalEnvValue(value) {
37
+ if (!value.includes("'"))
38
+ return `'${value}'`;
39
+ return `"${value.replace(/[\\"$]/g, (c) => `\\${c}`)}"`;
40
+ }
41
+ /**
42
+ * All keys that should be written for a target: the project name and
43
+ * compose file list (root target), allocated port variables, then the
44
+ * target's overrides (already interpolated). Overrides win on key
45
+ * conflicts. A remapped hardcoded port has no variable, so nothing is
46
+ * written for it.
33
47
  */
34
48
  export function buildOverrideEntries(allocations, overrides, opts = {}) {
35
49
  const entries = {};
@@ -39,7 +53,11 @@ export function buildOverrideEntries(allocations, overrides, opts = {}) {
39
53
  entries[PROJECT_NAME_VAR] = opts.projectName;
40
54
  values.set(PROJECT_NAME_VAR, opts.projectName);
41
55
  }
56
+ if (opts.composeFile)
57
+ entries[COMPOSE_FILE_VAR] = literalEnvValue(opts.composeFile);
42
58
  for (const a of allocations) {
59
+ if (a.envVar === null)
60
+ continue;
43
61
  entries[a.envVar] = String(a.port);
44
62
  values.set(a.envVar, a.port);
45
63
  }
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "worktree-compose",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "Zero-config Docker Compose isolation for git worktrees",
5
5
  "type": "module",
6
6
  "bin": {
7
- "worktree-compose": "./dist/cli.js",
8
- "wtc": "./dist/cli.js"
7
+ "worktree-compose": "dist/cli.js",
8
+ "wtc": "dist/cli.js"
9
9
  },
10
10
  "files": [
11
11
  "dist",