@coding-with-hassan/devkit 0.4.0 → 1.0.0-next.1
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.
- package/README.md +115 -0
- package/claude/agents/commit-writer.md +84 -0
- package/claude/skills/implement-ticket/SKILL.md +17 -0
- package/claude/standards.md +99 -0
- package/hooks/pre-commit.sh +9 -3
- package/lint-staged.js +81 -0
- package/package.json +21 -3
- package/src/commands/ci.js +186 -0
- package/src/commands/claude.js +24 -0
- package/src/commands/config.js +117 -0
- package/src/commands/docker.js +10 -0
- package/src/commands/hooks.js +27 -20
- package/src/commands/init.js +211 -0
- package/src/commands/test-cases.js +31 -0
- package/src/commands/worktree.js +37 -0
- package/src/core/agents-docs.js +225 -0
- package/src/core/ci/affected.js +155 -0
- package/src/core/ci/commit-standards.js +59 -0
- package/src/core/ci/nx-cache.js +74 -0
- package/src/core/ci/workflow.js +87 -0
- package/src/core/claude.js +113 -0
- package/src/core/compose.js +69 -0
- package/src/core/config.js +324 -0
- package/src/core/derive.js +130 -0
- package/src/core/env-block.js +76 -0
- package/src/core/exec.js +45 -0
- package/src/core/git.js +77 -0
- package/src/core/locks.js +60 -0
- package/src/core/root.js +30 -0
- package/src/core/scaffold.js +131 -0
- package/src/core/stack.js +63 -0
- package/src/core/test-cases/generate.js +287 -0
- package/src/core/test-cases/loader.mjs +40 -0
- package/src/core/tracker/github.js +29 -0
- package/src/core/tracker/index.js +37 -0
- package/src/core/tracker/jira.js +101 -0
- package/src/core/workspace.js +105 -0
- package/src/core/worktrees.js +580 -0
- package/src/index.js +12 -0
- package/test-cases.d.ts +48 -0
- package/test-cases.js +26 -0
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { expandEnv, portsForSlot } from './derive.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The managed block every checkout's `.env` (and the repo's `.env.dist` at slot 0)
|
|
5
|
+
* ends with. Written by `worktree:env`; owned keys are stripped wherever else they sit
|
|
6
|
+
* so the block is the single source of the values compose reads.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export const MANAGED_MARKER = '# ── Managed by hassan-devkit';
|
|
10
|
+
|
|
11
|
+
/** Keys the block owns (and that are removed from the rest of the file on rewrite). */
|
|
12
|
+
export function ownedKeys(ports, extraEnv) {
|
|
13
|
+
return [
|
|
14
|
+
'COMPOSE_PROJECT_NAME',
|
|
15
|
+
'COMPOSE_PROFILES',
|
|
16
|
+
'DEVKIT_IMAGE_TAG',
|
|
17
|
+
'DEVKIT_SLOT',
|
|
18
|
+
'DEVKIT_BRANCH',
|
|
19
|
+
...Object.keys(portsForSlot(ports, 0)),
|
|
20
|
+
...Object.keys(extraEnv ?? {}),
|
|
21
|
+
];
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Compute the managed values for a slot. `extraEnv` templates may reference any
|
|
26
|
+
* `${DEVKIT_*}` value (ports, slot, branch, tag) and are expanded in declaration order.
|
|
27
|
+
*/
|
|
28
|
+
export function managedValues({ slot, projectName, profiles, imageTag, branch, ports, extraEnv = {} }) {
|
|
29
|
+
const values = {
|
|
30
|
+
COMPOSE_PROJECT_NAME: projectName,
|
|
31
|
+
COMPOSE_PROFILES: profiles.join(','),
|
|
32
|
+
DEVKIT_IMAGE_TAG: imageTag,
|
|
33
|
+
DEVKIT_SLOT: String(slot),
|
|
34
|
+
DEVKIT_BRANCH: branch,
|
|
35
|
+
...portsForSlot(ports, slot),
|
|
36
|
+
};
|
|
37
|
+
for (const [key, template] of Object.entries(extraEnv)) values[key] = expandEnv(template, values);
|
|
38
|
+
return values;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Render the block text (marker + comment lines + `KEY=value` lines). */
|
|
42
|
+
export function renderManagedBlock(values, { slot, profilesHint }) {
|
|
43
|
+
const lines = [
|
|
44
|
+
`${MANAGED_MARKER} (slot ${slot}) — do not edit by hand ──`,
|
|
45
|
+
`# Profiles: hassan-devkit worktree:profiles add|remove <${profilesHint}>.`,
|
|
46
|
+
'# Image tag: recomputed by hassan-devkit worktree:env (pnpm docker:dev:up runs it).',
|
|
47
|
+
];
|
|
48
|
+
for (const [key, value] of Object.entries(values)) lines.push(`${key}=${value}`);
|
|
49
|
+
return `${lines.join('\n')}\n`;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Rewrite `text` so it ends with exactly one managed block: strip a previous block (from
|
|
54
|
+
* the marker to EOF) and every owned key found elsewhere, then append the new block.
|
|
55
|
+
*/
|
|
56
|
+
export function writeManagedBlock(text, values, opts) {
|
|
57
|
+
const owned = new Set(Object.keys(values));
|
|
58
|
+
const lines = (text ?? '').split('\n');
|
|
59
|
+
const markerIdx = lines.findIndex((l) => l.startsWith(MANAGED_MARKER));
|
|
60
|
+
const kept = (markerIdx === -1 ? lines : lines.slice(0, markerIdx)).filter((line) => {
|
|
61
|
+
const m = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(line);
|
|
62
|
+
return !(m && owned.has(m[1]));
|
|
63
|
+
});
|
|
64
|
+
const head = kept.join('\n').replace(/\s+$/, '');
|
|
65
|
+
return `${head ? `${head}\n\n` : ''}${renderManagedBlock(values, opts)}`;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Parse `KEY=value` lines (ignores comments/blank/exports; no quote handling needed here). */
|
|
69
|
+
export function parseEnv(text) {
|
|
70
|
+
const out = {};
|
|
71
|
+
for (const line of (text ?? '').split('\n')) {
|
|
72
|
+
const m = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/.exec(line);
|
|
73
|
+
if (m) out[m[1]] = m[2].trim();
|
|
74
|
+
}
|
|
75
|
+
return out;
|
|
76
|
+
}
|
package/src/core/exec.js
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { execFileSync, spawn } from 'node:child_process';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Run a command and return its trimmed stdout. Throws with the command line and stderr
|
|
5
|
+
* unless `allowFailure`, in which case `null` is returned (use it for probes whose exit
|
|
6
|
+
* code IS the answer, e.g. `docker image inspect`, `git merge-base --is-ancestor`).
|
|
7
|
+
*/
|
|
8
|
+
export function capture(cmd, args, { cwd, env, allowFailure = false, input } = {}) {
|
|
9
|
+
try {
|
|
10
|
+
return execFileSync(cmd, args, {
|
|
11
|
+
cwd,
|
|
12
|
+
env: env ? { ...process.env, ...env } : process.env,
|
|
13
|
+
input,
|
|
14
|
+
stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'],
|
|
15
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
16
|
+
})
|
|
17
|
+
.toString()
|
|
18
|
+
.replace(/\n$/, '');
|
|
19
|
+
} catch (e) {
|
|
20
|
+
if (allowFailure) return null;
|
|
21
|
+
const stderr = e.stderr ? e.stderr.toString().trim() : '';
|
|
22
|
+
const err = new Error(`${cmd} ${args.join(' ')} failed${stderr ? `:\n${stderr}` : ` (exit ${e.status ?? '?'})`}`);
|
|
23
|
+
err.cause = e;
|
|
24
|
+
throw err;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Run a command with inherited stdio; resolves on exit 0, rejects otherwise. */
|
|
29
|
+
export function run(cmd, args, { cwd, env, allowFailure = false } = {}) {
|
|
30
|
+
return new Promise((resolve, reject) => {
|
|
31
|
+
const child = spawn(cmd, args, { cwd, env: env ? { ...process.env, ...env } : process.env, stdio: 'inherit' });
|
|
32
|
+
child.on('error', (e) => (allowFailure ? resolve(false) : reject(e)));
|
|
33
|
+
child.on('exit', (code) => {
|
|
34
|
+
if (code === 0) resolve(true);
|
|
35
|
+
else if (allowFailure) resolve(false);
|
|
36
|
+
else reject(new Error(`${cmd} ${args.join(' ')} exited with code ${code}`));
|
|
37
|
+
});
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function commandExists(cmd) {
|
|
42
|
+
return capture(process.platform === 'win32' ? 'where' : 'which', [cmd], { allowFailure: true }) !== null;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
package/src/core/git.js
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { capture, run } from './exec.js';
|
|
2
|
+
|
|
3
|
+
/** Thin git helpers; every call takes the checkout directory explicitly. */
|
|
4
|
+
|
|
5
|
+
export const git = (dir, args, opts = {}) => capture('git', args, { cwd: dir, ...opts });
|
|
6
|
+
|
|
7
|
+
/** The main checkout of the repository `dir` belongs to (first entry of `worktree list`). */
|
|
8
|
+
export function mainRoot(dir) {
|
|
9
|
+
const first = git(dir, ['worktree', 'list', '--porcelain']).split('\n')[0] ?? '';
|
|
10
|
+
return first.replace(/^worktree /, '');
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** All worktrees of the repository as `{ path, head, branch }` (branch `null` when detached). */
|
|
14
|
+
export function listWorktrees(dir) {
|
|
15
|
+
const out = git(dir, ['worktree', 'list', '--porcelain']);
|
|
16
|
+
const entries = [];
|
|
17
|
+
let current = null;
|
|
18
|
+
for (const line of out.split('\n')) {
|
|
19
|
+
if (line.startsWith('worktree ')) {
|
|
20
|
+
current = { path: line.slice(9), head: null, branch: null };
|
|
21
|
+
entries.push(current);
|
|
22
|
+
} else if (current && line.startsWith('HEAD ')) current.head = line.slice(5);
|
|
23
|
+
else if (current && line.startsWith('branch ')) current.branch = line.slice(7).replace(/^refs\/heads\//, '');
|
|
24
|
+
}
|
|
25
|
+
return entries;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function currentBranch(dir) {
|
|
29
|
+
const b = git(dir, ['branch', '--show-current'], { allowFailure: true });
|
|
30
|
+
return b ? b.trim() : null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function hasRemote(dir, name) {
|
|
34
|
+
return git(dir, ['remote', 'get-url', name], { allowFailure: true }) !== null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function remoteUrl(dir, name) {
|
|
38
|
+
return git(dir, ['remote', 'get-url', name], { allowFailure: true });
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function branchExists(dir, branch) {
|
|
42
|
+
return git(dir, ['show-ref', '--verify', '--quiet', `refs/heads/${branch}`], { allowFailure: true }) !== null;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function isAncestor(dir, ancestor, descendant) {
|
|
46
|
+
return git(dir, ['merge-base', '--is-ancestor', ancestor, descendant], { allowFailure: true }) !== null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function fetch(dir, remote, ref) {
|
|
50
|
+
return run('git', ['-C', dir, 'fetch', remote, ref]);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function worktreeAdd(dir, path, { branch, newBranch, startPoint }) {
|
|
54
|
+
const args = ['-C', dir, 'worktree', 'add'];
|
|
55
|
+
if (newBranch) args.push('--no-track', '-b', newBranch, path, startPoint);
|
|
56
|
+
else args.push(path, branch);
|
|
57
|
+
return run('git', args);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function worktreeRemove(dir, path, { force = false } = {}) {
|
|
61
|
+
return run('git', ['-C', dir, 'worktree', 'remove', ...(force ? ['--force'] : []), path], { allowFailure: true });
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function branchDelete(dir, branch) {
|
|
65
|
+
return run('git', ['-C', dir, 'branch', '-D', branch], { allowFailure: true });
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function toplevel(dir) {
|
|
69
|
+
return git(dir, ['rev-parse', '--show-toplevel']);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** `owner/repo` of a remote URL (https or ssh), or the URL itself when it is not GitHub-shaped. */
|
|
73
|
+
export function repoSlug(url) {
|
|
74
|
+
if (!url) return null;
|
|
75
|
+
const m = /github\.com[:/]([^/]+\/[^/]+?)(?:\.git)?$/.exec(url);
|
|
76
|
+
return m ? m[1] : url;
|
|
77
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { sleep } from './exec.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Cross-checkout locks: `mkdir` is atomic on every platform (macOS has no flock), and
|
|
7
|
+
* the pid file inside lets a crashed holder be reclaimed. Two locks exist, never nested:
|
|
8
|
+
* .slot.lock — slot allocation (scan → write .env), seconds
|
|
9
|
+
* .image-build.lock — pnpm install inside docker build, minutes
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
function pidAlive(pid) {
|
|
13
|
+
try {
|
|
14
|
+
process.kill(pid, 0);
|
|
15
|
+
return true;
|
|
16
|
+
} catch (e) {
|
|
17
|
+
return e.code === 'EPERM';
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Run `fn` while holding `<baseDir>/<name>`; waits up to `maxSeconds`, reclaims stale locks. */
|
|
22
|
+
export async function withLock(baseDir, name, what, maxSeconds, fn, { log = console.log, pollMs = 2000 } = {}) {
|
|
23
|
+
const lock = join(baseDir, name);
|
|
24
|
+
mkdirSync(baseDir, { recursive: true });
|
|
25
|
+
let waited = 0;
|
|
26
|
+
for (;;) {
|
|
27
|
+
try {
|
|
28
|
+
mkdirSync(lock);
|
|
29
|
+
break;
|
|
30
|
+
} catch (e) {
|
|
31
|
+
if (e.code !== 'EEXIST') throw e;
|
|
32
|
+
}
|
|
33
|
+
let holder = null;
|
|
34
|
+
try {
|
|
35
|
+
holder = Number(readFileSync(join(lock, 'pid'), 'utf8').trim()) || null;
|
|
36
|
+
} catch {
|
|
37
|
+
holder = null;
|
|
38
|
+
}
|
|
39
|
+
if (holder && !pidAlive(holder)) {
|
|
40
|
+
log(`reclaiming stale lock ${lock} (pid ${holder} is gone)`);
|
|
41
|
+
rmSync(lock, { recursive: true, force: true });
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
if (waited === 0) log(`another hassan-devkit is ${what} (pid ${holder ?? '?'}) — waiting...`);
|
|
45
|
+
await sleep(pollMs);
|
|
46
|
+
waited += pollMs / 1000;
|
|
47
|
+
if (waited >= maxSeconds) {
|
|
48
|
+
throw new Error(`gave up waiting for ${lock} after ${maxSeconds}s — remove it if no hassan-devkit is running`);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
writeFileSync(join(lock, 'pid'), String(process.pid));
|
|
52
|
+
const release = () => rmSync(lock, { recursive: true, force: true });
|
|
53
|
+
process.once('exit', release);
|
|
54
|
+
try {
|
|
55
|
+
return await fn();
|
|
56
|
+
} finally {
|
|
57
|
+
release();
|
|
58
|
+
process.off('exit', release);
|
|
59
|
+
}
|
|
60
|
+
}
|
package/src/core/root.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { existsSync } from 'node:fs';
|
|
3
|
+
import { dirname, join, resolve } from 'node:path';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The repo root the CLI operates on: the git toplevel of `cwd` (a worktree's own
|
|
7
|
+
* directory when run inside one), falling back to the nearest ancestor holding a
|
|
8
|
+
* `pnpm-workspace.yaml` or `package.json`, and finally to `cwd` itself.
|
|
9
|
+
*/
|
|
10
|
+
export function findRepoRoot(cwd = process.cwd()) {
|
|
11
|
+
try {
|
|
12
|
+
return execFileSync('git', ['rev-parse', '--show-toplevel'], {
|
|
13
|
+
cwd,
|
|
14
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
15
|
+
})
|
|
16
|
+
.toString()
|
|
17
|
+
.trim();
|
|
18
|
+
} catch {
|
|
19
|
+
// not a git checkout — fall through to the filesystem walk
|
|
20
|
+
}
|
|
21
|
+
let dir = resolve(cwd);
|
|
22
|
+
for (;;) {
|
|
23
|
+
if (existsSync(join(dir, 'pnpm-workspace.yaml')) || existsSync(join(dir, 'package.json'))) {
|
|
24
|
+
return dir;
|
|
25
|
+
}
|
|
26
|
+
const parent = dirname(dir);
|
|
27
|
+
if (parent === dir) return resolve(cwd);
|
|
28
|
+
dir = parent;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync, chmodSync } from 'node:fs';
|
|
2
|
+
import { dirname, join } from 'node:path';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Idempotent file scaffolding shared by `init` (and, later, by the Claude and CI
|
|
6
|
+
* scaffolds). A plan says what WOULD happen; `applyPlan` does it. A file the project has
|
|
7
|
+
* edited is never overwritten without `--force`, and `--force` always prints the diff.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/** Deep-merge `patch` into `target` adding only keys that are missing. Returns added paths. */
|
|
11
|
+
export function mergeMissing(target, patch, path = '') {
|
|
12
|
+
const added = [];
|
|
13
|
+
for (const [key, value] of Object.entries(patch)) {
|
|
14
|
+
const here = path ? `${path}.${key}` : key;
|
|
15
|
+
if (!(key in target)) {
|
|
16
|
+
target[key] = value;
|
|
17
|
+
added.push(here);
|
|
18
|
+
} else if (isPlainObject(target[key]) && isPlainObject(value)) {
|
|
19
|
+
added.push(...mergeMissing(target[key], value, here));
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
return added;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Replace everything from the first line equal to/starting with `marker` to the end of
|
|
29
|
+
* `text` with `block`; append when the marker is absent. Mirrors the managed-block
|
|
30
|
+
* semantics of the `.env` writer so `.env.dist` and `.env` agree.
|
|
31
|
+
*/
|
|
32
|
+
export function upsertTrailingBlock(text, markerPrefix, block) {
|
|
33
|
+
const lines = (text ?? '').split('\n');
|
|
34
|
+
const idx = lines.findIndex((l) => l.startsWith(markerPrefix));
|
|
35
|
+
const head = (idx === -1 ? lines : lines.slice(0, idx)).join('\n').replace(/\s+$/, '');
|
|
36
|
+
return `${head ? `${head}\n\n` : ''}${block.replace(/\s+$/, '')}\n`;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Minimal line diff (LCS) rendered as unified-ish `-`/`+` lines. */
|
|
40
|
+
export function lineDiff(before, after) {
|
|
41
|
+
const a = before.split('\n');
|
|
42
|
+
const b = after.split('\n');
|
|
43
|
+
const n = a.length;
|
|
44
|
+
const m = b.length;
|
|
45
|
+
const dp = Array.from({ length: n + 1 }, () => new Uint16Array(m + 1));
|
|
46
|
+
for (let i = n - 1; i >= 0; i--) {
|
|
47
|
+
for (let j = m - 1; j >= 0; j--) {
|
|
48
|
+
dp[i][j] = a[i] === b[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
const out = [];
|
|
52
|
+
let i = 0;
|
|
53
|
+
let j = 0;
|
|
54
|
+
while (i < n && j < m) {
|
|
55
|
+
if (a[i] === b[j]) {
|
|
56
|
+
i++;
|
|
57
|
+
j++;
|
|
58
|
+
} else if (dp[i + 1][j] >= dp[i][j + 1]) out.push(`-${a[i++]}`);
|
|
59
|
+
else out.push(`+${b[j++]}`);
|
|
60
|
+
}
|
|
61
|
+
while (i < n) out.push(`-${a[i++]}`);
|
|
62
|
+
while (j < m) out.push(`+${b[j++]}`);
|
|
63
|
+
return out;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* @typedef {{ path: string, content: string, mode?: number, status: 'create'|'same'|'differs', current: string|null }} FilePlan
|
|
68
|
+
*/
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Plan one file. `path` is relative to `root`. A `managed` plan is one whose content is
|
|
72
|
+
* computed FROM the current file (a merged package.json, a managed `.env.dist` block), so
|
|
73
|
+
* rewriting it can never lose project edits — it is updated without `--force`.
|
|
74
|
+
*/
|
|
75
|
+
export function planFile(root, path, content, { mode, managed = false } = {}) {
|
|
76
|
+
const abs = join(root, path);
|
|
77
|
+
if (!existsSync(abs)) return { path, content, mode, managed, status: 'create', current: null };
|
|
78
|
+
const current = readFileSync(abs, 'utf8');
|
|
79
|
+
return { path, content, mode, managed, status: current === content ? 'same' : 'differs', current };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Apply plans. Returns a summary `{ created, updated, overwritten, skipped, unchanged }`.
|
|
84
|
+
* `differs` files are skipped unless `force` (the diff is logged first) — except managed
|
|
85
|
+
* plans, which are always updated because their content preserves the project's edits.
|
|
86
|
+
*/
|
|
87
|
+
export function applyPlan(root, plans, { force = false, dryRun = false, log = console.log } = {}) {
|
|
88
|
+
const summary = { created: [], updated: [], overwritten: [], skipped: [], unchanged: [] };
|
|
89
|
+
for (const plan of plans) {
|
|
90
|
+
const abs = join(root, plan.path);
|
|
91
|
+
if (plan.status === 'same') {
|
|
92
|
+
summary.unchanged.push(plan.path);
|
|
93
|
+
log(` unchanged ${plan.path}`);
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
if (plan.status === 'differs' && plan.managed) {
|
|
97
|
+
log(` update ${plan.path}`);
|
|
98
|
+
summary.updated.push(plan.path);
|
|
99
|
+
} else if (plan.status === 'differs' && !force) {
|
|
100
|
+
summary.skipped.push(plan.path);
|
|
101
|
+
log(` differs ${plan.path} (kept; re-run with --force to overwrite)`);
|
|
102
|
+
continue;
|
|
103
|
+
} else if (plan.status === 'differs') {
|
|
104
|
+
log(` overwrite ${plan.path}`);
|
|
105
|
+
for (const line of lineDiff(plan.current, plan.content)) log(` ${line}`);
|
|
106
|
+
summary.overwritten.push(plan.path);
|
|
107
|
+
} else {
|
|
108
|
+
log(` create ${plan.path}`);
|
|
109
|
+
summary.created.push(plan.path);
|
|
110
|
+
}
|
|
111
|
+
if (dryRun) continue;
|
|
112
|
+
mkdirSync(dirname(abs), { recursive: true });
|
|
113
|
+
writeFileSync(abs, plan.content);
|
|
114
|
+
if (plan.mode) chmodSync(abs, plan.mode);
|
|
115
|
+
}
|
|
116
|
+
return summary;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Read a JSON file or return `fallback`. */
|
|
120
|
+
export function readJson(path, fallback = null) {
|
|
121
|
+
try {
|
|
122
|
+
return JSON.parse(readFileSync(path, 'utf8'));
|
|
123
|
+
} catch {
|
|
124
|
+
return fallback;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Serialise JSON the way package managers do: 2 spaces, trailing newline. */
|
|
129
|
+
export function formatJson(value) {
|
|
130
|
+
return `${JSON.stringify(value, null, 2)}\n`;
|
|
131
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { COMPOSE_FILE, ENV_FILE } from './config.js';
|
|
4
|
+
import { capture, run, sleep } from './exec.js';
|
|
5
|
+
|
|
6
|
+
/** Docker helpers for one checkout's stack. All compose calls read that checkout's `.env`. */
|
|
7
|
+
|
|
8
|
+
export function hasComposeFile(root) {
|
|
9
|
+
return existsSync(join(root, COMPOSE_FILE));
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function composeArgs(root) {
|
|
13
|
+
const args = ['compose'];
|
|
14
|
+
if (existsSync(join(root, ENV_FILE))) args.push('--env-file', ENV_FILE);
|
|
15
|
+
args.push('-f', COMPOSE_FILE);
|
|
16
|
+
return args;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function compose(root, args, { env, allowFailure = false } = {}) {
|
|
20
|
+
return run('docker', [...composeArgs(root), ...args], { cwd: root, env, allowFailure });
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function imageExists(ref) {
|
|
24
|
+
return capture('docker', ['image', 'inspect', ref], { allowFailure: true }) !== null;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function listVolumes() {
|
|
28
|
+
return (capture('docker', ['volume', 'ls', '-q'], { allowFailure: true }) ?? '').split('\n').filter(Boolean);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function removeVolume(name) {
|
|
32
|
+
return capture('docker', ['volume', 'rm', name], { allowFailure: true }) !== null;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function listImages() {
|
|
36
|
+
return (capture('docker', ['image', 'ls', '--format', '{{.Repository}}:{{.Tag}}'], { allowFailure: true }) ?? '')
|
|
37
|
+
.split('\n')
|
|
38
|
+
.filter(Boolean);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function imagesInUse() {
|
|
42
|
+
return (capture('docker', ['ps', '-a', '--format', '{{.Image}}'], { allowFailure: true }) ?? '').split('\n').filter(Boolean);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function removeImage(ref) {
|
|
46
|
+
return capture('docker', ['image', 'rm', ref], { allowFailure: true }) !== null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Poll `url` until it answers 2xx/3xx; throws after `timeoutSeconds`. */
|
|
50
|
+
export async function waitForUrl(url, timeoutSeconds, { log = console.log, pollMs = 3000 } = {}) {
|
|
51
|
+
log(`waiting for ${url} (first boot compiles, this takes a while)...`);
|
|
52
|
+
const deadline = Date.now() + timeoutSeconds * 1000;
|
|
53
|
+
while (Date.now() < deadline) {
|
|
54
|
+
try {
|
|
55
|
+
const res = await fetch(url, { signal: AbortSignal.timeout(2000), redirect: 'manual' });
|
|
56
|
+
if (res.status < 400) return;
|
|
57
|
+
} catch {
|
|
58
|
+
// not up yet
|
|
59
|
+
}
|
|
60
|
+
await sleep(pollMs);
|
|
61
|
+
}
|
|
62
|
+
throw new Error(`${url} did not come up within ${timeoutSeconds}s — check pnpm docker:dev:logs`);
|
|
63
|
+
}
|