worktree-compose 0.2.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/README.md +501 -143
  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 +26 -0
  27. package/dist/compose/isolation.js +91 -0
  28. package/dist/compose/override.d.ts +152 -0
  29. package/dist/compose/override.js +542 -0
  30. package/dist/compose/parse.d.ts +12 -0
  31. package/dist/compose/parse.js +199 -29
  32. package/dist/compose/status.d.ts +84 -0
  33. package/dist/compose/status.js +227 -0
  34. package/dist/compose/types.d.ts +43 -0
  35. package/dist/config.d.ts +31 -0
  36. package/dist/config.js +23 -6
  37. package/dist/context.d.ts +104 -3
  38. package/dist/context.js +299 -45
  39. package/dist/core/clean.d.ts +91 -0
  40. package/dist/core/clean.js +347 -0
  41. package/dist/core/compose.d.ts +92 -0
  42. package/dist/core/compose.js +195 -0
  43. package/dist/core/doctor.d.ts +29 -0
  44. package/dist/core/doctor.js +342 -0
  45. package/dist/core/list.d.ts +46 -0
  46. package/dist/core/list.js +101 -0
  47. package/dist/core/promote.d.ts +40 -0
  48. package/dist/core/promote.js +117 -0
  49. package/dist/core/prune.d.ts +32 -0
  50. package/dist/core/prune.js +79 -0
  51. package/dist/core/restart.d.ts +14 -0
  52. package/dist/core/restart.js +18 -0
  53. package/dist/core/start.d.ts +33 -0
  54. package/dist/core/start.js +113 -0
  55. package/dist/core/stop.d.ts +32 -0
  56. package/dist/core/stop.js +58 -0
  57. package/dist/core/teardown.d.ts +123 -0
  58. package/dist/core/teardown.js +305 -0
  59. package/dist/core/types.d.ts +15 -0
  60. package/dist/core/types.js +1 -0
  61. package/dist/git/promote.d.ts +49 -2
  62. package/dist/git/promote.js +160 -38
  63. package/dist/git/repo.d.ts +72 -0
  64. package/dist/git/repo.js +167 -0
  65. package/dist/git/status.d.ts +8 -0
  66. package/dist/git/status.js +25 -0
  67. package/dist/git/worktree.d.ts +63 -3
  68. package/dist/git/worktree.js +173 -29
  69. package/dist/mcp/server.d.ts +2 -0
  70. package/dist/mcp/server.js +230 -115
  71. package/dist/ports/allocate.d.ts +39 -5
  72. package/dist/ports/allocate.js +96 -16
  73. package/dist/ports/extract.d.ts +12 -0
  74. package/dist/ports/extract.js +48 -4
  75. package/dist/ports/types.d.ts +12 -1
  76. package/dist/selectors.d.ts +10 -0
  77. package/dist/selectors.js +106 -0
  78. package/dist/skill.d.ts +13 -0
  79. package/dist/skill.js +28 -0
  80. package/dist/state/registry.d.ts +194 -0
  81. package/dist/state/registry.js +595 -0
  82. package/dist/sync/env.d.ts +93 -2
  83. package/dist/sync/env.js +169 -32
  84. package/dist/sync/files.d.ts +15 -1
  85. package/dist/sync/files.js +126 -38
  86. package/dist/utils/exec.d.ts +69 -4
  87. package/dist/utils/exec.js +221 -15
  88. package/dist/utils/log.d.ts +37 -0
  89. package/dist/utils/log.js +68 -4
  90. package/dist/utils/paths.d.ts +61 -0
  91. package/dist/utils/paths.js +163 -0
  92. package/dist/utils/sanitize.d.ts +7 -0
  93. package/dist/utils/sanitize.js +12 -0
  94. package/dist/version.d.ts +1 -0
  95. package/dist/version.js +3 -0
  96. package/dist/workspaces/resolve.d.ts +21 -0
  97. package/dist/workspaces/resolve.js +235 -0
  98. package/package.json +20 -16
  99. package/wtc.schema.json +62 -0
@@ -0,0 +1,305 @@
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 { cliCall, isComposePlugin } from "../compose/engine.js";
8
+ import { COMPOSE_FILE_VAR } from "../sync/env.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, prepareStack } 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 — with the compose files the
57
+ * stack was started with (its runtime override, which is deleted when its
58
+ * record is forgotten). Fallbacks, in order:
59
+ * - plain `down -v` from the same directory (podman-compose < 1.0.6 rejects
60
+ * `--remove-orphans`, which would make every teardown fail);
61
+ * - for the Compose v2 plugin only, `down -v --remove-orphans` from an
62
+ * empty directory: it tears a project down by its labels alone when the
63
+ * compose file no longer parses. Standalone docker-compose v1 and
64
+ * podman-compose always need a compose file, so that retry cannot help.
65
+ * Anonymous volumes the containers mounted are removed afterwards.
66
+ */
67
+ export async function teardownStack(ctx, engine, target, io) {
68
+ const cwd = fs.existsSync(target.path) ? target.path : ctx.repoRoot;
69
+ let env;
70
+ try {
71
+ // The compose files the stack was started with (runtime override included).
72
+ const stack = prepareStack(ctx, { project: target.project, index: target.index, dir: cwd }, { write: false });
73
+ env = composeEnv(target.project, stack.allocations, stack.composeFile, ctx.repo.commonDir);
74
+ }
75
+ catch {
76
+ env = undefined;
77
+ }
78
+ // The label-only retry must not load any compose file, wtc's or an inherited list.
79
+ const labelsOnlyEnv = { ...env, [COMPOSE_FILE_VAR]: undefined };
80
+ const anonymous = anonymousVolumes(engine, target.project);
81
+ const call = { live: io.live, signal: io.signal, onLine: io.onOutput };
82
+ const attempts = [
83
+ { args: ["down", "-v", "--remove-orphans"], dir: () => cwd, env },
84
+ { args: ["down", "-v"], dir: () => cwd, env },
85
+ ];
86
+ if (isComposePlugin(engine)) {
87
+ attempts.push({
88
+ args: ["down", "-v", "--remove-orphans"],
89
+ dir: () => fs.mkdtempSync(path.join(os.tmpdir(), "wtc-down-")),
90
+ env: labelsOnlyEnv,
91
+ });
92
+ }
93
+ let firstError = null;
94
+ for (const attempt of attempts) {
95
+ if (io.signal?.aborted)
96
+ break;
97
+ const dir = attempt.dir();
98
+ try {
99
+ await composeRun(engine, target.project, attempt.args, { ...call, env: attempt.env, cwd: dir });
100
+ for (const volume of anonymous) {
101
+ const [file, args] = cliCall(engine, "volume", "rm", volume);
102
+ runSafe(file, args, { timeoutMs: ENGINE_PROBE_TIMEOUT_MS });
103
+ }
104
+ return { ok: true };
105
+ }
106
+ catch (err) {
107
+ firstError ??= err;
108
+ }
109
+ finally {
110
+ if (dir !== cwd)
111
+ fs.rmSync(dir, { recursive: true, force: true });
112
+ }
113
+ }
114
+ return {
115
+ ok: false,
116
+ error: firstError instanceof Error ? firstError.message : String(firstError ?? "cancelled"),
117
+ };
118
+ }
119
+ /**
120
+ * Re-check an orphan right before tearing it down, with a fresh `git
121
+ * worktree list`: another wtc process (or `git worktree repair` / a moved
122
+ * directory coming back) may have made its worktree live again since the
123
+ * context was built, and `down -v` would then destroy a live stack's data.
124
+ * Same identity rules as reconcile: a record is live when a worktree holds
125
+ * its id, or sits at its path without a conflicting id (a new worktree at a
126
+ * reused path is not the old one, so the orphan can still be pruned).
127
+ * Returns null when the orphan is still gone, else why it must be skipped.
128
+ */
129
+ export function orphanSkipReason(ctx, record) {
130
+ let listed;
131
+ try {
132
+ listed = listRepoWorktrees(ctx.repo);
133
+ }
134
+ catch (err) {
135
+ return `could not re-check its worktree (${err instanceof Error ? err.message.split("\n")[0] : String(err)})`;
136
+ }
137
+ return recordIsLive(record, listed) ? `its worktree (${record.path}) exists again; run 'wtc list' to see it` : null;
138
+ }
139
+ const defaultRunner = (file, args) => run(file, args, { timeoutMs: ENGINE_PROBE_TIMEOUT_MS });
140
+ const KINDS = [
141
+ {
142
+ key: "containers",
143
+ label: "container",
144
+ list: ["ps", "-a", "--format", "json"],
145
+ remove: (id) => ["rm", "-f", id],
146
+ },
147
+ {
148
+ key: "networks",
149
+ label: "network",
150
+ list: ["network", "ls", "--format", "json"],
151
+ remove: (id) => ["network", "rm", id],
152
+ },
153
+ {
154
+ key: "volumes",
155
+ label: "volume",
156
+ list: ["volume", "ls", "--format", "json"],
157
+ remove: (id) => ["volume", "rm", id],
158
+ },
159
+ ];
160
+ function parseResources(kind, output) {
161
+ if (kind.key === "containers") {
162
+ return parsePsContainers(output).map((c) => ({
163
+ id: c.id || c.name,
164
+ name: c.name,
165
+ project: c.project,
166
+ }));
167
+ }
168
+ return parseJsonListing(output).map((entry) => {
169
+ const labels = labelsOf(entry);
170
+ const name = String(field(entry, "Name") ?? "");
171
+ // Volumes are removed by name; networks by id when there is one.
172
+ const id = kind.key === "networks" ? String(field(entry, "ID") ?? "") || name : name;
173
+ return { id, name, project: PROJECT_LABELS.map((l) => labels[l]).find(Boolean) ?? null };
174
+ });
175
+ }
176
+ /**
177
+ * Remove leftover containers, networks and volumes of this repository's
178
+ * worktree stacks — never another checkout's.
179
+ *
180
+ * A name like `<repo>-wt-<n>-…` proves nothing: the prefix is the checkout
181
+ * directory's basename, which a second clone (or an unrelated repo also
182
+ * called `api`) shares. Ownership comes from compose's labels instead. A
183
+ * project is *owned* when it is in this repository's registry, or when it
184
+ * is a `<repo>-wt-<n>-` project one of whose containers ran
185
+ * (`project.working_dir`) from the main checkout (or below it), a current
186
+ * worktree, or a registry path. Only resources whose project label is owned
187
+ * are removed, one at a time (a volume still in use cannot discard the rest).
188
+ *
189
+ * Name-matching projects that are not owned are kept and listed, in two
190
+ * groups: *stale* ones, whose working directory no longer exists (removed
191
+ * with `sweep`), and the rest — whose directory exists (another checkout),
192
+ * or which have nothing to attribute them by — which are never removed.
193
+ */
194
+ export function sweepStaleResources(cliArgv, repoName, opts = {}) {
195
+ const runner = opts.runner ?? defaultRunner;
196
+ const dirExists = opts.dirExists ?? ((dir) => fs.existsSync(dir));
197
+ // An empty prefix (a repo name with no ASCII letters/digits) would match
198
+ // every repository's `wt-<n>-` stacks: no name-based matching at all then.
199
+ const namePattern = sanitize(repoName) ? worktreeResourcePattern(repoName) : null;
200
+ const nameMatches = (name) => !!name && !!namePattern && namePattern.test(name);
201
+ const skip = new Set(opts.skipProjects ?? []);
202
+ const result = {
203
+ containers: { removed: [], failed: [] },
204
+ networks: { removed: [], failed: [] },
205
+ volumes: { removed: [], failed: [] },
206
+ stale: [],
207
+ notOwned: [],
208
+ };
209
+ const listings = new Map();
210
+ const containerDirs = new Map();
211
+ for (const kind of KINDS) {
212
+ try {
213
+ const output = runner(cliArgv[0], [...cliArgv.slice(1), ...kind.list]);
214
+ listings.set(kind.key, parseResources(kind, output));
215
+ if (kind.key === "containers") {
216
+ for (const c of parsePsContainers(output)) {
217
+ if (!c.project || !c.workingDir)
218
+ continue;
219
+ const dirs = containerDirs.get(c.project) ?? new Set();
220
+ dirs.add(c.workingDir);
221
+ containerDirs.set(c.project, dirs);
222
+ }
223
+ }
224
+ }
225
+ catch (err) {
226
+ result.error = err instanceof Error ? err.message : String(err);
227
+ opts.reporter?.warn(`Could not list ${kind.label}s: ${result.error.split("\n")[0]}`);
228
+ }
229
+ }
230
+ // Attribute `<repo>-wt-<n>-` projects by where their containers ran.
231
+ const owned = new Set(opts.registryProjects ?? []);
232
+ const stale = new Set();
233
+ const real = (p) => {
234
+ try {
235
+ return fs.realpathSync.native(p);
236
+ }
237
+ catch {
238
+ return path.resolve(p);
239
+ }
240
+ };
241
+ const mainRoot = opts.mainRoot;
242
+ const ours = (dir) => (mainRoot !== undefined && (isWithin(mainRoot, dir) || isWithin(real(mainRoot), real(dir)))) ||
243
+ (opts.checkouts ?? []).some((c) => samePath(c, dir));
244
+ for (const [project, dirs] of containerDirs) {
245
+ if (owned.has(project) || !nameMatches(project))
246
+ continue;
247
+ if ([...dirs].some(ours))
248
+ owned.add(project);
249
+ else if (![...dirs].some(dirExists))
250
+ stale.add(project);
251
+ }
252
+ const groupOf = (r) => {
253
+ if (r.project !== null && owned.has(r.project))
254
+ return "owned";
255
+ if (!nameMatches(r.name) && !nameMatches(r.project))
256
+ return null;
257
+ return r.project !== null && stale.has(r.project) ? "stale" : "notOwned";
258
+ };
259
+ for (const kind of KINDS) {
260
+ for (const r of listings.get(kind.key) ?? []) {
261
+ if (r.project !== null && skip.has(r.project))
262
+ continue;
263
+ const group = groupOf(r);
264
+ if (group === null)
265
+ continue;
266
+ const label = `${kind.label} ${r.name}`;
267
+ if (group === "notOwned") {
268
+ result.notOwned.push(label);
269
+ continue;
270
+ }
271
+ if (group === "stale") {
272
+ result.stale.push(label);
273
+ if (!opts.sweep)
274
+ continue;
275
+ }
276
+ const why = group === "stale" ? " (its worktree directory is gone)" : "";
277
+ if (opts.dryRun) {
278
+ opts.reporter?.info(`Would remove leftover ${label}${why}`);
279
+ result[kind.key].removed.push(r.name);
280
+ continue;
281
+ }
282
+ try {
283
+ runner(cliArgv[0], [...cliArgv.slice(1), ...kind.remove(r.id)]);
284
+ result[kind.key].removed.push(r.name);
285
+ opts.reporter?.info(`Removed leftover ${label}${why}`);
286
+ }
287
+ catch (err) {
288
+ result[kind.key].failed.push(r.name);
289
+ const reason = err instanceof Error ? err.message.split("\n").slice(-1)[0] : String(err);
290
+ opts.reporter?.warn(`Could not remove ${label}: ${reason}`);
291
+ }
292
+ }
293
+ }
294
+ if (result.stale.length > 0 && !opts.sweep) {
295
+ opts.reporter?.warn(`Kept ${result.stale.length} leftover resource(s) of worktree stacks whose directory no longer exists ` +
296
+ `(e.g. left by wtc ≤0.2): ${result.stale.join(", ")}. ` +
297
+ `Remove them with 'wtc clean --sweep' (preview with --dry-run).`);
298
+ }
299
+ if (result.notOwned.length > 0) {
300
+ opts.reporter?.warn(`Kept ${result.notOwned.length} resource(s) named like this repo's worktree stacks that this checkout ` +
301
+ `does not own (another checkout with the same directory name, or nothing to attribute them by): ` +
302
+ `${result.notOwned.join(", ")}. wtc never removes these; remove them yourself if they are yours.`);
303
+ }
304
+ return result;
305
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * How an operation talks to the outside world. The CLI streams compose output
3
+ * to the terminal; the MCP server captures it (stdout is its JSON-RPC
4
+ * channel) and keeps the event loop free while compose runs.
5
+ */
6
+ export interface CoreIo {
7
+ /** Inherit stdio for compose (CLI) instead of capturing output (MCP). */
8
+ live: boolean;
9
+ /** Directory wtc runs from: locates the repo and resolves `.` selectors. */
10
+ cwd?: string;
11
+ /** Cancels running compose commands (an MCP client's cancellation). */
12
+ signal?: AbortSignal;
13
+ /** Receives captured compose output lines (MCP progress), when not `live`. */
14
+ onOutput?: (line: string) => void;
15
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -1,4 +1,51 @@
1
- export declare function getChangedFiles(repoRoot: string, wtPath: string, currentBranch: string, wtBranch: string): string[];
1
+ /** Root compose filenames; wtc overwrites these in every worktree. */
2
+ export declare const PROMOTE_EXCLUDES: Set<string>;
3
+ /**
4
+ * Local env files are excluded from promote — wtc rewrites them with
5
+ * per-worktree ports: `.env`, `.env.development`, `.env.local`, …
6
+ */
7
+ export declare function isEnvFile(file: string): boolean;
8
+ /** Split NUL-terminated git output (`-z`) into paths. */
9
+ export declare function splitNul(output: string): string[];
10
+ /** Resolve a ref to a commit id, or throw a readable error. */
11
+ export declare function resolveCommit(cwd: string, ref: string): string;
12
+ /** Merge-base of the target checkout's HEAD and the worktree's HEAD. */
13
+ export declare function getMergeBase(targetRoot: string, wtPath: string): string;
14
+ /**
15
+ * Files the target branch itself changed (committed) since `mergeBase`.
16
+ * Promote copies whole files, so for a file both sides changed it would
17
+ * silently revert the target's commits.
18
+ */
19
+ export declare function getTargetChangedFiles(targetRoot: string, mergeBase: string): string[];
20
+ /**
21
+ * Files a worktree changed relative to its merge-base with `targetRoot`'s
22
+ * HEAD: committed + staged + unstaged changes in one `git diff <merge-base>`
23
+ * (merge-base vs working tree), plus untracked files. `-z` keeps non-ASCII
24
+ * names intact (otherwise `core.quotePath` turns `café.txt` into a quoted
25
+ * escape that matches no file); `--no-renames` reports a rename as delete +
26
+ * add so the old path is removed from the target too.
27
+ */
28
+ export declare function getChangedFiles(targetRoot: string, wtPath: string, excludes?: Set<string>, mergeBase?: string): string[];
29
+ /**
30
+ * Paths in the target checkout that promote must not overwrite: tracked
31
+ * changes (staged or unstaged) AND untracked files — an untracked file in
32
+ * main is just as much unsaved work.
33
+ */
2
34
  export declare function getLocalDirtyFiles(repoRoot: string): string[];
3
35
  export declare function findConflicts(files: string[], dirtyFiles: string[]): string[];
4
- export declare function promoteFiles(repoRoot: string, wtPath: string, files: string[]): void;
36
+ /**
37
+ * Validate every path before anything is written (all-or-nothing): each must
38
+ * stay inside both roots lexically *and* physically — see `assertContained`.
39
+ */
40
+ export declare function assertPromotable(targetRoot: string, wtPath: string, files: string[]): void;
41
+ /**
42
+ * Copy (or delete) each changed file from the worktree into the target.
43
+ * Every path is validated up front (`assertPromotable`) and re-checked
44
+ * before each write — a symlink created earlier in the same run must not be
45
+ * followed either. A symlink at the final component in the target is
46
+ * replaced (unlinked) on write and removed (unlinked, not followed) on
47
+ * delete. Deletions run first. Symlinks are recreated as symlinks. Returns
48
+ * paths that were skipped (directories such as submodules, non-empty
49
+ * directories in the way of a file or symlink).
50
+ */
51
+ export declare function promoteFiles(repoRoot: string, wtPath: string, files: string[]): string[];
@@ -1,58 +1,180 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
- import { exec, execSafe } from "../utils/exec.js";
4
- const PROMOTE_EXCLUDES = new Set([
5
- ".env",
3
+ import { run } from "../utils/exec.js";
4
+ import { parentPlacement, resolveInside, symlinkAncestor } from "../utils/paths.js";
5
+ /** Root compose filenames; wtc overwrites these in every worktree. */
6
+ export const PROMOTE_EXCLUDES = new Set([
6
7
  "docker-compose.yml",
7
8
  "docker-compose.yaml",
8
9
  "compose.yml",
9
10
  "compose.yaml",
10
11
  ]);
11
- function resolveRef(repoRoot, ref) {
12
- return exec(`git -C "${repoRoot}" rev-parse "${ref}"`);
13
- }
14
- export function getChangedFiles(repoRoot, wtPath, currentBranch, wtBranch) {
15
- const currentRef = resolveRef(repoRoot, currentBranch === "HEAD" ? "HEAD" : currentBranch);
16
- const wtRef = resolveRef(wtPath, "HEAD");
17
- const mergeBase = exec(`git -C "${repoRoot}" merge-base "${currentRef}" "${wtRef}"`);
18
- const committed = execSafe(`git -C "${wtPath}" diff --name-only "${mergeBase}" HEAD`) ?? "";
19
- let uncommitted = "";
20
- const hasStagedOrUnstaged = execSafe(`git -C "${wtPath}" diff --quiet`) === null ||
21
- execSafe(`git -C "${wtPath}" diff --cached --quiet`) === null;
22
- if (hasStagedOrUnstaged) {
23
- uncommitted = execSafe(`git -C "${wtPath}" diff --name-only HEAD`) ?? "";
24
- }
25
- const untracked = execSafe(`git -C "${wtPath}" ls-files --others --exclude-standard`) ?? "";
26
- const allFiles = [committed, uncommitted, untracked]
27
- .join("\n")
28
- .split("\n")
29
- .map((f) => f.trim())
30
- .filter(Boolean);
31
- const unique = [...new Set(allFiles)];
32
- return unique.filter((f) => !PROMOTE_EXCLUDES.has(f));
12
+ /** Committed env templates; wtc never writes these, so they stay promotable. */
13
+ const ENV_TEMPLATES = new Set([
14
+ ".env.example",
15
+ ".env.sample",
16
+ ".env.template",
17
+ ".env.dist",
18
+ ".env.defaults",
19
+ ]);
20
+ /**
21
+ * Local env files are excluded from promote — wtc rewrites them with
22
+ * per-worktree ports: `.env`, `.env.development`, `.env.local`, …
23
+ */
24
+ export function isEnvFile(file) {
25
+ const base = path.posix.basename(file);
26
+ if (ENV_TEMPLATES.has(base))
27
+ return false;
28
+ return base === ".env" || base.startsWith(".env.");
29
+ }
30
+ /** Split NUL-terminated git output (`-z`) into paths. */
31
+ export function splitNul(output) {
32
+ return output.split("\0").filter(Boolean);
33
+ }
34
+ /** Like `run`, but keeps NUL separators and trailing whitespace in paths intact. */
35
+ function gitPaths(cwd, args) {
36
+ return splitNul(run("git", ["-C", cwd, ...args], { trim: false }));
37
+ }
38
+ /** Resolve a ref to a commit id, or throw a readable error. */
39
+ export function resolveCommit(cwd, ref) {
40
+ try {
41
+ return run("git", ["-C", cwd, "rev-parse", "--verify", "--quiet", `${ref}^{commit}`]);
42
+ }
43
+ catch {
44
+ throw new Error(`Cannot resolve ${ref} to a commit in ${cwd} (no commits yet?).`);
45
+ }
33
46
  }
47
+ /** Merge-base of the target checkout's HEAD and the worktree's HEAD. */
48
+ export function getMergeBase(targetRoot, wtPath) {
49
+ const targetHead = resolveCommit(targetRoot, "HEAD");
50
+ const wtHead = resolveCommit(wtPath, "HEAD");
51
+ return run("git", ["-C", targetRoot, "merge-base", targetHead, wtHead]);
52
+ }
53
+ /**
54
+ * Files the target branch itself changed (committed) since `mergeBase`.
55
+ * Promote copies whole files, so for a file both sides changed it would
56
+ * silently revert the target's commits.
57
+ */
58
+ export function getTargetChangedFiles(targetRoot, mergeBase) {
59
+ return gitPaths(targetRoot, ["diff", "--name-only", "-z", "--no-renames", mergeBase, "HEAD", "--"]);
60
+ }
61
+ /**
62
+ * Files a worktree changed relative to its merge-base with `targetRoot`'s
63
+ * HEAD: committed + staged + unstaged changes in one `git diff <merge-base>`
64
+ * (merge-base vs working tree), plus untracked files. `-z` keeps non-ASCII
65
+ * names intact (otherwise `core.quotePath` turns `café.txt` into a quoted
66
+ * escape that matches no file); `--no-renames` reports a rename as delete +
67
+ * add so the old path is removed from the target too.
68
+ */
69
+ export function getChangedFiles(targetRoot, wtPath, excludes = PROMOTE_EXCLUDES, mergeBase = getMergeBase(targetRoot, wtPath)) {
70
+ const changed = gitPaths(wtPath, ["diff", "--name-only", "-z", "--no-renames", mergeBase, "--"]);
71
+ const untracked = gitPaths(wtPath, ["ls-files", "--others", "--exclude-standard", "-z"]);
72
+ const unique = [...new Set([...changed, ...untracked])];
73
+ return unique.filter((f) => !excludes.has(f) && !isEnvFile(f));
74
+ }
75
+ /**
76
+ * Paths in the target checkout that promote must not overwrite: tracked
77
+ * changes (staged or unstaged) AND untracked files — an untracked file in
78
+ * main is just as much unsaved work.
79
+ */
34
80
  export function getLocalDirtyFiles(repoRoot) {
35
- const unstaged = execSafe(`git -C "${repoRoot}" diff --name-only HEAD`) ?? "";
36
- const staged = execSafe(`git -C "${repoRoot}" diff --cached --name-only HEAD`) ?? "";
37
- return [...new Set([unstaged, staged].join("\n").split("\n"))]
38
- .map((f) => f.trim())
39
- .filter(Boolean);
81
+ const tracked = gitPaths(repoRoot, ["diff", "--name-only", "-z", "--no-renames", "HEAD", "--"]);
82
+ const untracked = gitPaths(repoRoot, ["ls-files", "--others", "--exclude-standard", "-z"]);
83
+ return [...new Set([...tracked, ...untracked])];
40
84
  }
41
85
  export function findConflicts(files, dirtyFiles) {
42
86
  const dirtySet = new Set(dirtyFiles);
43
87
  return files.filter((f) => dirtySet.has(f));
44
88
  }
89
+ /**
90
+ * Throw when promoting `rel` would pass through a symlink on either side.
91
+ * Target: a symlinked (or non-directory) ancestor would make the write or
92
+ * delete land outside the checkout (`data -> /var/shared`), and the realpath
93
+ * of the directory that will hold the file must stay inside the target.
94
+ * Worktree: content is never read through a symlinked directory the branch
95
+ * planted (`config -> ~/.ssh`).
96
+ */
97
+ function assertContained(targetRoot, wtPath, rel) {
98
+ if (!resolveInside(wtPath, rel) || !resolveInside(targetRoot, rel)) {
99
+ throw new Error(`Refusing to promote "${rel}": path escapes the repository.`);
100
+ }
101
+ const targetLink = symlinkAncestor(targetRoot, rel);
102
+ if (targetLink) {
103
+ throw new Error(`Refusing to promote "${rel}": ${targetLink} in the target is a symlink (or not a directory), so the file would land outside the checkout. Replace it with a real directory first.`);
104
+ }
105
+ if (parentPlacement(targetRoot, rel) !== "inside") {
106
+ throw new Error(`Refusing to promote "${rel}": its directory resolves outside the target checkout.`);
107
+ }
108
+ const wtLink = symlinkAncestor(wtPath, rel);
109
+ if (wtLink) {
110
+ throw new Error(`Refusing to promote "${rel}": ${wtLink} in the worktree is a symlink (or not a directory); promote never reads through one. Apply that change to the target by hand.`);
111
+ }
112
+ }
113
+ /**
114
+ * Validate every path before anything is written (all-or-nothing): each must
115
+ * stay inside both roots lexically *and* physically — see `assertContained`.
116
+ */
117
+ export function assertPromotable(targetRoot, wtPath, files) {
118
+ for (const f of files)
119
+ assertContained(targetRoot, wtPath, f);
120
+ }
121
+ /**
122
+ * Copy (or delete) each changed file from the worktree into the target.
123
+ * Every path is validated up front (`assertPromotable`) and re-checked
124
+ * before each write — a symlink created earlier in the same run must not be
125
+ * followed either. A symlink at the final component in the target is
126
+ * replaced (unlinked) on write and removed (unlinked, not followed) on
127
+ * delete. Deletions run first. Symlinks are recreated as symlinks. Returns
128
+ * paths that were skipped (directories such as submodules, non-empty
129
+ * directories in the way of a file or symlink).
130
+ */
45
131
  export function promoteFiles(repoRoot, wtPath, files) {
46
- for (const f of files) {
47
- const src = path.join(wtPath, f);
48
- const dst = path.join(repoRoot, f);
49
- if (fs.existsSync(src)) {
50
- fs.mkdirSync(path.dirname(dst), { recursive: true });
51
- fs.copyFileSync(src, dst);
132
+ assertPromotable(repoRoot, wtPath, files);
133
+ const resolved = files.map((f) => {
134
+ const src = path.resolve(wtPath, f);
135
+ const dst = path.resolve(repoRoot, f);
136
+ return { f, src, dst, stat: fs.lstatSync(src, { throwIfNoEntry: false }) };
137
+ });
138
+ const skipped = [];
139
+ const deletions = resolved.filter((r) => !r.stat);
140
+ const writes = resolved.filter((r) => r.stat);
141
+ for (const { f, dst } of deletions) {
142
+ assertContained(repoRoot, wtPath, f);
143
+ const existing = fs.lstatSync(dst, { throwIfNoEntry: false });
144
+ if (!existing)
145
+ continue;
146
+ if (existing.isDirectory()) {
147
+ skipped.push(f);
148
+ continue;
149
+ }
150
+ fs.unlinkSync(dst);
151
+ }
152
+ for (const { f, src, dst, stat } of writes) {
153
+ if (!stat.isFile() && !stat.isSymbolicLink()) {
154
+ skipped.push(f);
155
+ continue;
156
+ }
157
+ assertContained(repoRoot, wtPath, f);
158
+ fs.mkdirSync(path.dirname(dst), { recursive: true });
159
+ const existing = fs.lstatSync(dst, { throwIfNoEntry: false });
160
+ if (existing?.isDirectory()) {
161
+ // A file or symlink replacing a directory: only an empty one can go.
162
+ if (fs.readdirSync(dst).length > 0) {
163
+ skipped.push(f);
164
+ continue;
165
+ }
166
+ fs.rmdirSync(dst);
167
+ }
168
+ else if (existing && (stat.isSymbolicLink() || !existing.isFile())) {
169
+ // Never write through a symlink (or into a FIFO) sitting at the path.
170
+ fs.unlinkSync(dst);
171
+ }
172
+ if (stat.isSymbolicLink()) {
173
+ fs.symlinkSync(fs.readlinkSync(src), dst);
52
174
  }
53
175
  else {
54
- if (fs.existsSync(dst))
55
- fs.unlinkSync(dst);
176
+ fs.copyFileSync(src, dst);
56
177
  }
57
178
  }
179
+ return skipped;
58
180
  }