@coding-with-hassan/devkit 0.4.0 → 1.0.0-next.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.
@@ -0,0 +1,564 @@
1
+ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
2
+ import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
3
+ import { loadProfiles } from './compose.js';
4
+ import { CONFIG_KEY, ENV_DIST_FILE, ENV_FILE } from './config.js';
5
+ import { expandEnv, imageTag, imageTagInputs, sanitizeName } from './derive.js';
6
+ import { managedValues, parseEnv, writeManagedBlock } from './env-block.js';
7
+ import { commandExists, run } from './exec.js';
8
+ import * as git from './git.js';
9
+ import { withLock } from './locks.js';
10
+ import * as stack from './stack.js';
11
+ import { startTicket } from './tracker/index.js';
12
+ import { listProjects } from './workspace.js';
13
+
14
+ /**
15
+ * Parallel-development worktrees: one per ticket, each with its own Docker stack (own
16
+ * compose project, host ports and volumes) sharing the dev images with every other
17
+ * checkout on the same dependency manifest. Port of car-rental's `scripts/worktree.sh`.
18
+ *
19
+ * Pure decision functions come first (tested); the orchestration below composes them with
20
+ * git/docker/pnpm side effects. A repo without a compose file gets worktrees without a
21
+ * stack: no `.env`, no slot, no images — just branch + install + tracker.
22
+ */
23
+
24
+ // ───────────────────────── pure ─────────────────────────
25
+
26
+ /** Compose project of a checkout: slot 0 keeps the configured name; others use the branch. */
27
+ export function projectNameFor({ slot, branch, projectName }) {
28
+ if (slot === 0) return projectName;
29
+ const fromBranch = String(branch ?? '')
30
+ .toLowerCase()
31
+ .replace(/[^a-z0-9_-]/g, '-');
32
+ return fromBranch || `${projectName}-wt${slot}`;
33
+ }
34
+
35
+ /**
36
+ * Validate + order a requested profile list: required profiles first (always present),
37
+ * then the rest in the compose file's order; unknown names throw. With no profiles in
38
+ * the compose file the result is always `[]`.
39
+ */
40
+ export function normalizeProfiles(requested, { known, required }) {
41
+ if (known.length === 0) return [];
42
+ const wanted = new Set(
43
+ (Array.isArray(requested) ? requested : String(requested ?? '').split(','))
44
+ .map((p) => p.trim())
45
+ .filter(Boolean),
46
+ );
47
+ for (const p of wanted) {
48
+ if (!known.includes(p)) throw new Error(`unknown profile '${p}' (known: ${known.join(' ')})`);
49
+ }
50
+ for (const r of required) wanted.add(r);
51
+ return [...required.filter((r) => wanted.has(r)), ...known.filter((k) => wanted.has(k) && !required.includes(k))];
52
+ }
53
+
54
+ /** Lowest slot in 1..maxSlot not in `used` (slot 0 is the main checkout). */
55
+ export function pickFreeSlot(used, maxSlot) {
56
+ const taken = new Set([0, ...used.map(Number)]);
57
+ for (let s = 1; s <= maxSlot; s++) if (!taken.has(s)) return s;
58
+ throw new Error(`no free slot (all ${maxSlot} in use) — remove a worktree first`);
59
+ }
60
+
61
+ export function validateSlot(value, maxSlot) {
62
+ const n = Number(value);
63
+ if (!/^\d+$/.test(String(value)) || n < 1 || n > maxSlot) {
64
+ throw new Error(`slot must be a number 1-${maxSlot} (0 is the main checkout), got '${value}'`);
65
+ }
66
+ return n;
67
+ }
68
+
69
+ /** Image repository of a `repo[:tag]` reference (registry ports are not tags). */
70
+ export function imageRepo(ref) {
71
+ const slash = ref.lastIndexOf('/');
72
+ const colon = ref.lastIndexOf(':');
73
+ return colon > slash ? ref.slice(0, colon) : ref;
74
+ }
75
+
76
+ /** `{ service, image }` for every buildable service of the active profiles at `tag`. */
77
+ export function imagesFor(compose, profiles, tag) {
78
+ const out = [];
79
+ const seen = new Set();
80
+ const active = new Set(profiles);
81
+ for (const [service, svc] of Object.entries(compose.services)) {
82
+ if (!svc.build || !svc.image) continue;
83
+ const inScope = svc.profiles.length === 0 || svc.profiles.some((p) => active.has(p));
84
+ if (!inScope || seen.has(service)) continue;
85
+ seen.add(service);
86
+ out.push({ service, image: `${imageRepo(svc.image)}:${tag}` });
87
+ }
88
+ return out.sort((a, b) => a.service.localeCompare(b.service));
89
+ }
90
+
91
+ /** Repositories of every buildable service (the dev images this repo owns). */
92
+ export function ownedImageRepos(compose) {
93
+ return [...new Set(Object.values(compose.services).filter((s) => s.build && s.image).map((s) => imageRepo(s.image)))].sort();
94
+ }
95
+
96
+ /** node_modules volumes of `project` that belong to another image tag. */
97
+ export function staleVolumes(volumes, project, tag) {
98
+ const re = new RegExp(`^${escapeRe(project)}_.*_node_modules_`);
99
+ return volumes.filter((v) => re.test(v) && !v.endsWith(`_node_modules_${tag}`));
100
+ }
101
+
102
+ /** Every node_modules volume of `project` (for a full teardown). */
103
+ export function projectVolumes(volumes, project) {
104
+ const re = new RegExp(`^${escapeRe(project)}_.*_node_modules_`);
105
+ return volumes.filter((v) => re.test(v));
106
+ }
107
+
108
+ /** Owned dev images whose tag no checkout references and no container uses. */
109
+ export function unreferencedImages(images, { repos, referencedTags, inUse }) {
110
+ const referenced = new Set(['latest', ...referencedTags]);
111
+ const used = new Set(inUse);
112
+ const owned = new Set(repos);
113
+ return images.filter((img) => owned.has(imageRepo(img)) && !referenced.has(img.slice(imageRepo(img).length + 1)) && !used.has(img));
114
+ }
115
+
116
+ /** What `prune` does with a worktree given the `gh pr list` state summary. */
117
+ export function pruneDecision(states) {
118
+ if (states === null) return 'error';
119
+ if (states === '') return 'none';
120
+ if (states.includes('OPEN')) return 'open';
121
+ if (states.includes('MERGED')) return 'merged';
122
+ return 'closed';
123
+ }
124
+
125
+ /** Dockerfiles of the buildable services, relative to `root` (extra image-tag inputs). */
126
+ export function dockerfilesFromCompose(compose, root) {
127
+ const files = new Set();
128
+ for (const svc of Object.values(compose?.services ?? {})) {
129
+ if (!svc.build) continue;
130
+ const context = svc.build.context ?? '.';
131
+ const dockerfile = svc.build.dockerfile ?? 'Dockerfile';
132
+ const abs = isAbsolute(dockerfile) ? dockerfile : resolve(isAbsolute(context) ? context : join(root, context), dockerfile);
133
+ const rel = relative(root, abs).split('\\').join('/');
134
+ if (!rel.startsWith('..')) files.add(rel);
135
+ }
136
+ return [...files].sort();
137
+ }
138
+
139
+ const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
140
+
141
+ // ───────────────────────── context ─────────────────────────
142
+
143
+ /**
144
+ * Everything the commands need, resolved once. `hasStack` is false when the repo has no
145
+ * compose file; then every docker/env step is skipped.
146
+ */
147
+ export function createContext(loaded, { log = console.log, note = (m) => console.error(`note: ${m}`) } = {}) {
148
+ const { root, rootName, config } = loaded;
149
+ const wt = config.worktree;
150
+ if (!wt) throw new Error(`Missing "${CONFIG_KEY}.worktree" in ${join(root, 'package.json')} — add it (or run \`hassan-devkit init\`).`);
151
+ const main = git.mainRoot(root);
152
+ const baseDir = resolve(main, wt.baseDir);
153
+ const hasStack = stack.hasComposeFile(root);
154
+ let compose = null;
155
+ if (hasStack) {
156
+ compose = loadProfiles(root);
157
+ for (const r of wt.profiles.required) {
158
+ if (!(r in compose.profiles)) throw new Error(`${CONFIG_KEY}.worktree.profiles.required names "${r}", but the compose file has no service with that profile`);
159
+ }
160
+ }
161
+ const known = compose ? Object.keys(compose.profiles) : [];
162
+ return {
163
+ root,
164
+ mainRoot: main,
165
+ baseDir,
166
+ rootName,
167
+ wt,
168
+ tracker: config.tracker,
169
+ hasStack,
170
+ compose,
171
+ known,
172
+ log,
173
+ note,
174
+ };
175
+ }
176
+
177
+ // ───────────────────────── .env bookkeeping ─────────────────────────
178
+
179
+ export function envOf(dir) {
180
+ const file = join(dir, ENV_FILE);
181
+ return existsSync(file) ? parseEnv(readFileSync(file, 'utf8')) : {};
182
+ }
183
+
184
+ /** `[{ dir, env }]` for the main checkout and every worktree under baseDir that has a .env. */
185
+ export function allCheckouts(ctx) {
186
+ const dirs = [ctx.mainRoot];
187
+ if (existsSync(ctx.baseDir)) {
188
+ for (const entry of readdirSync(ctx.baseDir, { withFileTypes: true })) {
189
+ if (entry.isDirectory() && !entry.name.startsWith('.')) dirs.push(join(ctx.baseDir, entry.name));
190
+ }
191
+ }
192
+ return dirs.filter((d) => existsSync(join(d, ENV_FILE))).map((d) => ({ dir: d, env: envOf(d) }));
193
+ }
194
+
195
+ export function slotHolders(ctx, slot, exclude) {
196
+ return allCheckouts(ctx)
197
+ .filter(({ dir, env }) => env.DEVKIT_SLOT === String(slot) && (!exclude || resolve(dir) !== resolve(exclude)))
198
+ .map(({ dir }) => basename(dir));
199
+ }
200
+
201
+ export function usedSlots(ctx) {
202
+ return allCheckouts(ctx)
203
+ .filter(({ dir }) => resolve(dir) !== resolve(ctx.mainRoot))
204
+ .map(({ env }) => env.DEVKIT_SLOT)
205
+ .filter((s) => s !== undefined && s !== '');
206
+ }
207
+
208
+ function currentImageTag(ctx, dir) {
209
+ const projects = listProjects(dir);
210
+ const inputs = imageTagInputs(dir, projects, dockerfilesFromCompose(ctx.compose, dir));
211
+ if (inputs.length === 0) throw new Error(`cannot hash the dev image inputs: ${dir} is not a checkout of this repo`);
212
+ return imageTag(dir, inputs);
213
+ }
214
+
215
+ /**
216
+ * Write the managed block of `dir/.env`: own `.env` first (keeps local edits), then the
217
+ * main checkout's, then `.env.dist`; atomic via rename. Returns the managed values.
218
+ */
219
+ export function writeEnv(ctx, dir, slot, profiles) {
220
+ const sources = [join(dir, ENV_FILE), join(ctx.mainRoot, ENV_FILE), join(ctx.mainRoot, ENV_DIST_FILE)];
221
+ const src = sources.find((f) => existsSync(f));
222
+ const current = src ? readFileSync(src, 'utf8') : '';
223
+ const branch = git.currentBranch(dir) ?? '';
224
+ const tag = currentImageTag(ctx, dir);
225
+ const values = managedValues({
226
+ slot,
227
+ projectName: projectNameFor({ slot, branch, projectName: ctx.wt.projectName }),
228
+ profiles,
229
+ imageTag: tag,
230
+ branch,
231
+ ports: ctx.wt.ports,
232
+ extraEnv: ctx.wt.env,
233
+ });
234
+ const text = writeManagedBlock(current, values, { slot, profilesHint: ctx.known.length ? ctx.known.join('|') : 'profile' });
235
+ const tmp = join(dir, `${ENV_FILE}.tmp`);
236
+ writeFileSync(tmp, text);
237
+ renameSync(tmp, join(dir, ENV_FILE));
238
+ const ports = Object.entries(values)
239
+ .filter(([k]) => k.startsWith('DEVKIT_PORT_'))
240
+ .map(([k, v]) => `${k.slice('DEVKIT_PORT_'.length).toLowerCase()}=${v}`)
241
+ .join(' ');
242
+ ctx.log(`wrote ${join(dir, ENV_FILE)} (slot ${slot}, profiles ${profiles.join(',') || '-'}, image tag ${tag}${ports ? `: ${ports}` : ''})`);
243
+ return values;
244
+ }
245
+
246
+ // ───────────────────────── images & volumes ─────────────────────────
247
+
248
+ function missingImages(ctx, dir) {
249
+ const env = envOf(dir);
250
+ const profiles = (env.COMPOSE_PROFILES ?? '').split(',').filter(Boolean);
251
+ return imagesFor(ctx.compose, profiles, env.DEVKIT_IMAGE_TAG ?? 'latest').filter(({ image }) => !stack.imageExists(image));
252
+ }
253
+
254
+ /** Build the active profiles' images when the tag is new; serialized across checkouts. */
255
+ export async function ensureImages(ctx, dir) {
256
+ if (missingImages(ctx, dir).length === 0) return;
257
+ await withLock(
258
+ ctx.baseDir,
259
+ '.image-build.lock',
260
+ 'building the shared dev images',
261
+ 1800,
262
+ async () => {
263
+ const missing = missingImages(ctx, dir); // someone may have built them while we waited
264
+ if (missing.length === 0) return;
265
+ ctx.log(`building shared dev image(s) ${missing.map((m) => m.image).join(', ')} — every checkout on the same lockfile reuses them`);
266
+ await stack.compose(dir, ['build', ...missing.map((m) => m.service)]);
267
+ },
268
+ { log: ctx.log },
269
+ );
270
+ }
271
+
272
+ /** Drop this project's node_modules volumes that belong to other image tags. */
273
+ export function cleanStaleVolumes(ctx, dir) {
274
+ const env = envOf(dir);
275
+ if (!env.COMPOSE_PROJECT_NAME || !env.DEVKIT_IMAGE_TAG) return;
276
+ for (const v of staleVolumes(stack.listVolumes(), env.COMPOSE_PROJECT_NAME, env.DEVKIT_IMAGE_TAG)) {
277
+ if (stack.removeVolume(v)) ctx.log(`removed stale node_modules volume ${v}`);
278
+ else ctx.log(`note: stale volume ${v} is still in use (container on the old image tag) — left alone`);
279
+ }
280
+ }
281
+
282
+ /** Remove owned image tags no checkout's .env references and no container uses. */
283
+ export function pruneImages(ctx) {
284
+ if (!ctx.compose) return;
285
+ const referencedTags = allCheckouts(ctx)
286
+ .map(({ env }) => env.DEVKIT_IMAGE_TAG)
287
+ .filter(Boolean);
288
+ const targets = unreferencedImages(stack.listImages(), { repos: ownedImageRepos(ctx.compose), referencedTags, inUse: stack.imagesInUse() });
289
+ for (const img of targets) {
290
+ if (stack.removeImage(img)) ctx.log(`removed unreferenced dev image ${img}`);
291
+ else ctx.note(`could not remove unreferenced dev image ${img}`);
292
+ }
293
+ }
294
+
295
+ /** `down` across every profile (nothing left behind); `wipe` also removes volumes. */
296
+ export async function stackDown(ctx, dir, { wipe }) {
297
+ const ok = await stack.compose(dir, ['--profile', '*', 'down', ...(wipe ? ['-v'] : []), '--remove-orphans'], {
298
+ // The shell env wins over --env-file: a .env from before profiles were mandatory must
299
+ // not block its own teardown on the compose guard.
300
+ env: { COMPOSE_PROFILES: process.env.COMPOSE_PROFILES || ctx.known[0] || 'devkit' },
301
+ allowFailure: true,
302
+ });
303
+ if (!ok) ctx.note(`compose down failed in ${dir} — check 'docker ps -a' for leftovers`);
304
+ if (wipe) {
305
+ const project = envOf(dir).COMPOSE_PROJECT_NAME;
306
+ if (project) {
307
+ for (const v of projectVolumes(stack.listVolumes(), project)) {
308
+ if (stack.removeVolume(v)) ctx.log(`removed volume ${v}`);
309
+ else ctx.note(`could not remove volume ${v}`);
310
+ }
311
+ }
312
+ }
313
+ }
314
+
315
+ async function refreshEnv(ctx, dir, slot, profiles) {
316
+ writeEnv(ctx, dir, slot, profiles);
317
+ await ensureImages(ctx, dir);
318
+ cleanStaleVolumes(ctx, dir);
319
+ }
320
+
321
+ function currentProfiles(ctx, dir) {
322
+ const raw = (envOf(dir).COMPOSE_PROFILES ?? '').split(',').filter(Boolean);
323
+ const valid = raw.filter((p) => ctx.known.includes(p)); // a stale name from an old .env is dropped, not fatal
324
+ return normalizeProfiles(valid.length ? valid : ctx.wt.profiles.default, { known: ctx.known, required: ctx.wt.profiles.required });
325
+ }
326
+
327
+ function isMain(ctx, dir) {
328
+ return resolve(dir) === resolve(ctx.mainRoot);
329
+ }
330
+
331
+ // ───────────────────────── commands ─────────────────────────
332
+
333
+ /** `worktree:env` — refresh this checkout's managed block, images and volumes. */
334
+ export async function cmdEnv(ctx, { cwd = process.cwd(), slot: requestedSlot } = {}) {
335
+ if (!ctx.hasStack) {
336
+ ctx.log('no docker/docker-compose.dev.yml — nothing to refresh');
337
+ return;
338
+ }
339
+ const dir = git.toplevel(cwd);
340
+ const env = envOf(dir);
341
+ let slot = requestedSlot !== undefined ? validateSlot(requestedSlot, ctx.wt.maxSlot) : isMain(ctx, dir) ? 0 : env.DEVKIT_SLOT ? Number(env.DEVKIT_SLOT) : null;
342
+ const profiles = currentProfiles(ctx, dir);
343
+ // This runs on every `docker:up`: the one place to catch two checkouts on one slot
344
+ // before their stacks fight over the ports.
345
+ await withLock(
346
+ ctx.baseDir,
347
+ '.slot.lock',
348
+ 'assigning a slot',
349
+ 120,
350
+ async () => {
351
+ if (slot === null) slot = pickFreeSlot(usedSlots(ctx), ctx.wt.maxSlot);
352
+ const holders = slotHolders(ctx, slot, dir);
353
+ if (holders.length) {
354
+ throw new Error(`slot ${slot} is already used by: ${holders.join(' ')} — two stacks on one slot share host ports; run 'hassan-devkit worktree:env --slot <free slot>' in one of them (see 'hassan-devkit worktree:list')`);
355
+ }
356
+ writeEnv(ctx, dir, slot, profiles);
357
+ },
358
+ { log: ctx.log },
359
+ );
360
+ await ensureImages(ctx, dir);
361
+ cleanStaleVolumes(ctx, dir);
362
+ if (!existsSync(join(dir, 'node_modules')) || (existsSync(join(dir, '.husky')) && !existsSync(join(dir, '.husky/_')))) {
363
+ ctx.note(`${dir} is missing node_modules or .husky/_ — run 'pnpm install' there, otherwise git SILENTLY SKIPS the pre-commit hooks`);
364
+ }
365
+ }
366
+
367
+ /** `worktree:create <branch>` */
368
+ export async function cmdCreate(ctx, branch, { profiles: requested, up = true } = {}) {
369
+ if (!branch) throw new Error('usage: hassan-devkit worktree:create <BRANCH> [--profiles a,b] [--no-up]');
370
+ const profiles = ctx.hasStack ? normalizeProfiles(requested ?? ctx.wt.profiles.default, { known: ctx.known, required: ctx.wt.profiles.required }) : [];
371
+ await cmdPrune(ctx, {}); // reclaim merged-PR stacks (and their slots) before spending resources on a new one
372
+ const wtDir = join(ctx.baseDir, branch);
373
+ if (existsSync(wtDir)) throw new Error(`${wtDir} already exists`);
374
+ mkdirSync(ctx.baseDir, { recursive: true });
375
+
376
+ // Always start from the freshest main of the canonical remote — never the local main.
377
+ const remote = git.hasRemote(ctx.mainRoot, 'upstream') ? 'upstream' : 'origin';
378
+ const fetched = await run('git', ['-C', ctx.mainRoot, 'fetch', remote, 'main'], { allowFailure: true });
379
+ if (!fetched) throw new Error(`cannot fetch ${remote}/main — refusing to base new work on a possibly stale main`);
380
+ const base = `refs/remotes/${remote}/main`;
381
+ if (git.branchExists(ctx.mainRoot, branch)) {
382
+ await git.worktreeAdd(ctx.mainRoot, wtDir, { branch });
383
+ if (!git.isAncestor(ctx.mainRoot, base, branch)) ctx.note(`existing branch ${branch} is behind ${remote}/main — merge it before starting work`);
384
+ } else {
385
+ await git.worktreeAdd(ctx.mainRoot, wtDir, { newBranch: branch, startPoint: base });
386
+ }
387
+ if (git.branchExists(ctx.mainRoot, 'main') && !git.isAncestor(ctx.mainRoot, base, 'main')) {
388
+ ctx.note(`local main is behind ${remote}/main — sync it with: git checkout main && git merge --ff-only ${remote}/main`);
389
+ }
390
+
391
+ let slot = null;
392
+ if (ctx.hasStack) {
393
+ await withLock(
394
+ ctx.baseDir,
395
+ '.slot.lock',
396
+ 'assigning a slot',
397
+ 120,
398
+ async () => {
399
+ slot = pickFreeSlot(usedSlots(ctx), ctx.wt.maxSlot);
400
+ writeEnv(ctx, wtDir, slot, profiles);
401
+ },
402
+ { log: ctx.log },
403
+ );
404
+ }
405
+
406
+ await startTicket({ branch, tracker: ctx.tracker, cwd: wtDir, log: ctx.log, note: ctx.note });
407
+
408
+ await run('pnpm', ['install', '--frozen-lockfile'], { cwd: wtDir });
409
+ if (existsSync(join(wtDir, '.husky'))) {
410
+ // husky's shim dir (.husky/_) is per-worktree and git SILENTLY skips every hook when
411
+ // core.hooksPath points at a missing dir — bootstrap it and fail loudly if it didn't take.
412
+ await run('pnpm', ['exec', 'husky'], { cwd: wtDir });
413
+ if (!existsSync(join(wtDir, '.husky/_/pre-commit'))) throw new Error(`husky shims missing in ${wtDir} — git would silently skip all hooks`);
414
+ }
415
+
416
+ let values = null;
417
+ if (ctx.hasStack && up) {
418
+ await ensureImages(ctx, wtDir);
419
+ await stack.compose(wtDir, ['up', '-d', '--build']);
420
+ values = envOf(wtDir);
421
+ if (ctx.wt.ready) await stack.waitForUrl(expandEnv(ctx.wt.ready.url, values), ctx.wt.ready.timeoutSeconds, { log: ctx.log });
422
+ for (const script of ctx.wt.seeds.scripts) await stack.compose(wtDir, ['exec', ctx.wt.seeds.service, 'pnpm', script]);
423
+ }
424
+
425
+ ctx.log('');
426
+ ctx.log(`Worktree ready: ${wtDir}${slot !== null ? ` (slot ${slot}, profiles: ${profiles.join(',')})` : ''}`);
427
+ if (values) {
428
+ for (const [k, v] of Object.entries(values)) if (k.startsWith('DEVKIT_PORT_')) ctx.log(` ${k.slice('DEVKIT_PORT_'.length).toLowerCase().padEnd(14)} localhost:${v}`);
429
+ const optional = ctx.known.filter((p) => !ctx.wt.profiles.required.includes(p) && !profiles.includes(p));
430
+ if (optional.length) ctx.log(` add a profile with: hassan-devkit worktree:profiles add ${optional.join('|')}`);
431
+ }
432
+ return { dir: wtDir, slot, profiles };
433
+ }
434
+
435
+ /** `worktree:profiles list|add|remove [names…]` */
436
+ export async function cmdProfiles(ctx, action = 'list', names = [], { cwd = process.cwd() } = {}) {
437
+ if (!ctx.hasStack) throw new Error('no docker/docker-compose.dev.yml — this repo has no stack profiles');
438
+ const dir = git.toplevel(cwd);
439
+ const env = envOf(dir);
440
+ const slot = isMain(ctx, dir) ? 0 : env.DEVKIT_SLOT ? Number(env.DEVKIT_SLOT) : null;
441
+ if (slot === null) throw new Error(`no managed .env in ${dir} — run 'hassan-devkit worktree:env' first`);
442
+ const current = currentProfiles(ctx, dir);
443
+ switch (action) {
444
+ case 'list':
445
+ ctx.log(`active: ${current.join(',') || '-'}`);
446
+ ctx.log(`available: ${ctx.known.join(' ')}${ctx.wt.profiles.required.length ? ` (${ctx.wt.profiles.required.join(', ')} mandatory)` : ''}`);
447
+ return current;
448
+ case 'add': {
449
+ if (names.length === 0) throw new Error(`usage: hassan-devkit worktree:profiles add <${ctx.known.join('|')}> [...]`);
450
+ const next = normalizeProfiles([...current, ...names], { known: ctx.known, required: ctx.wt.profiles.required });
451
+ await refreshEnv(ctx, dir, slot, next);
452
+ // `up -d` is idempotent for running services; only the new profile's containers appear.
453
+ await stack.compose(dir, ['up', '-d']);
454
+ return next;
455
+ }
456
+ case 'remove': {
457
+ if (names.length === 0) throw new Error(`usage: hassan-devkit worktree:profiles remove <${ctx.known.join('|')}> [...]`);
458
+ for (const p of names) {
459
+ if (ctx.wt.profiles.required.includes(p)) throw new Error(`the ${p} profile is mandatory and cannot be removed`);
460
+ if (!ctx.known.includes(p)) throw new Error(`unknown profile '${p}' (known: ${ctx.known.join(' ')})`);
461
+ }
462
+ const next = normalizeProfiles(current.filter((p) => !names.includes(p)), { known: ctx.known, required: ctx.wt.profiles.required });
463
+ writeEnv(ctx, dir, slot, next);
464
+ for (const p of names) {
465
+ // The profile is no longer active, so a plain up/down would not see its containers.
466
+ await stack.compose(dir, ['--profile', p, 'rm', '-sf', ...ctx.compose.profiles[p]], { allowFailure: true });
467
+ }
468
+ return next;
469
+ }
470
+ default:
471
+ throw new Error('usage: hassan-devkit worktree:profiles list|add|remove [name ...]');
472
+ }
473
+ }
474
+
475
+ /** `worktree:remove <name>` — stack down (volumes gone unless --keep-data), worktree removed, branch kept. */
476
+ export async function cmdRemove(ctx, name, { keepData = false, force = false } = {}) {
477
+ if (!name) throw new Error('usage: hassan-devkit worktree:remove <BRANCH> [--keep-data] [--force]');
478
+ const dir = existsSync(name) && existsSync(join(name, '.git')) ? resolve(name) : join(ctx.baseDir, name);
479
+ if (!existsSync(dir)) throw new Error(`no worktree at ${dir}`);
480
+ if (ctx.hasStack && existsSync(join(dir, ENV_FILE))) await stackDown(ctx, dir, { wipe: !keepData });
481
+ const removed = await git.worktreeRemove(ctx.mainRoot, dir, { force });
482
+ if (!removed) throw new Error(`git worktree remove failed for ${dir} — stray changes? re-run with --force`);
483
+ pruneImages(ctx);
484
+ ctx.log(`removed ${dir} (branch kept — delete it with: git branch -D ${basename(dir)})`);
485
+ }
486
+
487
+ /** `worktree:prune` — remove every worktree whose PR is merged (GitHub is the oracle). */
488
+ export async function cmdPrune(ctx, { dryRun = false } = {}) {
489
+ if (!commandExists('gh')) {
490
+ ctx.note('gh not installed — cannot check PR states, skipping prune');
491
+ return [];
492
+ }
493
+ const removed = [];
494
+ if (!existsSync(ctx.baseDir)) return removed;
495
+ for (const entry of readdirSync(ctx.baseDir, { withFileTypes: true })) {
496
+ if (!entry.isDirectory() || entry.name.startsWith('.')) continue;
497
+ const dir = join(ctx.baseDir, entry.name);
498
+ if (!existsSync(join(dir, '.git'))) continue;
499
+ const branch = git.currentBranch(dir);
500
+ if (!branch) {
501
+ ctx.note(`prune: ${entry.name}: no branch checked out — keeping`);
502
+ continue;
503
+ }
504
+ // PRs live on the base repo (fork model): ask upstream, not origin. `pr view` cannot
505
+ // see fork-owned heads, so filter `pr list` by head ref name instead.
506
+ const baseRepo = git.remoteUrl(dir, 'upstream') ?? git.remoteUrl(dir, 'origin');
507
+ if (!baseRepo) {
508
+ ctx.note(`prune: ${entry.name}: no git remote — keeping`);
509
+ continue;
510
+ }
511
+ const states = ghPrStates(baseRepo, branch);
512
+ const decision = pruneDecision(states);
513
+ if (decision !== 'merged') {
514
+ const why = { error: 'gh could not answer', none: 'no PR', open: 'PR open', closed: 'PR closed without merge' }[decision];
515
+ ctx.log(`prune: ${entry.name}: ${why} — keeping`);
516
+ continue;
517
+ }
518
+ if (dryRun) {
519
+ ctx.log(`prune: ${entry.name}: PR merged — would remove worktree, containers, volumes, and branch`);
520
+ removed.push(entry.name);
521
+ continue;
522
+ }
523
+ ctx.log(`prune: ${entry.name}: PR merged — removing worktree, containers, volumes, and branch`);
524
+ if (ctx.hasStack && existsSync(join(dir, ENV_FILE))) await stackDown(ctx, dir, { wipe: true });
525
+ if (await git.worktreeRemove(ctx.mainRoot, dir)) {
526
+ await git.branchDelete(ctx.mainRoot, branch);
527
+ removed.push(entry.name);
528
+ } else {
529
+ ctx.note(`prune: ${entry.name} has stray changes — check them, then run: hassan-devkit worktree:remove ${entry.name} --force && git branch -D ${branch}`);
530
+ }
531
+ }
532
+ if (!dryRun) pruneImages(ctx);
533
+ return removed;
534
+ }
535
+
536
+ function ghPrStates(repoUrl, branch) {
537
+ const { capture } = stackExecShim;
538
+ return capture('gh', ['pr', 'list', '--repo', repoUrl, '--head', branch, '--state', 'all', '--json', 'state', '--jq', '[.[].state] | unique | join(",")'], { allowFailure: true });
539
+ }
540
+
541
+ /** `worktree:list` */
542
+ export function cmdList(ctx) {
543
+ for (const w of git.listWorktrees(ctx.mainRoot)) ctx.log(`${w.path} ${w.head ? w.head.slice(0, 8) : ''} [${w.branch ?? 'detached'}]`);
544
+ const checkouts = allCheckouts(ctx).filter(({ env }) => env.DEVKIT_SLOT !== undefined && env.DEVKIT_SLOT !== '');
545
+ for (const { dir, env } of checkouts) {
546
+ const ports = Object.entries(env)
547
+ .filter(([k]) => k.startsWith('DEVKIT_PORT_'))
548
+ .map(([k, v]) => `${k.slice('DEVKIT_PORT_'.length).toLowerCase()} :${v}`)
549
+ .join(', ');
550
+ ctx.log(` ${basename(dir)}: slot ${env.DEVKIT_SLOT} (${ports}), profiles [${env.COMPOSE_PROFILES ?? ''}], image tag [${env.DEVKIT_IMAGE_TAG ?? ''}]`);
551
+ }
552
+ const bySlot = new Map();
553
+ for (const { dir, env } of checkouts) bySlot.set(env.DEVKIT_SLOT, [...(bySlot.get(env.DEVKIT_SLOT) ?? []), basename(dir)]);
554
+ for (const [slot, names] of bySlot) {
555
+ if (names.length > 1) ctx.note(`slot ${slot} is used by ${names.join(' ')} — run 'hassan-devkit worktree:env --slot <free slot>' in all but one of them`);
556
+ }
557
+ }
558
+
559
+ // `capture` is imported lazily through this shim so the pure functions above can be unit
560
+ // tested without touching child_process at module load.
561
+ import { capture as captureImpl } from './exec.js';
562
+ const stackExecShim = { capture: captureImpl };
563
+
564
+ export { sanitizeName, dirname };
package/src/index.js CHANGED
@@ -3,10 +3,16 @@ import { registerDocker } from './commands/docker.js';
3
3
  import { registerDb } from './commands/db.js';
4
4
  import { registerHooks } from './commands/hooks.js';
5
5
  import { registerI18n } from './commands/i18n.js';
6
+ import { registerInit } from './commands/init.js';
7
+ import { registerConfig } from './commands/config.js';
8
+ import { registerWorktree } from './commands/worktree.js';
6
9
 
7
10
  export function run(argv) {
8
11
  const cli = cac('hassan-devkit');
9
12
 
13
+ registerInit(cli);
14
+ registerConfig(cli);
15
+ registerWorktree(cli);
10
16
  registerDocker(cli);
11
17
  registerDb(cli);
12
18
  registerHooks(cli);