@coding-with-hassan/devkit 1.0.0-next.0 → 1.0.0-next.2
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 +47 -1
- 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 +16 -2
- package/src/commands/ci.js +200 -0
- package/src/commands/claude.js +24 -0
- package/src/commands/docker.js +3 -2
- package/src/commands/hooks.js +38 -20
- package/src/commands/init.js +98 -14
- package/src/commands/test-cases.js +31 -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/config.js +11 -3
- package/src/core/test-cases/generate.js +287 -0
- package/src/core/test-cases/loader.mjs +40 -0
- package/src/core/worktrees.js +17 -1
- package/src/index.js +6 -0
- package/test-cases.d.ts +48 -0
- package/test-cases.js +26 -0
package/src/commands/hooks.js
CHANGED
|
@@ -6,31 +6,49 @@ import { runCommand, exitOnFailure } from '../util/run.js';
|
|
|
6
6
|
const here = dirname(fileURLToPath(import.meta.url));
|
|
7
7
|
const HOOK_SOURCE = resolve(here, '../../hooks/pre-commit.sh');
|
|
8
8
|
|
|
9
|
+
/**
|
|
10
|
+
* `hooks:install` runs from the consumer's `prepare` script, i.e. on every `pnpm install`
|
|
11
|
+
* — in the main checkout, in every worktree, AND inside container image builds (the dev
|
|
12
|
+
* Dockerfiles install with the root package.json present). Two rules follow:
|
|
13
|
+
* - no git checkout (no `.git` file/dir, or `HUSKY=0` as the Dockerfiles set) → there is
|
|
14
|
+
* nothing to hook; log and return without failing the install;
|
|
15
|
+
* - in a real checkout, husky's shim directory (`.husky/_`) is per checkout and git
|
|
16
|
+
* SILENTLY skips every hook when `core.hooksPath` points at a missing directory, so the
|
|
17
|
+
* shims are (re)created with `pnpm exec husky` and their absence afterwards is a hard error.
|
|
18
|
+
* `husky init` is never used: it rewrites the consumer's `prepare` script to plain `husky`.
|
|
19
|
+
*/
|
|
20
|
+
export async function installHooks({ cwd = process.cwd(), env = process.env, log = console.log } = {}) {
|
|
21
|
+
if (env.HUSKY === '0') {
|
|
22
|
+
log('hooks: HUSKY=0 — skipping the pre-commit hook install');
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
if (!existsSync(resolve(cwd, '.git'))) {
|
|
26
|
+
log('hooks: no git checkout here (container build or export) — skipping the pre-commit hook install');
|
|
27
|
+
return false;
|
|
28
|
+
}
|
|
29
|
+
const husky = resolve(cwd, '.husky');
|
|
30
|
+
mkdirSync(husky, { recursive: true });
|
|
31
|
+
if (!existsSync(resolve(husky, '_', 'pre-commit'))) {
|
|
32
|
+
await runCommand('pnpm', ['exec', 'husky'], { cwd });
|
|
33
|
+
}
|
|
34
|
+
const target = resolve(husky, 'pre-commit');
|
|
35
|
+
copyFileSync(HOOK_SOURCE, target);
|
|
36
|
+
chmodSync(target, 0o755);
|
|
37
|
+
log(`Wrote ${target}`);
|
|
38
|
+
if (!existsSync(resolve(husky, '_', 'pre-commit'))) {
|
|
39
|
+
throw new Error(`husky shims missing in ${husky}/_ — git would silently skip all hooks; run \`pnpm exec husky\``);
|
|
40
|
+
}
|
|
41
|
+
return true;
|
|
42
|
+
}
|
|
43
|
+
|
|
9
44
|
export function registerHooks(cli) {
|
|
10
45
|
cli
|
|
11
|
-
.command('hooks:install', 'Install husky and the shared pre-commit hook into the current repo')
|
|
12
|
-
.action(() =>
|
|
13
|
-
exitOnFailure(
|
|
14
|
-
(async () => {
|
|
15
|
-
if (!existsSync('.husky')) {
|
|
16
|
-
await runCommand('pnpm', ['exec', 'husky', 'init']);
|
|
17
|
-
}
|
|
18
|
-
const target = resolve(process.cwd(), '.husky/pre-commit');
|
|
19
|
-
mkdirSync(dirname(target), { recursive: true });
|
|
20
|
-
copyFileSync(HOOK_SOURCE, target);
|
|
21
|
-
chmodSync(target, 0o755);
|
|
22
|
-
console.log(`Wrote ${target}`);
|
|
23
|
-
})(),
|
|
24
|
-
),
|
|
25
|
-
);
|
|
46
|
+
.command('hooks:install', 'Install husky (and its per-checkout shims) and the shared pre-commit hook into the current repo')
|
|
47
|
+
.action(() => exitOnFailure(installHooks()));
|
|
26
48
|
|
|
27
49
|
cli
|
|
28
50
|
.command('pre-commit', 'Body of the shared pre-commit hook (called from .husky/pre-commit)')
|
|
29
|
-
.action(() =>
|
|
30
|
-
exitOnFailure(
|
|
31
|
-
runCommand('sh', [HOOK_SOURCE]),
|
|
32
|
-
),
|
|
33
|
-
);
|
|
51
|
+
.action(() => exitOnFailure(runCommand('sh', [HOOK_SOURCE])));
|
|
34
52
|
|
|
35
53
|
cli
|
|
36
54
|
.command('hooks:print', 'Print the shared pre-commit hook content to stdout')
|
package/src/commands/init.js
CHANGED
|
@@ -3,6 +3,10 @@ import { join } from 'node:path';
|
|
|
3
3
|
import { COMPOSE_FILE, CONFIG_KEY, ENV_DIST_FILE, loadConfig, resolveConfig } from '../core/config.js';
|
|
4
4
|
import { managedValues, writeManagedBlock } from '../core/env-block.js';
|
|
5
5
|
import { agentsDocs } from '../core/agents-docs.js';
|
|
6
|
+
import { WORKFLOW_PATH, renderWorkflow } from '../core/ci/workflow.js';
|
|
7
|
+
import { claudePlans } from '../core/claude.js';
|
|
8
|
+
import { listDataFiles } from '../core/test-cases/generate.js';
|
|
9
|
+
import { worktreeActive } from '../core/worktrees.js';
|
|
6
10
|
import { applyPlan, formatJson, mergeMissing, planFile } from '../core/scaffold.js';
|
|
7
11
|
import { exitOnFailure } from '../util/run.js';
|
|
8
12
|
|
|
@@ -32,11 +36,21 @@ const DOCKER_SCRIPTS = {
|
|
|
32
36
|
'docker:dev:down': 'hassan-devkit docker:down',
|
|
33
37
|
'docker:dev:logs': 'hassan-devkit docker:logs',
|
|
34
38
|
};
|
|
35
|
-
const HOOK_SCRIPTS = { prepare: 'hassan-devkit hooks:install' };
|
|
39
|
+
const HOOK_SCRIPTS = { prepare: 'hassan-devkit hooks:install && hassan-devkit claude:install' };
|
|
40
|
+
const CLAUDE_ONLY_SCRIPTS = { prepare: 'hassan-devkit claude:install' };
|
|
36
41
|
const SCRIPT_DEFAULTS = { ...DOCKER_SCRIPTS, ...HOOK_SCRIPTS };
|
|
37
42
|
|
|
38
43
|
const usesHusky = (pkg) => Boolean(pkg.devDependencies?.husky || pkg.dependencies?.husky);
|
|
39
44
|
|
|
45
|
+
const LINT_STAGED_CONFIG = `// Targets are derived from the workspace (every project with an ESLint/Prettier config).
|
|
46
|
+
// Options: { exclude: ['api-client'] } to leave a project alone (e.g. generated code that must
|
|
47
|
+
// stay as its generator wrote it), { extra: { 'scripts/**/*.mjs': ['prettier --write'] } } for
|
|
48
|
+
// files outside any project.
|
|
49
|
+
import lintStaged from '@coding-with-hassan/devkit/lint-staged';
|
|
50
|
+
|
|
51
|
+
export default lintStaged();
|
|
52
|
+
`;
|
|
53
|
+
|
|
40
54
|
const PRE_COMMIT_EXTRA = `#!/bin/sh
|
|
41
55
|
# Project-specific pre-commit guards. Invoked first by the shared hook that
|
|
42
56
|
# @coding-with-hassan/devkit installs (\`hassan-devkit hooks:install\`); exit non-zero to
|
|
@@ -45,6 +59,31 @@ const PRE_COMMIT_EXTRA = `#!/bin/sh
|
|
|
45
59
|
exit 0
|
|
46
60
|
`;
|
|
47
61
|
|
|
62
|
+
const TC_DATA_STARTER = `// Bilingual acceptance test cases — the quality gate of this project (see CLAUDE.md).
|
|
63
|
+
// Every change to user-facing behaviour updates the cases here; regenerate the workbooks with
|
|
64
|
+
// \`hassan-devkit test-cases:generate\` (they are gitignored artifacts — commit this file only).
|
|
65
|
+
// One file per suite (\`tc-data-<suite>.ts\`), one area per epic, case IDs \`<AREA>-<nn>\`.
|
|
66
|
+
import { tc, type Area, type KnownIssue, type Readme } from '@coding-with-hassan/devkit/test-cases';
|
|
67
|
+
|
|
68
|
+
export const APP_AREAS: Area[] = [
|
|
69
|
+
{
|
|
70
|
+
key: 'AUTH',
|
|
71
|
+
name: { en: 'Authentication', nl: 'Authenticatie' },
|
|
72
|
+
tab: '1F3864',
|
|
73
|
+
cases: [
|
|
74
|
+
tc('AUTH-01', 'H', 'Sign in with valid credentials', 'Inloggen met geldige gegevens', 'A user account exists.', 'Er bestaat een gebruikersaccount.', '1. Open the sign-in page.\\n2. Enter the credentials and submit.', '1. Open de inlogpagina.\\n2. Vul de gegevens in en verzend.', 'The user lands on the start page, signed in.', 'De gebruiker komt ingelogd op de startpagina.'),
|
|
75
|
+
],
|
|
76
|
+
},
|
|
77
|
+
];
|
|
78
|
+
|
|
79
|
+
export const APP_KNOWN_ISSUES: KnownIssue[] = [];
|
|
80
|
+
|
|
81
|
+
export const APP_README: Readme = {
|
|
82
|
+
en: [['How to test', ['Work through every sheet; set Status per case and note findings in Notes.']]],
|
|
83
|
+
nl: [['Hoe te testen', ['Loop elk tabblad door; zet per test de Status en noteer bevindingen bij Notities.']]],
|
|
84
|
+
};
|
|
85
|
+
`;
|
|
86
|
+
|
|
48
87
|
/**
|
|
49
88
|
* Plan the package.json changes: config skeleton + default scripts, only where missing.
|
|
50
89
|
* Docker scripts only make sense with a compose file, the `prepare` hook installer only
|
|
@@ -56,7 +95,7 @@ export function planPackageJson(root, pkg) {
|
|
|
56
95
|
next[CONFIG_KEY] ??= {};
|
|
57
96
|
added.push(...mergeMissing(next[CONFIG_KEY], structuredClone(CONFIG_SKELETON), CONFIG_KEY));
|
|
58
97
|
next.scripts ??= {};
|
|
59
|
-
const scripts = { ...(existsSync(join(root, COMPOSE_FILE)) ? DOCKER_SCRIPTS : {}), ...(usesHusky(pkg) ? HOOK_SCRIPTS :
|
|
98
|
+
const scripts = { ...(existsSync(join(root, COMPOSE_FILE)) ? DOCKER_SCRIPTS : {}), ...(usesHusky(pkg) ? HOOK_SCRIPTS : CLAUDE_ONLY_SCRIPTS) };
|
|
60
99
|
added.push(...mergeMissing(next.scripts, scripts, 'scripts'));
|
|
61
100
|
return { plan: planFile(root, 'package.json', formatJson(next), { managed: true }), added, next };
|
|
62
101
|
}
|
|
@@ -64,9 +103,9 @@ export function planPackageJson(root, pkg) {
|
|
|
64
103
|
/** `.env.dist` gets the slot-0 managed block so a fresh clone's `.env` starts valid. */
|
|
65
104
|
export function planEnvDist(root, config, rootName) {
|
|
66
105
|
const wt = config.worktree;
|
|
67
|
-
// An untouched skeleton
|
|
68
|
-
//
|
|
69
|
-
if (!wt ||
|
|
106
|
+
// An untouched skeleton would write an empty COMPOSE_PROFILES= that the compose guard
|
|
107
|
+
// rejects — same activation rule as the worktree commands and docker:up.
|
|
108
|
+
if (!worktreeActive(wt, { hasStack: existsSync(join(root, COMPOSE_FILE)) }) || Object.keys(wt.ports).length === 0) return null;
|
|
70
109
|
const values = managedValues({
|
|
71
110
|
slot: 0,
|
|
72
111
|
projectName: wt.projectName ?? rootName,
|
|
@@ -83,30 +122,74 @@ export function planEnvDist(root, config, rootName) {
|
|
|
83
122
|
return planFile(root, ENV_DIST_FILE, content, { managed: true });
|
|
84
123
|
}
|
|
85
124
|
|
|
86
|
-
|
|
125
|
+
/**
|
|
126
|
+
* The parts `init` can scaffold; `--only a,b` restricts a run to some of them so an existing
|
|
127
|
+
* repo can adopt the way of working one piece at a time (config first, the Claude layer last).
|
|
128
|
+
*/
|
|
129
|
+
export const INIT_PARTS = {
|
|
130
|
+
config: 'the hassan-devkit block and default scripts in package.json',
|
|
131
|
+
env: 'the slot-0 managed block in .env.dist',
|
|
132
|
+
hooks: 'the pre-commit seam and lint-staged.config.mjs',
|
|
133
|
+
agents: 'docs/agents/*.md rendered from the tracker config',
|
|
134
|
+
ci: 'the thin .github/workflows/ci.yml',
|
|
135
|
+
claude: 'the CLAUDE.md import, agent/skill stubs and the PR-assignee hook',
|
|
136
|
+
'test-cases': 'a starter docs/testing data file',
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
export function parseOnly(only) {
|
|
140
|
+
if (only === undefined || only === null || only === true) return null;
|
|
141
|
+
const parts = (Array.isArray(only) ? only : String(only).split(',')).map((p) => p.trim()).filter(Boolean);
|
|
142
|
+
const unknown = parts.filter((p) => !(p in INIT_PARTS));
|
|
143
|
+
if (unknown.length) throw new Error(`unknown init part(s) ${unknown.join(', ')} — known: ${Object.keys(INIT_PARTS).join(', ')}`);
|
|
144
|
+
return new Set(parts);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export function buildPlans(loaded, notes = [], { only = null } = {}) {
|
|
87
148
|
const { root, rootName, pkg } = loaded;
|
|
149
|
+
const want = (part) => only === null || only.has(part);
|
|
88
150
|
const plans = [];
|
|
89
151
|
const { plan: pkgPlan, next } = planPackageJson(root, pkg);
|
|
90
|
-
plans.push(pkgPlan);
|
|
152
|
+
if (want('config')) plans.push(pkgPlan);
|
|
91
153
|
// Resolve against the package.json we are ABOUT to write, so `.env.dist` reflects a
|
|
92
154
|
// worktree block the skeleton just added.
|
|
93
155
|
const effective = resolveConfig(next[CONFIG_KEY] ?? {}, { rootName });
|
|
94
|
-
const envDist = planEnvDist(root, effective, rootName);
|
|
156
|
+
const envDist = want('env') ? planEnvDist(root, effective, rootName) : null;
|
|
95
157
|
if (envDist) plans.push(envDist);
|
|
96
|
-
if (usesHusky(pkg))
|
|
158
|
+
if (want('hooks') && usesHusky(pkg)) {
|
|
159
|
+
plans.push(planFile(root, 'scripts/pre-commit-extra.sh', PRE_COMMIT_EXTRA, { mode: 0o755 }));
|
|
160
|
+
// lint-staged only reads one config file; a legacy hand-written `.js` must go first.
|
|
161
|
+
const legacy = ['lint-staged.config.js', 'lint-staged.config.cjs', '.lintstagedrc', '.lintstagedrc.js', '.lintstagedrc.json'].find((f) => existsSync(join(root, f)));
|
|
162
|
+
if (legacy) notes.push(`${legacy} exists — lint-staged reads only one config; replace it with the scaffolded lint-staged.config.mjs (derived targets) or delete the new file`);
|
|
163
|
+
plans.push(planFile(root, 'lint-staged.config.mjs', LINT_STAGED_CONFIG));
|
|
164
|
+
}
|
|
97
165
|
// The skills' tracker/label/domain adapters are a function of the tracker config: managed,
|
|
98
166
|
// so a tracker change (or a devkit bump that rewords them) flows on the next init.
|
|
99
|
-
for (const [path, content] of agentsDocs(effective.tracker)) plans.push(planFile(root, path, content, { managed: true }));
|
|
167
|
+
if (want('agents')) for (const [path, content] of agentsDocs(effective.tracker)) plans.push(planFile(root, path, content, { managed: true }));
|
|
168
|
+
// The thin CI workflow: only for Nx workspaces (ci:affected / ci:cache need nx). Not
|
|
169
|
+
// managed — a project may have edited it, so drift is reported by ci:doctor and fixed
|
|
170
|
+
// with --force.
|
|
171
|
+
if (want('ci') && existsSync(join(root, 'nx.json'))) {
|
|
172
|
+
plans.push(planFile(root, WORKFLOW_PATH, renderWorkflow({ nodeVersion: effective.ci.nodeVersion, baseBranch: effective.ci.baseBranch, exemptAuthors: effective.commits.exemptAuthors })));
|
|
173
|
+
}
|
|
174
|
+
// The Claude layer: standards import, agent/skill stubs, PR-assignee hook.
|
|
175
|
+
if (want('claude')) plans.push(...claudePlans(root));
|
|
176
|
+
// Acceptance cases: a starter data file when the section is configured and none exists.
|
|
177
|
+
if (want('test-cases') && effective.testCases && listDataFiles(join(root, effective.testCases.dir)).length === 0) {
|
|
178
|
+
plans.push(planFile(root, `${effective.testCases.dir}/tc-data-app.ts`, TC_DATA_STARTER));
|
|
179
|
+
}
|
|
100
180
|
return plans;
|
|
101
181
|
}
|
|
102
182
|
|
|
103
|
-
export async function init({ force = false, dryRun = false, cwd = process.cwd(), root, log = console.log } = {}) {
|
|
183
|
+
export async function init({ force = false, dryRun = false, only, cwd = process.cwd(), root, log = console.log } = {}) {
|
|
184
|
+
const parts = parseOnly(only);
|
|
104
185
|
const loaded = loadConfig({ cwd, root });
|
|
105
186
|
if (loaded.errors.length > 0) {
|
|
106
187
|
throw new Error(`Fix the "${CONFIG_KEY}" block first:\n - ${loaded.errors.join('\n - ')}`);
|
|
107
188
|
}
|
|
108
|
-
log(`hassan-devkit init → ${loaded.root}${dryRun ? ' (dry run)' : ''}`);
|
|
109
|
-
const
|
|
189
|
+
log(`hassan-devkit init → ${loaded.root}${parts ? ` (only: ${[...parts].join(', ')})` : ''}${dryRun ? ' (dry run)' : ''}`);
|
|
190
|
+
const notes = [];
|
|
191
|
+
const summary = applyPlan(loaded.root, buildPlans(loaded, notes, { only: parts }), { force, dryRun, log });
|
|
192
|
+
for (const n of notes) log(` note: ${n}`);
|
|
110
193
|
const next = [
|
|
111
194
|
`Fill in "${CONFIG_KEY}" in package.json (ports, profiles, seeds, tracker) and re-run \`hassan-devkit init\` to refresh ${ENV_DIST_FILE}.`,
|
|
112
195
|
'Check the result with `hassan-devkit config:show` and `hassan-devkit commits:show`.',
|
|
@@ -120,7 +203,8 @@ export function registerInit(cli) {
|
|
|
120
203
|
.command('init', 'Scaffold the devkit way of working into this workspace (idempotent; --force overwrites edited files)')
|
|
121
204
|
.option('--force', 'Overwrite files that differ from the template (a diff is printed first)')
|
|
122
205
|
.option('--dry-run', 'Show what would change without writing')
|
|
123
|
-
.
|
|
206
|
+
.option('--only <parts>', `Scaffold only these parts (comma-separated): ${Object.keys(INIT_PARTS).join(', ')}`)
|
|
207
|
+
.action((opts) => exitOnFailure(init({ force: Boolean(opts.force), dryRun: Boolean(opts.dryRun), only: opts.only })));
|
|
124
208
|
}
|
|
125
209
|
|
|
126
210
|
// Exported for the tests and for later scaffolds that extend the plan.
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { join } from 'node:path';
|
|
2
|
+
import { requireConfig, requireSection } from '../core/config.js';
|
|
3
|
+
import { generate } from '../core/test-cases/generate.js';
|
|
4
|
+
import { exitOnFailure } from '../util/run.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* `test-cases:generate` — the acceptance-case workbooks from `<testCases.dir>/tc-data-*.ts`.
|
|
8
|
+
* Languages come from `testCases.languages`, the title from `testCases.title` (default: the
|
|
9
|
+
* root package name). Workbooks are written next to the data and are gitignored artifacts.
|
|
10
|
+
*/
|
|
11
|
+
export function registerTestCases(cli) {
|
|
12
|
+
cli
|
|
13
|
+
.command('test-cases:generate', 'Generate the bilingual acceptance-test workbooks from docs/testing/tc-data-*.ts')
|
|
14
|
+
.option('--lang <code>', 'Only this language')
|
|
15
|
+
.option('--testers <file>', 'JSON array of testers; writes one personalised workbook per tester')
|
|
16
|
+
.action((opts) =>
|
|
17
|
+
exitOnFailure(
|
|
18
|
+
Promise.resolve().then(() => {
|
|
19
|
+
const loaded = requireConfig();
|
|
20
|
+
const tc = requireSection(loaded, 'testCases');
|
|
21
|
+
return generate({
|
|
22
|
+
dir: join(loaded.root, tc.dir),
|
|
23
|
+
languages: tc.languages,
|
|
24
|
+
project: tc.title ?? loaded.pkg.name ?? loaded.rootName,
|
|
25
|
+
onlyLang: opts.lang ?? null,
|
|
26
|
+
testersFile: opts.testers ? join(process.cwd(), opts.testers) : null,
|
|
27
|
+
});
|
|
28
|
+
}),
|
|
29
|
+
),
|
|
30
|
+
);
|
|
31
|
+
}
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
|
|
2
|
+
import { tmpdir } from 'node:os';
|
|
3
|
+
import { dirname, join } from 'node:path';
|
|
4
|
+
import { capture, run } from '../exec.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Affected lint/build/format:check that ignores files which cannot change the outcome.
|
|
8
|
+
*
|
|
9
|
+
* `nx affected` maps changed files → projects → dependents and does NOT look at target
|
|
10
|
+
* inputs, so a translation-JSON edit in a shared lib marks every app affected. This wrapper
|
|
11
|
+
* computes the changed-file list itself, drops the files no target reads, and hands the
|
|
12
|
+
* rest to Nx. `.nxignore` would achieve the same affected result but also removes the files
|
|
13
|
+
* from task hashing (a cached build would replay stale content) — hence the filter lives
|
|
14
|
+
* here and the Nx cache is left intact.
|
|
15
|
+
*
|
|
16
|
+
* Two kinds of targets:
|
|
17
|
+
* - graph targets (`build`): the touched projects AND their dependents, exactly as
|
|
18
|
+
* `nx affected` computes them from the filtered file list;
|
|
19
|
+
* - own-files targets (`lint`, `format:check`, …): only projects that own a changed file.
|
|
20
|
+
* Valid as long as no ESLint config uses type-aware rules across projects.
|
|
21
|
+
*
|
|
22
|
+
* Project-specific lists come from `ci.affected` in the config: `contentOnly` (globs of
|
|
23
|
+
* files copied verbatim into outputs — skipped unless `--with-content`) and `adopted`
|
|
24
|
+
* (glob → project that reads files outside every project root).
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
export const DOCS_ONLY = [/\.md$/, /^docs\//];
|
|
28
|
+
export const WORKSPACE_GLOBALS = [/^package\.json$/, /^pnpm-lock\.yaml$/, /^pnpm-workspace\.yaml$/, /^nx\.json$/, /^tsconfig[^/]*\.json$/, /^\.npmrc$/];
|
|
29
|
+
export const GRAPH_TARGETS = new Set(['build']);
|
|
30
|
+
|
|
31
|
+
/** Pure: minimal glob → anchored RegExp (`**`, `*`, `?`). */
|
|
32
|
+
export function globToRegExp(glob) {
|
|
33
|
+
let re = '';
|
|
34
|
+
for (let i = 0; i < glob.length; i++) {
|
|
35
|
+
const ch = glob[i];
|
|
36
|
+
if (ch === '*') {
|
|
37
|
+
if (glob[i + 1] === '*') {
|
|
38
|
+
const slash = glob[i + 2] === '/';
|
|
39
|
+
re += slash ? '(?:.*/)?' : '.*';
|
|
40
|
+
i += slash ? 2 : 1;
|
|
41
|
+
} else re += '[^/]*';
|
|
42
|
+
} else if (ch === '?') re += '[^/]';
|
|
43
|
+
else re += ch.replace(/[.+^${}()|[\]\\]/g, '\\$&');
|
|
44
|
+
}
|
|
45
|
+
return new RegExp(`^${re}$`);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Pure: split the changed files into ignored / relevant, and map the relevant ones to
|
|
50
|
+
* owning projects, workspace globals or "unowned".
|
|
51
|
+
*/
|
|
52
|
+
export function classifyFiles(changed, { roots, contentOnly = [], adopted = {}, withContent = false }) {
|
|
53
|
+
const contentRes = contentOnly.map(globToRegExp);
|
|
54
|
+
const adoptedRes = Object.entries(adopted).map(([glob, project]) => [globToRegExp(glob), project]);
|
|
55
|
+
const ignore = withContent ? DOCS_ONLY : [...DOCS_ONLY, ...contentRes];
|
|
56
|
+
const ignored = [];
|
|
57
|
+
const files = [];
|
|
58
|
+
for (const f of changed) (ignore.some((re) => re.test(f)) ? ignored : files).push(f);
|
|
59
|
+
const touched = new Set();
|
|
60
|
+
const globals = [];
|
|
61
|
+
const unowned = [];
|
|
62
|
+
const byLength = Object.entries(roots).sort((a, b) => b[1].length - a[1].length);
|
|
63
|
+
for (const file of files) {
|
|
64
|
+
const owner = byLength.find(([, root]) => file === root || file.startsWith(`${root}/`))?.[0] ?? adoptedRes.find(([re]) => re.test(file))?.[1];
|
|
65
|
+
if (owner) touched.add(owner);
|
|
66
|
+
else if (WORKSPACE_GLOBALS.some((re) => re.test(file))) globals.push(file);
|
|
67
|
+
else unowned.push(file);
|
|
68
|
+
}
|
|
69
|
+
return { ignored, files, touched, globals, unowned };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Pure: target → project list, given the Nx answers injected as functions. */
|
|
73
|
+
export function planTargets(targets, { files, touched, globals }, { affectedFor, withTarget }) {
|
|
74
|
+
const plan = new Map();
|
|
75
|
+
for (const target of targets) {
|
|
76
|
+
let projects;
|
|
77
|
+
if (GRAPH_TARGETS.has(target)) projects = affectedFor(files, target);
|
|
78
|
+
else if (globals.length) projects = withTarget(target);
|
|
79
|
+
else projects = withTarget(target).filter((p) => touched.has(p));
|
|
80
|
+
plan.set(target, [...projects].sort());
|
|
81
|
+
}
|
|
82
|
+
return plan;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Pure: one `nx run-many` per distinct project set keeps lint+build of the same projects in one task graph. */
|
|
86
|
+
export function groupPlan(plan) {
|
|
87
|
+
const groups = new Map();
|
|
88
|
+
for (const [target, projects] of plan) {
|
|
89
|
+
if (projects.length === 0) continue;
|
|
90
|
+
const key = projects.join(',');
|
|
91
|
+
groups.set(key, [...(groups.get(key) ?? []), target]);
|
|
92
|
+
}
|
|
93
|
+
return [...groups].map(([projects, targets]) => ({ projects: projects.split(','), targets }));
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// ───────────────────────── git / nx side ─────────────────────────
|
|
97
|
+
|
|
98
|
+
const gitLines = (root, args) => capture('git', args, { cwd: root }).split('\n').filter(Boolean);
|
|
99
|
+
|
|
100
|
+
/** Same semantics as `nx affected`: merge-base(base, head)..head, plus the working tree when no head is given. */
|
|
101
|
+
export function changedFiles(root, { base = 'main', head } = {}) {
|
|
102
|
+
const target = head ?? 'HEAD';
|
|
103
|
+
const mergeBase = capture('git', ['merge-base', base, target], { cwd: root, allowFailure: true }) ?? base;
|
|
104
|
+
const files = new Set(gitLines(root, ['diff', '--name-only', mergeBase, target]));
|
|
105
|
+
if (head === undefined) {
|
|
106
|
+
for (const f of gitLines(root, ['diff', '--name-only', 'HEAD'])) files.add(f);
|
|
107
|
+
for (const f of gitLines(root, ['ls-files', '--others', '--exclude-standard'])) files.add(f);
|
|
108
|
+
}
|
|
109
|
+
return { base: mergeBase.slice(0, 12), head: target.slice(0, 12), files: [...files].sort() };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const nxBin = (root) => join(root, 'node_modules', '.bin', 'nx');
|
|
113
|
+
|
|
114
|
+
export function projectRoots(root) {
|
|
115
|
+
const dir = mkdtempSync(join(tmpdir(), 'devkit-affected-'));
|
|
116
|
+
const file = join(dir, 'graph.json');
|
|
117
|
+
capture(nxBin(root), ['graph', `--file=${file}`], { cwd: root });
|
|
118
|
+
const { graph } = JSON.parse(readFileSync(file, 'utf8'));
|
|
119
|
+
rmSync(dirname(file), { recursive: true, force: true });
|
|
120
|
+
return Object.fromEntries(Object.entries(graph.nodes).map(([name, node]) => [name, node.data.root]));
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export function nxAffected(root, files, target) {
|
|
124
|
+
return JSON.parse(capture(nxBin(root), ['show', 'projects', '--affected', '--stdin', '--with-target', target, '--json'], { cwd: root, input: `${files.join('\n')}\n` }));
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export function nxProjectsWithTarget(root, target) {
|
|
128
|
+
return JSON.parse(capture(nxBin(root), ['show', 'projects', '--with-target', target, '--json'], { cwd: root }));
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** The whole command. Returns the plan; runs nx unless `dryRun`. */
|
|
132
|
+
export async function affected(root, { targets = ['lint', 'build'], base, head, withContent = false, dryRun = false, passthrough = [], config, log = console.log }) {
|
|
133
|
+
const { base: b, head: h, files: changed } = changedFiles(root, { base, head });
|
|
134
|
+
const classified = classifyFiles(changed, { roots: changed.length ? projectRoots(root) : {}, contentOnly: config.contentOnly, adopted: config.adopted, withContent });
|
|
135
|
+
log(`affected: ${b}..${h}`);
|
|
136
|
+
log(` ${changed.length} changed file(s), ${classified.ignored.length} ignored, ${classified.files.length} relevant`);
|
|
137
|
+
if (classified.files.length === 0) {
|
|
138
|
+
log(' nothing to run');
|
|
139
|
+
return new Map();
|
|
140
|
+
}
|
|
141
|
+
log(` touched projects: ${[...classified.touched].sort().join(', ') || '(none)'}`);
|
|
142
|
+
if (classified.globals.length) log(` workspace-level change (${classified.globals.join(', ')}) → own-files targets run for all projects`);
|
|
143
|
+
const plan = planTargets(targets, classified, {
|
|
144
|
+
affectedFor: (files, target) => nxAffected(root, files, target),
|
|
145
|
+
withTarget: (target) => nxProjectsWithTarget(root, target),
|
|
146
|
+
});
|
|
147
|
+
for (const [target, projects] of plan) log(` ${target}: ${projects.join(', ') || '(none)'}`);
|
|
148
|
+
if (dryRun) return plan;
|
|
149
|
+
const groups = groupPlan(plan);
|
|
150
|
+
if (groups.length === 0) log(' nothing to run');
|
|
151
|
+
for (const { projects, targets: groupTargets } of groups) {
|
|
152
|
+
await run(nxBin(root), ['run-many', '-t', ...groupTargets, '-p', projects.join(','), ...passthrough], { cwd: root });
|
|
153
|
+
}
|
|
154
|
+
return plan;
|
|
155
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { capture } from '../exec.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The commit-standards gate: every non-merge commit of a PR must match the derived
|
|
6
|
+
* subject pattern (`hassan-devkit commits:show`) and, when `commits.requireSigned`, be
|
|
7
|
+
* Verified on GitHub. PRs by `commits.exemptAuthors` (renovate) skip the check entirely.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/** Pure: evaluate the commits a PR carries. `commits` = [{ sha, subject, verified, parents }]. */
|
|
11
|
+
export function checkCommits(commits, { pattern, requireSigned }) {
|
|
12
|
+
const re = new RegExp(pattern);
|
|
13
|
+
const results = [];
|
|
14
|
+
for (const c of commits) {
|
|
15
|
+
const short = c.sha.slice(0, 7);
|
|
16
|
+
if (c.parents > 1) {
|
|
17
|
+
results.push({ sha: short, status: 'skip', subject: c.subject, reason: 'merge commit' });
|
|
18
|
+
continue;
|
|
19
|
+
}
|
|
20
|
+
const problems = [];
|
|
21
|
+
if (!re.test(c.subject)) problems.push('message does not match the commit standard');
|
|
22
|
+
if (requireSigned && !c.verified) problems.push('not Verified on GitHub (sign with a key registered on your account)');
|
|
23
|
+
results.push({ sha: short, status: problems.length ? 'fail' : 'ok', subject: c.subject, problems });
|
|
24
|
+
}
|
|
25
|
+
return { results, failed: results.filter((r) => r.status === 'fail') };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Pure: shape `gh api …/pulls/N/commits` JSON into the check's input. */
|
|
29
|
+
export function fromGithubCommits(json) {
|
|
30
|
+
return json.map((c) => ({
|
|
31
|
+
sha: c.sha,
|
|
32
|
+
subject: (c.commit?.message ?? '').split('\n')[0],
|
|
33
|
+
verified: Boolean(c.commit?.verification?.verified),
|
|
34
|
+
parents: (c.parents ?? []).length,
|
|
35
|
+
}));
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** PR coordinates from the Actions environment (or explicit overrides). */
|
|
39
|
+
export function prContext({ env = process.env, repo, pr } = {}) {
|
|
40
|
+
let event = null;
|
|
41
|
+
if (env.GITHUB_EVENT_PATH) {
|
|
42
|
+
try {
|
|
43
|
+
event = JSON.parse(readFileSync(env.GITHUB_EVENT_PATH, 'utf8'));
|
|
44
|
+
} catch {
|
|
45
|
+
event = null;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return {
|
|
49
|
+
repo: repo ?? env.GITHUB_REPOSITORY ?? null,
|
|
50
|
+
pr: pr ?? event?.pull_request?.number ?? (env.PR ? Number(env.PR) : null),
|
|
51
|
+
author: event?.pull_request?.user?.login ?? null,
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function fetchPrCommits(repo, pr, { cwd } = {}) {
|
|
56
|
+
const out = capture('gh', ['api', `repos/${repo}/pulls/${pr}/commits`, '--paginate', '--slurp'], { cwd });
|
|
57
|
+
const pages = JSON.parse(out);
|
|
58
|
+
return fromGithubCommits(Array.isArray(pages[0]) ? pages.flat() : pages);
|
|
59
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { copyFileSync, cpSync, existsSync, mkdirSync, readdirSync, renameSync, rmSync, statSync } from 'node:fs';
|
|
2
|
+
import { createRequire } from 'node:module';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Move Nx's local task cache between the repo and a folder GitHub Actions can cache, so a
|
|
7
|
+
* CI rerun replays every task whose inputs did not change.
|
|
8
|
+
*
|
|
9
|
+
* Nx keeps the cache in two places: the artifacts in `.nx/cache` and a SQLite index in
|
|
10
|
+
* `.nx/workspace-data` named after the machine id (`<machine-id>-v<schema>.db`). Lookups go
|
|
11
|
+
* through the index only — restored artifacts without a matching index are never hit, and
|
|
12
|
+
* every runner has a different machine id, so the index cannot simply be restored in place.
|
|
13
|
+
* `attach` therefore lets Nx's own native binding create this runner's (empty) index, learns
|
|
14
|
+
* its name, and copies the saved index over it. The staging folder lives outside `.nx` so Nx
|
|
15
|
+
* never prunes it; the workflow keys the cache on the lockfile, so an Nx upgrade (new schema)
|
|
16
|
+
* starts fresh.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
export const STAGE_DIR = '.nx-ci-cache';
|
|
20
|
+
const WORKSPACE_DATA = '.nx/workspace-data';
|
|
21
|
+
|
|
22
|
+
function indexFiles(dir) {
|
|
23
|
+
return existsSync(dir) ? readdirSync(dir).filter((f) => f.endsWith('.db')).map((f) => join(dir, f)) : [];
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function entryCount(dir) {
|
|
27
|
+
return existsSync(dir) ? readdirSync(dir, { withFileTypes: true }).filter((e) => e.isDirectory()).length : 0;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Let Nx create this machine's index in `workspaceData` (needs the consumer's `nx`). */
|
|
31
|
+
export function connectNxDb(root, workspaceData) {
|
|
32
|
+
const require = createRequire(join(root, 'package.json'));
|
|
33
|
+
require('nx/src/native').connectToNxDb(workspaceData);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function attach(root, { log = console.log, connect = connectNxDb } = {}) {
|
|
37
|
+
const stage = join(root, STAGE_DIR);
|
|
38
|
+
const workspaceData = join(root, WORKSPACE_DATA);
|
|
39
|
+
if (!existsSync(join(stage, 'index.db')) || !existsSync(join(stage, 'cache'))) {
|
|
40
|
+
log('nx cache: nothing restored, starting cold');
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
mkdirSync(workspaceData, { recursive: true });
|
|
44
|
+
connect(root, workspaceData);
|
|
45
|
+
const indexes = indexFiles(workspaceData);
|
|
46
|
+
if (indexes.length !== 1) {
|
|
47
|
+
log(`nx cache: expected one index in ${WORKSPACE_DATA}, found ${indexes.length} — starting cold`);
|
|
48
|
+
return false;
|
|
49
|
+
}
|
|
50
|
+
rmSync(join(root, '.nx/cache'), { recursive: true, force: true });
|
|
51
|
+
renameSync(join(stage, 'cache'), join(root, '.nx/cache'));
|
|
52
|
+
copyFileSync(join(stage, 'index.db'), indexes[0]);
|
|
53
|
+
log(`nx cache: attached ${entryCount(join(root, '.nx/cache'))} entries as ${indexes[0]}`);
|
|
54
|
+
return true;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function detach(root, { log = console.log } = {}) {
|
|
58
|
+
const stage = join(root, STAGE_DIR);
|
|
59
|
+
const workspaceData = join(root, WORKSPACE_DATA);
|
|
60
|
+
rmSync(stage, { recursive: true, force: true });
|
|
61
|
+
mkdirSync(stage, { recursive: true });
|
|
62
|
+
if (existsSync(join(root, '.nx/cache'))) renameSync(join(root, '.nx/cache'), join(stage, 'cache'));
|
|
63
|
+
// The most recently written index is the one this run's tasks used.
|
|
64
|
+
const index = indexFiles(workspaceData).sort((a, b) => statSync(b).mtimeMs - statSync(a).mtimeMs)[0];
|
|
65
|
+
if (!index) {
|
|
66
|
+
log('nx cache: no index written by this run, nothing to save');
|
|
67
|
+
return false;
|
|
68
|
+
}
|
|
69
|
+
copyFileSync(index, join(stage, 'index.db'));
|
|
70
|
+
log(`nx cache: staged ${entryCount(join(stage, 'cache'))} entries for saving`);
|
|
71
|
+
return true;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export { cpSync };
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The thin CI workflow `init` scaffolds. Every decision lives in the `hassan-devkit ci:*`
|
|
3
|
+
* commands (so a devkit bump updates it); the skeleton below only sequences them, and
|
|
4
|
+
* `ci:doctor` fails when a project's copy drifts from this template.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
export const WORKFLOW_PATH = '.github/workflows/ci.yml';
|
|
8
|
+
|
|
9
|
+
export function renderWorkflow({ nodeVersion, baseBranch = 'main', exemptAuthors = [] }) {
|
|
10
|
+
const skip = exemptAuthors.map((a) => `github.event.pull_request.user.login != '${a}'`).join(' && ');
|
|
11
|
+
return `# Scaffolded by hassan-devkit init — the steps only sequence \`hassan-devkit ci:*\`, whose
|
|
12
|
+
# logic (commit standard, checks, affected targets, Nx cache) ships with the installed devkit
|
|
13
|
+
# version. \`hassan-devkit ci:doctor\` fails when this file drifts from the devkit's template;
|
|
14
|
+
# re-run \`hassan-devkit init --force\` to refresh it.
|
|
15
|
+
name: CI
|
|
16
|
+
|
|
17
|
+
on:
|
|
18
|
+
pull_request:
|
|
19
|
+
branches: [${baseBranch}]
|
|
20
|
+
|
|
21
|
+
# PRs may come from forks: keep the token read-only and use no repo secrets.
|
|
22
|
+
permissions:
|
|
23
|
+
contents: read
|
|
24
|
+
|
|
25
|
+
concurrency:
|
|
26
|
+
group: ci-\${{ github.ref }}
|
|
27
|
+
cancel-in-progress: true
|
|
28
|
+
|
|
29
|
+
jobs:
|
|
30
|
+
commit-standards:
|
|
31
|
+
name: Commit standards
|
|
32
|
+
runs-on: ubuntu-latest${skip ? `\n if: ${skip}` : ''}
|
|
33
|
+
timeout-minutes: 5
|
|
34
|
+
permissions:
|
|
35
|
+
contents: read
|
|
36
|
+
pull-requests: read
|
|
37
|
+
steps:
|
|
38
|
+
- uses: actions/checkout@v5
|
|
39
|
+
- uses: pnpm/action-setup@v4
|
|
40
|
+
- uses: actions/setup-node@v5
|
|
41
|
+
with:
|
|
42
|
+
node-version: ${nodeVersion}
|
|
43
|
+
cache: pnpm
|
|
44
|
+
- run: pnpm install --frozen-lockfile
|
|
45
|
+
- name: Validate PR commits
|
|
46
|
+
env:
|
|
47
|
+
GH_TOKEN: \${{ github.token }}
|
|
48
|
+
run: pnpm exec hassan-devkit ci:commit-standards
|
|
49
|
+
|
|
50
|
+
ci:
|
|
51
|
+
name: Lint & build (affected)
|
|
52
|
+
runs-on: ubuntu-latest
|
|
53
|
+
timeout-minutes: 25
|
|
54
|
+
steps:
|
|
55
|
+
- uses: actions/checkout@v5
|
|
56
|
+
with:
|
|
57
|
+
fetch-depth: 0
|
|
58
|
+
- uses: pnpm/action-setup@v4
|
|
59
|
+
- uses: actions/setup-node@v5
|
|
60
|
+
with:
|
|
61
|
+
node-version: ${nodeVersion}
|
|
62
|
+
cache: pnpm
|
|
63
|
+
- run: pnpm install --frozen-lockfile
|
|
64
|
+
- name: Restore Nx task cache
|
|
65
|
+
uses: actions/cache/restore@v4
|
|
66
|
+
with:
|
|
67
|
+
path: .nx-ci-cache
|
|
68
|
+
key: nx-cache-\${{ hashFiles('pnpm-lock.yaml') }}-\${{ github.run_id }}-\${{ github.run_attempt }}
|
|
69
|
+
restore-keys: nx-cache-\${{ hashFiles('pnpm-lock.yaml') }}-
|
|
70
|
+
- run: pnpm exec hassan-devkit ci:cache attach
|
|
71
|
+
- uses: nrwl/nx-set-shas@v4
|
|
72
|
+
with:
|
|
73
|
+
main-branch-name: ${baseBranch}
|
|
74
|
+
- name: Doctor, formatting and path-triggered checks
|
|
75
|
+
run: pnpm exec hassan-devkit ci:check --base=$NX_BASE --head=$NX_HEAD
|
|
76
|
+
- name: Lint & build affected projects
|
|
77
|
+
run: pnpm exec hassan-devkit ci:affected --base=$NX_BASE --head=$NX_HEAD
|
|
78
|
+
- if: always()
|
|
79
|
+
run: pnpm exec hassan-devkit ci:cache detach
|
|
80
|
+
- name: Save Nx task cache
|
|
81
|
+
if: always() && hashFiles('.nx-ci-cache/index.db') != ''
|
|
82
|
+
uses: actions/cache/save@v4
|
|
83
|
+
with:
|
|
84
|
+
path: .nx-ci-cache
|
|
85
|
+
key: nx-cache-\${{ hashFiles('pnpm-lock.yaml') }}-\${{ github.run_id }}-\${{ github.run_attempt }}
|
|
86
|
+
`;
|
|
87
|
+
}
|