@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.
- package/README.md +69 -0
- package/package.json +6 -2
- package/src/commands/config.js +117 -0
- package/src/commands/docker.js +9 -0
- package/src/commands/init.js +127 -0
- package/src/commands/worktree.js +37 -0
- package/src/core/agents-docs.js +225 -0
- package/src/core/compose.js +69 -0
- package/src/core/config.js +316 -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/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 +564 -0
- package/src/index.js +6 -0
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { existsSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { COMPOSE_FILE, ENV_FILE } from './config.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Profile → service maps are derived from the compose file itself, never declared.
|
|
8
|
+
* `docker compose config` is asked for the fully resolved model with EVERY profile
|
|
9
|
+
* active (`--profile '*'`); without that, a service whose dependency sits behind an
|
|
10
|
+
* inactive profile makes the model invalid.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** Run `docker compose config --format json` and return the parsed model. */
|
|
14
|
+
export function readComposeModel(root, { composeFile = COMPOSE_FILE, envFile = ENV_FILE } = {}) {
|
|
15
|
+
const file = join(root, composeFile);
|
|
16
|
+
if (!existsSync(file)) return null;
|
|
17
|
+
const args = ['compose', '--profile', '*'];
|
|
18
|
+
if (existsSync(join(root, envFile))) args.push('--env-file', envFile);
|
|
19
|
+
args.push('-f', composeFile, 'config', '--format', 'json');
|
|
20
|
+
const out = execFileSync('docker', args, {
|
|
21
|
+
cwd: root,
|
|
22
|
+
// The profiles guard (`${COMPOSE_PROFILES:?…}`) must see a value even for a checkout
|
|
23
|
+
// whose .env predates profiles; the shell env wins over .env in interpolation.
|
|
24
|
+
env: { ...process.env, COMPOSE_PROFILES: process.env.COMPOSE_PROFILES || 'devkit-derive' },
|
|
25
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
26
|
+
maxBuffer: 16 * 1024 * 1024,
|
|
27
|
+
});
|
|
28
|
+
return JSON.parse(out.toString());
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Pure: turn a compose model into the maps the worktree commands need.
|
|
33
|
+
*
|
|
34
|
+
* profiles — { api: ['db', 'backend'], web: ['frontend'] } (services per profile)
|
|
35
|
+
* always — services with no `profiles:` (active in every stack)
|
|
36
|
+
* buildable — services per profile that have a `build:` (the images we tag + share)
|
|
37
|
+
* services — per service: profiles, build ({ context, dockerfile } | null), image, ports
|
|
38
|
+
*/
|
|
39
|
+
export function deriveProfiles(model) {
|
|
40
|
+
const services = {};
|
|
41
|
+
const profiles = {};
|
|
42
|
+
const buildable = {};
|
|
43
|
+
const always = [];
|
|
44
|
+
for (const [name, svc] of Object.entries(model?.services ?? {})) {
|
|
45
|
+
const svcProfiles = Array.isArray(svc.profiles) ? [...svc.profiles] : [];
|
|
46
|
+
const ports = (svc.ports ?? []).map((p) => (typeof p === 'object' ? String(p.published ?? '') : String(p).split(':')[0])).filter(Boolean);
|
|
47
|
+
const build = svc.build ? { context: svc.build.context ?? '.', dockerfile: svc.build.dockerfile ?? 'Dockerfile' } : null;
|
|
48
|
+
services[name] = { profiles: svcProfiles, build, image: svc.image ?? null, ports };
|
|
49
|
+
if (svcProfiles.length === 0) always.push(name);
|
|
50
|
+
for (const p of svcProfiles) {
|
|
51
|
+
(profiles[p] ??= []).push(name);
|
|
52
|
+
if (svc.build) (buildable[p] ??= []).push(name);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
const sortValues = (o) => Object.fromEntries(Object.entries(o).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => [k, v.sort()]));
|
|
56
|
+
return {
|
|
57
|
+
projectName: model?.name ?? null,
|
|
58
|
+
services,
|
|
59
|
+
always: always.sort(),
|
|
60
|
+
profiles: sortValues(profiles),
|
|
61
|
+
buildable: sortValues(buildable),
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Convenience: read + derive, or `null` when the repo has no compose file. */
|
|
66
|
+
export function loadProfiles(root, opts) {
|
|
67
|
+
const model = readComposeModel(root, opts);
|
|
68
|
+
return model ? deriveProfiles(model) : null;
|
|
69
|
+
}
|
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { basename, join } from 'node:path';
|
|
3
|
+
import { findRepoRoot } from './root.js';
|
|
4
|
+
import { sanitizeName } from './derive.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The `hassan-devkit` block of the consumer's root package.json — the one place a
|
|
8
|
+
* project declares its values. Everything that can be derived (workspace projects,
|
|
9
|
+
* commit scopes, compose profile maps, image names) is NOT declared here; see derive.js,
|
|
10
|
+
* workspace.js and compose.js.
|
|
11
|
+
*
|
|
12
|
+
* Shape (every key optional; defaults below):
|
|
13
|
+
*
|
|
14
|
+
* "hassan-devkit": {
|
|
15
|
+
* "worktree": {
|
|
16
|
+
* "baseDir": "../<root-name>-worktrees",
|
|
17
|
+
* "maxSlot": 30,
|
|
18
|
+
* "projectName": "<root-name>", // compose project of slot 0
|
|
19
|
+
* "ports": { "api": 3000, "db": 5432 }, // base host ports, slot N adds N*10
|
|
20
|
+
* "profiles": { "default": ["api"], "required": ["api"] },
|
|
21
|
+
* "seeds": { "service": "backend", "scripts": ["seed:admin-user"] },
|
|
22
|
+
* "ready": { "url": "http://localhost:${DEVKIT_PORT_API}/api-json", "timeoutSeconds": 600 },
|
|
23
|
+
* "env": { "API_PROXY_TARGET": "http://localhost:${DEVKIT_PORT_API}" }
|
|
24
|
+
* },
|
|
25
|
+
* "tracker": { "kind": "jira", "project": "DAZ", "baseUrl": "https://x.atlassian.net" }
|
|
26
|
+
* | { "kind": "github", "prefix": "GH" }
|
|
27
|
+
* | { "kind": "none" },
|
|
28
|
+
* "commits": { "types": [...], "extraScopes": [...], "requireSigned": true,
|
|
29
|
+
* "exemptAuthors": ["renovate[bot]"], "docsUrl": "https://..." },
|
|
30
|
+
* "ci": { "checks": [{ "name": "translations", "paths": ["^libs/i18n/"], "run": "pnpm ..." }],
|
|
31
|
+
* "affected": { "contentOnly": ["libs/i18n/src/**\/*.json"], "adopted": { "scripts/*.mjs": "daz-i18n" } } },
|
|
32
|
+
* "testCases": { "dir": "docs/testing", "languages": ["en", "nl"] },
|
|
33
|
+
* "db": { "service": "db", "user": "postgres", "name": "app" },
|
|
34
|
+
* "docker": { "preUp": "..." },
|
|
35
|
+
* "i18n": { "dir": "public/assets/i18n", "languages": ["en", "nl"] }
|
|
36
|
+
* }
|
|
37
|
+
*/
|
|
38
|
+
|
|
39
|
+
export const CONFIG_KEY = 'hassan-devkit';
|
|
40
|
+
export const COMPOSE_FILE = 'docker/docker-compose.dev.yml';
|
|
41
|
+
export const ENV_FILE = '.env';
|
|
42
|
+
export const ENV_DIST_FILE = '.env.dist';
|
|
43
|
+
|
|
44
|
+
export const DEFAULT_COMMIT_TYPES = ['feat', 'fix', 'refactor', 'chore', 'docs', 'test', 'perf'];
|
|
45
|
+
export const DEFAULT_EXTRA_SCOPES = ['docker', 'workspace', 'docs', 'deps'];
|
|
46
|
+
export const DEFAULT_EXEMPT_AUTHORS = ['renovate[bot]'];
|
|
47
|
+
export const DEFAULT_MAX_SLOT = 30;
|
|
48
|
+
export const DEFAULT_GITHUB_PREFIX = 'GH';
|
|
49
|
+
export const TRACKER_KINDS = ['jira', 'github', 'none'];
|
|
50
|
+
|
|
51
|
+
const isString = (v) => typeof v === 'string';
|
|
52
|
+
const isNonEmptyString = (v) => isString(v) && v.trim().length > 0;
|
|
53
|
+
const isBoolean = (v) => typeof v === 'boolean';
|
|
54
|
+
const isInteger = (v) => Number.isInteger(v);
|
|
55
|
+
const isPort = (v) => isInteger(v) && v > 0 && v < 65536;
|
|
56
|
+
const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
57
|
+
const isStringArray = (v) => Array.isArray(v) && v.every(isNonEmptyString);
|
|
58
|
+
const isStringRecord = (v) => isPlainObject(v) && Object.values(v).every(isString);
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Validate the raw block. Returns a list of `path: problem` strings; empty = valid.
|
|
62
|
+
* Unknown keys are reported too, since a typo in a key silently disables a feature.
|
|
63
|
+
*/
|
|
64
|
+
export function validateConfig(raw) {
|
|
65
|
+
const errors = [];
|
|
66
|
+
if (raw === undefined) return errors;
|
|
67
|
+
if (!isPlainObject(raw)) return [`${CONFIG_KEY}: expected an object`];
|
|
68
|
+
|
|
69
|
+
const known = ['worktree', 'tracker', 'commits', 'ci', 'testCases', 'db', 'docker', 'i18n'];
|
|
70
|
+
for (const key of Object.keys(raw)) {
|
|
71
|
+
if (!known.includes(key)) errors.push(`${CONFIG_KEY}.${key}: unknown key (known: ${known.join(', ')})`);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const expect = (path, value, pred, what) => {
|
|
75
|
+
if (value !== undefined && !pred(value)) errors.push(`${path}: expected ${what}`);
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
const wt = raw.worktree;
|
|
79
|
+
if (wt !== undefined) {
|
|
80
|
+
if (!isPlainObject(wt)) errors.push(`${CONFIG_KEY}.worktree: expected an object`);
|
|
81
|
+
else {
|
|
82
|
+
const p = `${CONFIG_KEY}.worktree`;
|
|
83
|
+
expect(`${p}.baseDir`, wt.baseDir, isNonEmptyString, 'a non-empty string');
|
|
84
|
+
expect(`${p}.maxSlot`, wt.maxSlot, (v) => isInteger(v) && v >= 1, 'an integer >= 1');
|
|
85
|
+
expect(`${p}.projectName`, wt.projectName, isNonEmptyString, 'a non-empty string');
|
|
86
|
+
expect(`${p}.ports`, wt.ports, (v) => isPlainObject(v) && Object.values(v).every(isPort), 'an object of port numbers');
|
|
87
|
+
if (wt.profiles !== undefined) {
|
|
88
|
+
if (!isPlainObject(wt.profiles)) errors.push(`${p}.profiles: expected an object`);
|
|
89
|
+
else {
|
|
90
|
+
expect(`${p}.profiles.default`, wt.profiles.default, isStringArray, 'an array of profile names');
|
|
91
|
+
expect(`${p}.profiles.required`, wt.profiles.required, isStringArray, 'an array of profile names');
|
|
92
|
+
if (isStringArray(wt.profiles.default) && isStringArray(wt.profiles.required)) {
|
|
93
|
+
for (const r of wt.profiles.required) {
|
|
94
|
+
if (!wt.profiles.default.includes(r)) errors.push(`${p}.profiles.default: must include required profile "${r}"`);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
if (wt.seeds !== undefined) {
|
|
100
|
+
if (!isPlainObject(wt.seeds)) errors.push(`${p}.seeds: expected an object`);
|
|
101
|
+
else {
|
|
102
|
+
expect(`${p}.seeds.service`, wt.seeds.service, isNonEmptyString, 'a compose service name');
|
|
103
|
+
expect(`${p}.seeds.scripts`, wt.seeds.scripts, isStringArray, 'an array of npm script names');
|
|
104
|
+
if (isStringArray(wt.seeds.scripts) && wt.seeds.scripts.length > 0 && !isNonEmptyString(wt.seeds.service)) {
|
|
105
|
+
errors.push(`${p}.seeds.service: required when seeds.scripts is set`);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
if (wt.ready !== undefined) {
|
|
110
|
+
if (!isPlainObject(wt.ready)) errors.push(`${p}.ready: expected an object`);
|
|
111
|
+
else {
|
|
112
|
+
expect(`${p}.ready.url`, wt.ready.url, isNonEmptyString, 'a URL (may use ${DEVKIT_PORT_*})');
|
|
113
|
+
expect(`${p}.ready.timeoutSeconds`, wt.ready.timeoutSeconds, (v) => isInteger(v) && v > 0, 'a positive integer');
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
expect(`${p}.env`, wt.env, isStringRecord, 'an object of string values');
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const tr = raw.tracker;
|
|
121
|
+
if (tr !== undefined) {
|
|
122
|
+
if (!isPlainObject(tr)) errors.push(`${CONFIG_KEY}.tracker: expected an object`);
|
|
123
|
+
else if (!TRACKER_KINDS.includes(tr.kind)) {
|
|
124
|
+
errors.push(`${CONFIG_KEY}.tracker.kind: expected one of ${TRACKER_KINDS.join(' | ')}`);
|
|
125
|
+
} else if (tr.kind === 'jira') {
|
|
126
|
+
if (!isNonEmptyString(tr.project) || !/^[A-Z][A-Z0-9_]*$/.test(tr.project)) {
|
|
127
|
+
errors.push(`${CONFIG_KEY}.tracker.project: expected a Jira project key like "DAZ"`);
|
|
128
|
+
}
|
|
129
|
+
expect(`${CONFIG_KEY}.tracker.baseUrl`, tr.baseUrl, (v) => isNonEmptyString(v) && /^https?:\/\//.test(v), 'an http(s) URL');
|
|
130
|
+
} else if (tr.kind === 'github') {
|
|
131
|
+
expect(`${CONFIG_KEY}.tracker.prefix`, tr.prefix, (v) => isNonEmptyString(v) && /^[A-Z][A-Z0-9]*$/.test(v), 'an upper-case token like "GH"');
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const cm = raw.commits;
|
|
136
|
+
if (cm !== undefined) {
|
|
137
|
+
if (!isPlainObject(cm)) errors.push(`${CONFIG_KEY}.commits: expected an object`);
|
|
138
|
+
else {
|
|
139
|
+
const p = `${CONFIG_KEY}.commits`;
|
|
140
|
+
expect(`${p}.types`, cm.types, (v) => isStringArray(v) && v.length > 0, 'a non-empty array of commit types');
|
|
141
|
+
expect(`${p}.extraScopes`, cm.extraScopes, isStringArray, 'an array of scope names');
|
|
142
|
+
expect(`${p}.requireSigned`, cm.requireSigned, isBoolean, 'a boolean');
|
|
143
|
+
expect(`${p}.exemptAuthors`, cm.exemptAuthors, isStringArray, 'an array of GitHub logins');
|
|
144
|
+
expect(`${p}.docsUrl`, cm.docsUrl, isNonEmptyString, 'a URL');
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const ci = raw.ci;
|
|
149
|
+
if (ci !== undefined) {
|
|
150
|
+
if (!isPlainObject(ci)) errors.push(`${CONFIG_KEY}.ci: expected an object`);
|
|
151
|
+
else {
|
|
152
|
+
const p = `${CONFIG_KEY}.ci`;
|
|
153
|
+
if (ci.checks !== undefined) {
|
|
154
|
+
if (!Array.isArray(ci.checks)) errors.push(`${p}.checks: expected an array`);
|
|
155
|
+
else {
|
|
156
|
+
ci.checks.forEach((c, i) => {
|
|
157
|
+
const cp = `${p}.checks[${i}]`;
|
|
158
|
+
if (!isPlainObject(c)) return errors.push(`${cp}: expected an object`);
|
|
159
|
+
if (!isNonEmptyString(c.name)) errors.push(`${cp}.name: expected a non-empty string`);
|
|
160
|
+
if (!isStringArray(c.paths) || c.paths.length === 0) errors.push(`${cp}.paths: expected a non-empty array of regexes`);
|
|
161
|
+
else {
|
|
162
|
+
for (const re of c.paths) {
|
|
163
|
+
try {
|
|
164
|
+
new RegExp(re);
|
|
165
|
+
} catch (e) {
|
|
166
|
+
errors.push(`${cp}.paths: invalid regex ${JSON.stringify(re)} (${e.message})`);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
if (!isNonEmptyString(c.run)) errors.push(`${cp}.run: expected a shell command`);
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
if (ci.affected !== undefined) {
|
|
175
|
+
if (!isPlainObject(ci.affected)) errors.push(`${p}.affected: expected an object`);
|
|
176
|
+
else {
|
|
177
|
+
expect(`${p}.affected.contentOnly`, ci.affected.contentOnly, isStringArray, 'an array of globs');
|
|
178
|
+
expect(`${p}.affected.adopted`, ci.affected.adopted, isStringRecord, 'an object of glob → project name');
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const tc = raw.testCases;
|
|
185
|
+
if (tc !== undefined) {
|
|
186
|
+
if (!isPlainObject(tc)) errors.push(`${CONFIG_KEY}.testCases: expected an object`);
|
|
187
|
+
else {
|
|
188
|
+
expect(`${CONFIG_KEY}.testCases.dir`, tc.dir, isNonEmptyString, 'a directory path');
|
|
189
|
+
expect(`${CONFIG_KEY}.testCases.languages`, tc.languages, (v) => isStringArray(v) && v.length > 0, 'a non-empty array of language codes');
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const db = raw.db;
|
|
194
|
+
if (db !== undefined) {
|
|
195
|
+
if (!isPlainObject(db)) errors.push(`${CONFIG_KEY}.db: expected an object`);
|
|
196
|
+
else {
|
|
197
|
+
for (const k of ['service', 'user', 'name']) {
|
|
198
|
+
if (!isNonEmptyString(db[k])) errors.push(`${CONFIG_KEY}.db.${k}: expected a non-empty string`);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const dk = raw.docker;
|
|
204
|
+
if (dk !== undefined) {
|
|
205
|
+
if (!isPlainObject(dk)) errors.push(`${CONFIG_KEY}.docker: expected an object`);
|
|
206
|
+
else expect(`${CONFIG_KEY}.docker.preUp`, dk.preUp, (v) => v === null || isString(v), 'a shell command or null');
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
const i18n = raw.i18n;
|
|
210
|
+
if (i18n !== undefined) {
|
|
211
|
+
if (!isPlainObject(i18n)) errors.push(`${CONFIG_KEY}.i18n: expected an object`);
|
|
212
|
+
else {
|
|
213
|
+
expect(`${CONFIG_KEY}.i18n.dir`, i18n.dir, isNonEmptyString, 'a directory path');
|
|
214
|
+
expect(`${CONFIG_KEY}.i18n.languages`, i18n.languages, isStringArray, 'an array of language codes');
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
return errors;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* Apply defaults. `rootName` is the sanitized root package name (or directory name),
|
|
223
|
+
* used for the worktree base dir, the slot-0 compose project and dev image names.
|
|
224
|
+
* Sections a project has not declared resolve to `null` (worktree, testCases, db) so
|
|
225
|
+
* commands can tell "not configured" from "configured with defaults".
|
|
226
|
+
*/
|
|
227
|
+
export function resolveConfig(raw = {}, { rootName }) {
|
|
228
|
+
const wt = raw.worktree;
|
|
229
|
+
const worktree =
|
|
230
|
+
wt === undefined
|
|
231
|
+
? null
|
|
232
|
+
: {
|
|
233
|
+
baseDir: wt.baseDir ?? `../${rootName}-worktrees`,
|
|
234
|
+
maxSlot: wt.maxSlot ?? DEFAULT_MAX_SLOT,
|
|
235
|
+
projectName: wt.projectName ?? rootName,
|
|
236
|
+
ports: { ...(wt.ports ?? {}) },
|
|
237
|
+
profiles: {
|
|
238
|
+
default: [...(wt.profiles?.default ?? [])],
|
|
239
|
+
required: [...(wt.profiles?.required ?? [])],
|
|
240
|
+
},
|
|
241
|
+
seeds: { service: wt.seeds?.service ?? null, scripts: [...(wt.seeds?.scripts ?? [])] },
|
|
242
|
+
ready: wt.ready?.url ? { url: wt.ready.url, timeoutSeconds: wt.ready.timeoutSeconds ?? 600 } : null,
|
|
243
|
+
env: { ...(wt.env ?? {}) },
|
|
244
|
+
};
|
|
245
|
+
|
|
246
|
+
const tr = raw.tracker ?? { kind: 'none' };
|
|
247
|
+
const tracker =
|
|
248
|
+
tr.kind === 'jira'
|
|
249
|
+
? { kind: 'jira', project: tr.project, baseUrl: tr.baseUrl ?? null }
|
|
250
|
+
: tr.kind === 'github'
|
|
251
|
+
? { kind: 'github', prefix: tr.prefix ?? DEFAULT_GITHUB_PREFIX }
|
|
252
|
+
: { kind: 'none' };
|
|
253
|
+
|
|
254
|
+
const cm = raw.commits ?? {};
|
|
255
|
+
const commits = {
|
|
256
|
+
types: [...(cm.types ?? DEFAULT_COMMIT_TYPES)],
|
|
257
|
+
extraScopes: [...(cm.extraScopes ?? DEFAULT_EXTRA_SCOPES)],
|
|
258
|
+
requireSigned: cm.requireSigned ?? true,
|
|
259
|
+
exemptAuthors: [...(cm.exemptAuthors ?? DEFAULT_EXEMPT_AUTHORS)],
|
|
260
|
+
docsUrl: cm.docsUrl ?? null,
|
|
261
|
+
};
|
|
262
|
+
|
|
263
|
+
const ci = {
|
|
264
|
+
checks: (raw.ci?.checks ?? []).map((c) => ({ name: c.name, paths: [...c.paths], run: c.run })),
|
|
265
|
+
affected: {
|
|
266
|
+
contentOnly: [...(raw.ci?.affected?.contentOnly ?? [])],
|
|
267
|
+
adopted: { ...(raw.ci?.affected?.adopted ?? {}) },
|
|
268
|
+
},
|
|
269
|
+
};
|
|
270
|
+
|
|
271
|
+
const tc = raw.testCases;
|
|
272
|
+
const testCases = tc === undefined ? null : { dir: tc.dir ?? 'docs/testing', languages: [...(tc.languages ?? ['en', 'nl'])] };
|
|
273
|
+
|
|
274
|
+
const db = raw.db ? { service: raw.db.service, user: raw.db.user, name: raw.db.name } : null;
|
|
275
|
+
const docker = { preUp: typeof raw.docker?.preUp === 'string' && raw.docker.preUp.trim() ? raw.docker.preUp.trim() : null };
|
|
276
|
+
const i18n = { dir: raw.i18n?.dir ?? 'public/assets/i18n', languages: [...(raw.i18n?.languages ?? ['en', 'nl'])] };
|
|
277
|
+
|
|
278
|
+
return { worktree, tracker, commits, ci, testCases, db, docker, i18n };
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* Load, validate and resolve the config of the repo containing `cwd` (or of an explicit
|
|
283
|
+
* `root`). Never throws for a missing block — `raw` is `{}` and every section takes defaults.
|
|
284
|
+
*/
|
|
285
|
+
export function loadConfig({ cwd = process.cwd(), root: explicitRoot } = {}) {
|
|
286
|
+
const root = explicitRoot ?? findRepoRoot(cwd);
|
|
287
|
+
let pkg = {};
|
|
288
|
+
try {
|
|
289
|
+
pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
|
|
290
|
+
} catch {
|
|
291
|
+
pkg = {};
|
|
292
|
+
}
|
|
293
|
+
const raw = pkg[CONFIG_KEY] ?? {};
|
|
294
|
+
const rootName = sanitizeName(pkg.name || basename(root));
|
|
295
|
+
const errors = validateConfig(pkg[CONFIG_KEY]);
|
|
296
|
+
const config = errors.length === 0 ? resolveConfig(raw, { rootName }) : null;
|
|
297
|
+
return { root, rootName, pkg, raw, errors, config };
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** `loadConfig` that throws an actionable error when the block is invalid. */
|
|
301
|
+
export function requireConfig(opts) {
|
|
302
|
+
const loaded = loadConfig(opts);
|
|
303
|
+
if (loaded.errors.length > 0) {
|
|
304
|
+
throw new Error(`Invalid "${CONFIG_KEY}" block in ${join(loaded.root, 'package.json')}:\n - ${loaded.errors.join('\n - ')}`);
|
|
305
|
+
}
|
|
306
|
+
return loaded;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/** Sections that must be present for a feature; throws with the exact key to add. */
|
|
310
|
+
export function requireSection(loaded, section) {
|
|
311
|
+
const value = loaded.config?.[section];
|
|
312
|
+
if (value === null || value === undefined) {
|
|
313
|
+
throw new Error(`Missing "${CONFIG_KEY}.${section}" in ${join(loaded.root, 'package.json')} — run \`hassan-devkit init\` to scaffold it.`);
|
|
314
|
+
}
|
|
315
|
+
return value;
|
|
316
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Everything a project must NOT declare because it follows from the workspace, the
|
|
8
|
+
* tracker kind or the repo: commit scopes, ticket tokens, the commit-subject regex,
|
|
9
|
+
* dev image names and the content-addressed image tag, the canonical remote.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/** `@scope/My Name` → `my-name`; used for the worktree base dir, compose project, images. */
|
|
13
|
+
export function sanitizeName(name) {
|
|
14
|
+
return String(name ?? '')
|
|
15
|
+
.replace(/^@[^/]+\//, '')
|
|
16
|
+
.toLowerCase()
|
|
17
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
18
|
+
.replace(/^-+|-+$/g, '') || 'project';
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Commit scopes = every workspace project name + the fixed extras, sorted, unique. */
|
|
22
|
+
export function commitScopes(projects, extraScopes = []) {
|
|
23
|
+
return [...new Set([...projects.map((p) => p.name), ...extraScopes])].sort();
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Regex source for the ticket token at the start of a branch name / commit subject. */
|
|
27
|
+
export function ticketPattern(tracker) {
|
|
28
|
+
if (tracker?.kind === 'jira') return `${tracker.project}-[0-9]+`;
|
|
29
|
+
if (tracker?.kind === 'github') return `${tracker.prefix}-[0-9]+`;
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** `DAZ-42-FE-Some-Feature` → `DAZ-42`; `null` when the branch carries no ticket. */
|
|
34
|
+
export function ticketKeyFromBranch(branch, tracker) {
|
|
35
|
+
const pattern = ticketPattern(tracker);
|
|
36
|
+
if (!pattern) return null;
|
|
37
|
+
const m = new RegExp(`^(${pattern})(?:-|$)`).exec(branch ?? '');
|
|
38
|
+
return m ? m[1] : null;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** GitHub issue number from a ticket key (`GH-12` → 12); Jira keys return `null`. */
|
|
42
|
+
export function issueNumberFromKey(key, tracker) {
|
|
43
|
+
if (tracker?.kind !== 'github' || !key) return null;
|
|
44
|
+
const m = new RegExp(`^${tracker.prefix}-([0-9]+)$`).exec(key);
|
|
45
|
+
return m ? Number(m[1]) : null;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* The commit-subject regex CI and the commit-writer agent share:
|
|
52
|
+
* `^<TICKET> (<types>)\((<scopes>)\): [a-z]` (ticket part omitted for tracker `none`)
|
|
53
|
+
*/
|
|
54
|
+
export function commitSubjectPattern({ tracker, commits }, scopes) {
|
|
55
|
+
const ticket = ticketPattern(tracker);
|
|
56
|
+
const types = commits.types.map(escapeRe).join('|');
|
|
57
|
+
const scopeAlt = scopes.map(escapeRe).join('|');
|
|
58
|
+
return `^${ticket ? `${ticket} ` : ''}(${types})\\((${scopeAlt})\\): [a-z]`;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function imageName(rootName, service, tag) {
|
|
62
|
+
return `${rootName}-dev-${service}:${tag}`;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const DEV_DOCKERFILE_RE = /^Dockerfile(\..+)?\.dev$/;
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* The files whose content decides a dev image: lockfile, workspace file, root + every
|
|
69
|
+
* project package.json, the Dockerfiles of the compose file's buildable services (`extra`,
|
|
70
|
+
* derived from `docker compose config`) and, as a fallback, every `docker/Dockerfile*.dev`.
|
|
71
|
+
* Sorted, relative to root, missing files dropped.
|
|
72
|
+
*/
|
|
73
|
+
export function imageTagInputs(root, projects, extra = []) {
|
|
74
|
+
const files = ['pnpm-lock.yaml', 'pnpm-workspace.yaml', 'package.json', ...extra];
|
|
75
|
+
for (const p of projects) files.push(`${p.dir}/package.json`);
|
|
76
|
+
const dockerDir = join(root, 'docker');
|
|
77
|
+
if (extra.length === 0 && existsSync(dockerDir)) {
|
|
78
|
+
for (const f of readdirSync(dockerDir)) if (DEV_DOCKERFILE_RE.test(f)) files.push(`docker/${f}`);
|
|
79
|
+
}
|
|
80
|
+
return [...new Set(files)].filter((f) => existsSync(join(root, f))).sort();
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** sha256 over `<path>\n<content>` of every input, first 12 hex chars. */
|
|
84
|
+
export function imageTag(root, inputs) {
|
|
85
|
+
const hash = createHash('sha256');
|
|
86
|
+
for (const rel of inputs) {
|
|
87
|
+
hash.update(rel);
|
|
88
|
+
hash.update('\n');
|
|
89
|
+
hash.update(readFileSync(join(root, rel)));
|
|
90
|
+
hash.update('\n');
|
|
91
|
+
}
|
|
92
|
+
return hash.digest('hex').slice(0, 12);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** The canonical remote: `upstream` when the fork model is in use, else `origin`. */
|
|
96
|
+
export function baseRemote(root) {
|
|
97
|
+
try {
|
|
98
|
+
const remotes = execFileSync('git', ['remote'], { cwd: root, stdio: ['ignore', 'pipe', 'ignore'] })
|
|
99
|
+
.toString()
|
|
100
|
+
.split('\n')
|
|
101
|
+
.map((s) => s.trim())
|
|
102
|
+
.filter(Boolean);
|
|
103
|
+
return remotes.includes('upstream') ? 'upstream' : 'origin';
|
|
104
|
+
} catch {
|
|
105
|
+
return 'origin';
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** `minioConsole` → `MINIO_CONSOLE`; `api` → `API`. */
|
|
110
|
+
export function toEnvKey(name) {
|
|
111
|
+
return String(name)
|
|
112
|
+
.replace(/([a-z0-9])([A-Z])/g, '$1_$2')
|
|
113
|
+
.replace(/[^A-Za-z0-9]+/g, '_')
|
|
114
|
+
.toUpperCase();
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Host ports of slot N: every base port + N*10, keyed `DEVKIT_PORT_<KEY>`. */
|
|
118
|
+
export function portsForSlot(ports, slot) {
|
|
119
|
+
const offset = slot * 10;
|
|
120
|
+
return Object.fromEntries(
|
|
121
|
+
Object.entries(ports)
|
|
122
|
+
.map(([name, base]) => [`DEVKIT_PORT_${toEnvKey(name)}`, base + offset])
|
|
123
|
+
.sort(([a], [b]) => a.localeCompare(b)),
|
|
124
|
+
);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Expand `${DEVKIT_*}` references in a string against the managed values. */
|
|
128
|
+
export function expandEnv(template, values) {
|
|
129
|
+
return String(template).replace(/\$\{([A-Z0-9_]+)\}/g, (m, key) => (key in values ? String(values[key]) : m));
|
|
130
|
+
}
|
|
@@ -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));
|