@kainappsinc/factory 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +317 -2
- package/package.json +77 -4
- package/src/cli/args.ts +48 -0
- package/src/cli/baseline.ts +57 -0
- package/src/cli/check.ts +104 -0
- package/src/cli/factory.schema.json +96 -0
- package/src/cli/git.ts +73 -0
- package/src/cli/glob.ts +46 -0
- package/src/cli/index.ts +7 -0
- package/src/cli/io.ts +46 -0
- package/src/cli/main.ts +99 -0
- package/src/cli/manifest.ts +230 -0
- package/src/cli/ratchet.ts +506 -0
- package/src/cli/risk.ts +104 -0
- package/src/depcruise/index.cjs +85 -0
- package/src/depcruise/index.d.cts +7 -0
- package/src/eslint/ast.ts +62 -0
- package/src/eslint/config.ts +86 -0
- package/src/eslint/index.ts +26 -0
- package/src/eslint/messages.ts +43 -0
- package/src/eslint/rules/import-suffix.ts +79 -0
- package/src/eslint/rules/no-json-parse-cast.ts +46 -0
- package/src/eslint/rules/no-raw-request-json.ts +46 -0
- package/src/eslint/rules/no-untracked-todo.ts +37 -0
- package/src/eslint/tester.ts +20 -0
- package/src/packs/ts-bun/classic-typescript.ts +149 -0
- package/src/packs/ts-bun/counter-cli.ts +69 -0
- package/src/packs/ts-bun/depcruise-counts.ts +114 -0
- package/src/packs/ts-bun/eslint-counts.ts +123 -0
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
|
3
|
+
"$id": "factory.schema.json",
|
|
4
|
+
"title": "factory.yaml",
|
|
5
|
+
"description": "Software factory manifest: gates that must pass, counts that may only go down, and paths that need human review. Validated by the factory CLI (manifest.ts); this schema is for editors.",
|
|
6
|
+
"type": "object",
|
|
7
|
+
"additionalProperties": false,
|
|
8
|
+
"required": ["version"],
|
|
9
|
+
"properties": {
|
|
10
|
+
"version": { "const": 1, "description": "Manifest format version." },
|
|
11
|
+
"pack": { "type": "string", "minLength": 1, "description": "Stack pack name (for example ts-bun). Informational for now." },
|
|
12
|
+
"cli": { "type": "string", "minLength": 1, "default": "factory", "description": "How a person runs the CLI in this repository, used in messages (for example \"bun run factory\")." },
|
|
13
|
+
"baselines_dir": { "type": "string", "minLength": 1, "default": "factory/baselines", "description": "Directory of <ratchet-id>.json baseline files, relative to the repository root." },
|
|
14
|
+
"gates": {
|
|
15
|
+
"type": "array",
|
|
16
|
+
"description": "Ordered shell commands that must exit 0.",
|
|
17
|
+
"items": {
|
|
18
|
+
"type": "object",
|
|
19
|
+
"additionalProperties": false,
|
|
20
|
+
"required": ["id", "run", "tier"],
|
|
21
|
+
"properties": {
|
|
22
|
+
"id": { "$ref": "#/$defs/id" },
|
|
23
|
+
"run": { "type": "string", "minLength": 1, "description": "Shell command, run with sh -c at the repository root." },
|
|
24
|
+
"tier": { "enum": ["fast", "full"], "description": "fast gates run in `check --tier fast`; every gate runs in the full tier." }
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
},
|
|
28
|
+
"ratchets": {
|
|
29
|
+
"type": "array",
|
|
30
|
+
"description": "Counts that may only go down. Exactly one of pattern, max_lines or run.",
|
|
31
|
+
"items": {
|
|
32
|
+
"type": "object",
|
|
33
|
+
"additionalProperties": false,
|
|
34
|
+
"required": ["id", "why"],
|
|
35
|
+
"properties": {
|
|
36
|
+
"id": { "$ref": "#/$defs/id" },
|
|
37
|
+
"why": { "type": "string", "minLength": 1, "description": "One line: why this is counted and what to do instead. Printed on every failure." },
|
|
38
|
+
"pattern": { "type": "string", "minLength": 1, "description": "JavaScript regular expression; the count is the number of matching lines in the selected files (key: total)." },
|
|
39
|
+
"max_lines": { "type": "integer", "minimum": 1, "description": "The count is the number of selected files with more lines than this (key: total)." },
|
|
40
|
+
"run": { "type": "string", "minLength": 1, "description": "Shell command printing one JSON object {\"key\": count} on stdout." },
|
|
41
|
+
"show": { "type": "string", "minLength": 1, "description": "Run ratchets only: a command printed on failure that lists the occurrences (file:line); {keys} becomes the comma-separated keys that rose." },
|
|
42
|
+
"include": { "$ref": "#/$defs/globs" },
|
|
43
|
+
"exclude": { "type": "array", "items": { "type": "string", "minLength": 1 }, "description": "Globs removed from include." }
|
|
44
|
+
},
|
|
45
|
+
"oneOf": [
|
|
46
|
+
{ "required": ["pattern", "include"], "not": { "anyOf": [{ "required": ["max_lines"] }, { "required": ["run"] }, { "required": ["show"] }] } },
|
|
47
|
+
{ "required": ["max_lines", "include"], "not": { "anyOf": [{ "required": ["pattern"] }, { "required": ["run"] }, { "required": ["show"] }] } },
|
|
48
|
+
{ "required": ["run"], "not": { "anyOf": [{ "required": ["pattern"] }, { "required": ["max_lines"] }, { "required": ["include"] }, { "required": ["exclude"] }] } }
|
|
49
|
+
]
|
|
50
|
+
}
|
|
51
|
+
},
|
|
52
|
+
"retired": {
|
|
53
|
+
"type": "array",
|
|
54
|
+
"description": "Ratchets removed on purpose. `ratchet --against` fails when a ratchet at the target is missing here, unless its id is listed. An id may not also be in ratchets.",
|
|
55
|
+
"items": {
|
|
56
|
+
"type": "object",
|
|
57
|
+
"additionalProperties": false,
|
|
58
|
+
"required": ["id", "why"],
|
|
59
|
+
"properties": {
|
|
60
|
+
"id": { "$ref": "#/$defs/id" },
|
|
61
|
+
"why": { "type": "string", "minLength": 1, "description": "Why the ratchet was retired (printed by ratchet --against)." }
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
},
|
|
65
|
+
"allowances": {
|
|
66
|
+
"type": "array",
|
|
67
|
+
"description": "Reviewed room to raise one ratchet key's baseline. Add one in its own merge request (a person reviews it); it has no effect there. A later change may then raise that key's baseline by up to `by` and must delete the allowance in the same change. `ratchet --against` reads allowances from the target branch only.",
|
|
68
|
+
"items": {
|
|
69
|
+
"type": "object",
|
|
70
|
+
"additionalProperties": false,
|
|
71
|
+
"required": ["ratchet", "by", "why"],
|
|
72
|
+
"properties": {
|
|
73
|
+
"ratchet": { "$ref": "#/$defs/id", "description": "Id of a ratchet in ratchets." },
|
|
74
|
+
"key": { "type": "string", "minLength": 1, "default": "total", "description": "The count's key. Pattern and max_lines ratchets have the single key total; a run ratchet's keys are what its command prints (for example (suppressed))." },
|
|
75
|
+
"by": { "type": "integer", "minimum": 1, "description": "How much the baseline for this key may rise." },
|
|
76
|
+
"why": { "type": "string", "minLength": 1, "description": "Why the new occurrences are justified (printed when the allowance is used)." }
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
},
|
|
80
|
+
"risk_zones": {
|
|
81
|
+
"type": "object",
|
|
82
|
+
"description": "Zone name -> globs. A change touching a zone needs human review. Read from the base ref, never the working copy.",
|
|
83
|
+
"propertyNames": { "$ref": "#/$defs/id" },
|
|
84
|
+
"additionalProperties": { "$ref": "#/$defs/globs" }
|
|
85
|
+
}
|
|
86
|
+
},
|
|
87
|
+
"$defs": {
|
|
88
|
+
"id": { "type": "string", "pattern": "^[a-z0-9][a-z0-9_-]*$" },
|
|
89
|
+
"globs": {
|
|
90
|
+
"type": "array",
|
|
91
|
+
"minItems": 1,
|
|
92
|
+
"description": "Globs against repository-relative paths: * within a segment, ** any segments, ?, [abc], {a,b}. No leading !, ./ or /.",
|
|
93
|
+
"items": { "type": "string", "minLength": 1 }
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
package/src/cli/git.ts
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { FactoryError } from './io.js';
|
|
2
|
+
|
|
3
|
+
export interface GitResult { code: number; stdout: string; stderr: string }
|
|
4
|
+
|
|
5
|
+
export function git(root: string, args: readonly string[]): GitResult {
|
|
6
|
+
const proc = Bun.spawnSync(['git', ...args], { cwd: root, stdout: 'pipe', stderr: 'pipe' });
|
|
7
|
+
return { code: proc.exitCode ?? 1, stdout: proc.stdout.toString(), stderr: proc.stderr.toString() };
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/** Splits `-z` output into paths. */
|
|
11
|
+
function splitNul(s: string): string[] {
|
|
12
|
+
return s.split('\0').filter(Boolean);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function gitOrThrow(root: string, args: readonly string[], what: string): string {
|
|
16
|
+
const r = git(root, args);
|
|
17
|
+
if (r.code !== 0) throw new FactoryError(`${what} failed: git ${args.join(' ')}: ${r.stderr.trim() || `exit ${r.code}`}`);
|
|
18
|
+
return r.stdout;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** The repository root containing `cwd`. */
|
|
22
|
+
export function repoRoot(cwd: string): string {
|
|
23
|
+
const r = git(cwd, ['rev-parse', '--show-toplevel']);
|
|
24
|
+
if (r.code !== 0) throw new FactoryError(`factory must run inside a git repository (${cwd} is not in one)`);
|
|
25
|
+
return r.stdout.trim();
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Files the repository knows about: tracked plus untracked-but-not-ignored, minus
|
|
30
|
+
* tracked files deleted in the working tree. Honours .gitignore and never walks
|
|
31
|
+
* node_modules, because git does the listing.
|
|
32
|
+
*/
|
|
33
|
+
export function listFiles(root: string): string[] {
|
|
34
|
+
const all = splitNul(gitOrThrow(root, ['ls-files', '-z', '--cached', '--others', '--exclude-standard'], 'listing files'));
|
|
35
|
+
const deleted = new Set(splitNul(gitOrThrow(root, ['ls-files', '-z', '--deleted'], 'listing deleted files')));
|
|
36
|
+
return [...new Set(all)].filter((f) => !deleted.has(f)).sort();
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Resolves a ref to a commit sha, or throws a readable error naming the ref. */
|
|
40
|
+
export function resolveCommit(root: string, ref: string): string {
|
|
41
|
+
const r = git(root, ['rev-parse', '--verify', '--quiet', `${ref}^{commit}`]);
|
|
42
|
+
if (r.code !== 0) {
|
|
43
|
+
throw new FactoryError(`git ref "${ref}" does not resolve to a commit here (in CI, fetch it first: git fetch origin <branch>)`);
|
|
44
|
+
}
|
|
45
|
+
return r.stdout.trim();
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** HEAD's sha, or null in a repository with no commits. */
|
|
49
|
+
export function headSha(root: string): string | null {
|
|
50
|
+
const r = git(root, ['rev-parse', '--verify', '--quiet', 'HEAD']);
|
|
51
|
+
return r.code === 0 ? r.stdout.trim() : null;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** A file's content at a commit, or null when the file does not exist there. */
|
|
55
|
+
export function showFile(root: string, commit: string, path: string): string | null {
|
|
56
|
+
const r = git(root, ['show', `${commit}:${path}`]);
|
|
57
|
+
return r.code === 0 ? r.stdout : null;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function mergeBase(root: string, a: string, b: string): string {
|
|
61
|
+
return gitOrThrow(root, ['merge-base', a, b], `finding the merge base of ${a} and ${b}`).trim();
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Paths changed since `from`: to the commit `to`, or to the working tree (tracked
|
|
66
|
+
* changes plus untracked files) when `to` is undefined. Renames count as a delete
|
|
67
|
+
* plus an add, so moving a file out of a zone still lists the old path.
|
|
68
|
+
*/
|
|
69
|
+
export function changedFiles(root: string, from: string, to?: string): string[] {
|
|
70
|
+
const diff = splitNul(gitOrThrow(root, ['diff', '-z', '--name-only', '--no-renames', from, ...(to ? [to] : [])], 'listing changed files'));
|
|
71
|
+
const untracked = to ? [] : splitNul(gitOrThrow(root, ['ls-files', '-z', '--others', '--exclude-standard'], 'listing untracked files'));
|
|
72
|
+
return [...new Set([...diff, ...untracked])].sort();
|
|
73
|
+
}
|
package/src/cli/glob.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Glob semantics (one set, used by ratchet include/exclude and risk zones).
|
|
3
|
+
*
|
|
4
|
+
* A pattern is matched against a repository-relative path with forward slashes,
|
|
5
|
+
* as `git ls-files` prints it (no leading `./`, no trailing `/`).
|
|
6
|
+
* * any run of characters inside one path segment (never crosses `/`)
|
|
7
|
+
* ** any number of whole segments, including none: `a/**\/b` matches `a/b`
|
|
8
|
+
* ? one character inside a segment
|
|
9
|
+
* [abc] one character from the set
|
|
10
|
+
* {a,b} either alternative: `**\/*.{ts,tsx}`
|
|
11
|
+
* Dotfiles are not special: `*.yml` matches `.gitlab-ci.yml`.
|
|
12
|
+
* A path is selected when it matches at least one `include` pattern and no
|
|
13
|
+
* `exclude` pattern. There is no `!` negation inside a list: use `exclude`.
|
|
14
|
+
* Matching is done by Bun.Glob; this module only fixes the rules above.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
export interface FileFilter {
|
|
18
|
+
include: readonly string[];
|
|
19
|
+
exclude?: readonly string[];
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Why a pattern is not allowed, or null when it is. */
|
|
23
|
+
export function globProblem(pattern: string): string | null {
|
|
24
|
+
if (pattern === '') return 'is empty';
|
|
25
|
+
if (pattern.startsWith('!')) return 'starts with "!": negation is not supported, list the pattern under exclude';
|
|
26
|
+
if (pattern.startsWith('/')) return 'is absolute: patterns are relative to the repository root';
|
|
27
|
+
if (pattern.startsWith('./')) return 'starts with "./": write the path without it';
|
|
28
|
+
if (pattern.endsWith('/')) return 'ends with "/": to match a directory\'s contents write dir/**';
|
|
29
|
+
if (pattern.includes('\\')) return 'contains a backslash: use forward slashes';
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function compileGlobs(patterns: readonly string[]): (path: string) => boolean {
|
|
34
|
+
const globs = patterns.map((p) => new Bun.Glob(p));
|
|
35
|
+
return (path) => globs.some((g) => g.match(path));
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function compileFilter(filter: FileFilter): (path: string) => boolean {
|
|
39
|
+
const inc = compileGlobs(filter.include);
|
|
40
|
+
const exc = compileGlobs(filter.exclude ?? []);
|
|
41
|
+
return (path) => inc(path) && !exc(path);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function selectFiles(files: readonly string[], filter: FileFilter): string[] {
|
|
45
|
+
return files.filter(compileFilter(filter));
|
|
46
|
+
}
|
package/src/cli/index.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
// The factory CLI (`factory <check|ratchet|risk|validate> ...`, the package bin).
|
|
3
|
+
// Generic: everything project-specific lives in the repository's factory.yaml.
|
|
4
|
+
import { processIo } from './io.js';
|
|
5
|
+
import { main } from './main.js';
|
|
6
|
+
|
|
7
|
+
process.exitCode = await main(process.argv.slice(2), process.cwd(), processIo);
|
package/src/cli/io.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/** Where a command writes. The real CLI writes to the process; tests capture. */
|
|
2
|
+
export interface Io {
|
|
3
|
+
out(text: string): void;
|
|
4
|
+
err(text: string): void;
|
|
5
|
+
/** True when child processes may inherit the terminal directly (keeps colours and TTY detection). */
|
|
6
|
+
inherit?: boolean;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export const processIo: Io = {
|
|
10
|
+
out: (text) => { process.stdout.write(text); },
|
|
11
|
+
err: (text) => { process.stderr.write(text); },
|
|
12
|
+
inherit: true,
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
/** An Io that records everything, for tests. */
|
|
16
|
+
export function memoryIo(): Io & { stdout: () => string; stderr: () => string } {
|
|
17
|
+
let out = '';
|
|
18
|
+
let err = '';
|
|
19
|
+
return {
|
|
20
|
+
out: (t) => { out += t; },
|
|
21
|
+
err: (t) => { err += t; },
|
|
22
|
+
stdout: () => out,
|
|
23
|
+
stderr: () => err,
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Left-aligned text table; the last column is not padded. */
|
|
28
|
+
export function table(rows: readonly (readonly string[])[]): string {
|
|
29
|
+
const widths: number[] = [];
|
|
30
|
+
for (const row of rows) row.forEach((cell, i) => { widths[i] = Math.max(widths[i] ?? 0, cell.length); });
|
|
31
|
+
return rows
|
|
32
|
+
.map((row) => row.map((cell, i) => (i === row.length - 1 ? cell : cell.padEnd(widths[i] ?? 0))).join(' '))
|
|
33
|
+
.join('\n') + '\n';
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export const EXIT_OK = 0;
|
|
37
|
+
export const EXIT_FAIL = 1;
|
|
38
|
+
export const EXIT_USAGE = 2;
|
|
39
|
+
export const EXIT_RISK = 3;
|
|
40
|
+
|
|
41
|
+
/** A user-facing error: printed as-is, no stack, exits with `code`. */
|
|
42
|
+
export class FactoryError extends Error {
|
|
43
|
+
constructor(message: string, readonly code: number = EXIT_USAGE) {
|
|
44
|
+
super(message);
|
|
45
|
+
}
|
|
46
|
+
}
|
package/src/cli/main.ts
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { listFlag, parseFlags, stringFlag } from './args.js';
|
|
2
|
+
import { runCheck } from './check.js';
|
|
3
|
+
import { listFiles, repoRoot } from './git.js';
|
|
4
|
+
import { compileGlobs } from './glob.js';
|
|
5
|
+
import { EXIT_OK, EXIT_USAGE, FactoryError, type Io } from './io.js';
|
|
6
|
+
import { loadManifest, type Manifest, TIERS, type Tier } from './manifest.js';
|
|
7
|
+
import { runRatchet } from './ratchet.js';
|
|
8
|
+
import { runRisk } from './risk.js';
|
|
9
|
+
|
|
10
|
+
export const USAGE = `factory: mechanical gates for a repository, driven by factory.yaml at its root.
|
|
11
|
+
|
|
12
|
+
Commands:
|
|
13
|
+
check [--tier fast|full] [--only <id>,...] [--json <path>]
|
|
14
|
+
Run the gates in order (default tier full: all of them). Keeps going after
|
|
15
|
+
a failure; exits 1 if any failed. --json writes an evidence file.
|
|
16
|
+
ratchet [--update [--allow-increase]] [--against <git-ref>] [--only <id>]
|
|
17
|
+
Counts that may only go down. Fails when a count is above its baseline
|
|
18
|
+
(new debt) or below it (stale baseline). --update lowers baselines;
|
|
19
|
+
raising or creating one needs --allow-increase. --against fails when a
|
|
20
|
+
baseline here is higher than at the ref (an MR cannot raise its own).
|
|
21
|
+
risk --base <git-ref> [--head <ref>] [--json] [--fail-on-risk]
|
|
22
|
+
Files changed since merge-base(base, head), grouped by the risk zones in
|
|
23
|
+
factory.yaml AT THE BASE. Without --head: the working tree. Exit 0, or 3
|
|
24
|
+
with --fail-on-risk when a zone is touched.
|
|
25
|
+
validate
|
|
26
|
+
Check factory.yaml, print what it declares and any glob matching no file.
|
|
27
|
+
|
|
28
|
+
Exit codes: 0 ok, 1 a gate or ratchet failed, 2 usage or manifest error, 3 risk (--fail-on-risk).
|
|
29
|
+
`;
|
|
30
|
+
|
|
31
|
+
/** Include and risk-zone globs that match no file today: usually a typo or a moved file. */
|
|
32
|
+
export function deadGlobs(m: Manifest, files: readonly string[]): string[] {
|
|
33
|
+
const dead: string[] = [];
|
|
34
|
+
const check = (path: string, globs: readonly string[]) => globs.forEach((g, i) => {
|
|
35
|
+
if (!files.some(compileGlobs([g]))) dead.push(`${path}[${i}]: "${g}" matches no file`);
|
|
36
|
+
});
|
|
37
|
+
for (const r of m.ratchets) if (r.kind !== 'run') check(`ratchets.${r.id}.include`, r.include);
|
|
38
|
+
for (const [name, globs] of Object.entries(m.risk_zones)) check(`risk_zones.${name}`, globs);
|
|
39
|
+
return dead;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export async function main(argv: readonly string[], cwd: string, io: Io): Promise<number> {
|
|
43
|
+
const [command, ...rest] = argv;
|
|
44
|
+
try {
|
|
45
|
+
if (command === undefined || command === 'help' || command === '--help' || command === '-h') {
|
|
46
|
+
io.out(USAGE);
|
|
47
|
+
return command === undefined ? EXIT_USAGE : EXIT_OK;
|
|
48
|
+
}
|
|
49
|
+
const root = repoRoot(cwd);
|
|
50
|
+
switch (command) {
|
|
51
|
+
case 'check': {
|
|
52
|
+
const flags = parseFlags(command, rest, { tier: 'string', only: 'string', json: 'string' });
|
|
53
|
+
const tier = stringFlag(flags, 'tier');
|
|
54
|
+
if (tier !== undefined && !TIERS.includes(tier as Tier)) throw new FactoryError(`factory check: --tier must be ${TIERS.join(' or ')}, got "${tier}"`);
|
|
55
|
+
const only = listFlag(flags, 'only');
|
|
56
|
+
const json = stringFlag(flags, 'json');
|
|
57
|
+
return await runCheck(root, loadManifest(root), {
|
|
58
|
+
...(tier !== undefined && { tier: tier as Tier }), ...(only && { only }), ...(json && { json }), cwd,
|
|
59
|
+
}, io);
|
|
60
|
+
}
|
|
61
|
+
case 'ratchet': {
|
|
62
|
+
const flags = parseFlags(command, rest, { update: 'boolean', 'allow-increase': 'boolean', against: 'string', only: 'string' });
|
|
63
|
+
const against = stringFlag(flags, 'against');
|
|
64
|
+
const only = stringFlag(flags, 'only');
|
|
65
|
+
return runRatchet(root, loadManifest(root), {
|
|
66
|
+
update: flags.update === true,
|
|
67
|
+
allowIncrease: flags['allow-increase'] === true,
|
|
68
|
+
...(against !== undefined && { against }),
|
|
69
|
+
...(only !== undefined && { only }),
|
|
70
|
+
}, io);
|
|
71
|
+
}
|
|
72
|
+
case 'risk': {
|
|
73
|
+
const flags = parseFlags(command, rest, { base: 'string', head: 'string', json: 'boolean', 'fail-on-risk': 'boolean' });
|
|
74
|
+
const base = stringFlag(flags, 'base');
|
|
75
|
+
if (!base) throw new FactoryError('factory risk: --base <git-ref> is required (the branch the change merges into)');
|
|
76
|
+
const head = stringFlag(flags, 'head');
|
|
77
|
+
return runRisk(root, {
|
|
78
|
+
base, ...(head !== undefined && { head }), json: flags.json === true, failOnRisk: flags['fail-on-risk'] === true,
|
|
79
|
+
}, io);
|
|
80
|
+
}
|
|
81
|
+
case 'validate': {
|
|
82
|
+
parseFlags(command, rest, {});
|
|
83
|
+
const m = loadManifest(root);
|
|
84
|
+
io.out(`factory.yaml is valid: version ${m.version}${m.pack ? `, pack ${m.pack}` : ''}; `
|
|
85
|
+
+ `${m.gates.length} gates, ${m.ratchets.length} ratchets, ${Object.keys(m.risk_zones).length} risk zones.\n`);
|
|
86
|
+
for (const d of deadGlobs(m, listFiles(root))) io.out(`NOTE ${d}\n`);
|
|
87
|
+
return EXIT_OK;
|
|
88
|
+
}
|
|
89
|
+
default:
|
|
90
|
+
throw new FactoryError(`unknown command "${command}"\n\n${USAGE}`);
|
|
91
|
+
}
|
|
92
|
+
} catch (e) {
|
|
93
|
+
if (e instanceof FactoryError) {
|
|
94
|
+
io.err(`factory: ${e.message}\n`);
|
|
95
|
+
return e.code;
|
|
96
|
+
}
|
|
97
|
+
throw e;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { globProblem } from './glob.js';
|
|
4
|
+
import { FactoryError } from './io.js';
|
|
5
|
+
|
|
6
|
+
export const MANIFEST_FILE = 'factory.yaml';
|
|
7
|
+
export const DEFAULT_BASELINES_DIR = 'factory/baselines';
|
|
8
|
+
export const DEFAULT_CLI = 'factory';
|
|
9
|
+
|
|
10
|
+
export type Tier = 'fast' | 'full';
|
|
11
|
+
export const TIERS: readonly Tier[] = ['fast', 'full'];
|
|
12
|
+
|
|
13
|
+
export interface Gate { id: string; run: string; tier: Tier }
|
|
14
|
+
|
|
15
|
+
interface RatchetBase { id: string; why: string; include: string[]; exclude: string[] }
|
|
16
|
+
/** Counts lines matching `pattern` in the selected files; one key, `total`. */
|
|
17
|
+
export interface PatternRatchet extends RatchetBase { kind: 'pattern'; pattern: string }
|
|
18
|
+
/** Counts selected files longer than `max_lines` lines; one key, `total`. */
|
|
19
|
+
export interface MaxLinesRatchet extends RatchetBase { kind: 'max_lines'; max_lines: number }
|
|
20
|
+
/**
|
|
21
|
+
* Runs `run`; its stdout is a JSON object of non-negative integer counts. `show`, when set, is a
|
|
22
|
+
* command printed on failure that lists the occurrences; `{keys}` in it becomes the keys that rose.
|
|
23
|
+
*/
|
|
24
|
+
export interface RunRatchet { kind: 'run'; id: string; why: string; run: string; show?: string }
|
|
25
|
+
export type Ratchet = PatternRatchet | MaxLinesRatchet | RunRatchet;
|
|
26
|
+
|
|
27
|
+
export interface Manifest {
|
|
28
|
+
version: 1;
|
|
29
|
+
pack?: string;
|
|
30
|
+
/** How a person invokes this CLI here, used in messages ("bun run factory"). */
|
|
31
|
+
cli: string;
|
|
32
|
+
baselines_dir: string;
|
|
33
|
+
gates: Gate[];
|
|
34
|
+
ratchets: Ratchet[];
|
|
35
|
+
risk_zones: Record<string, string[]>;
|
|
36
|
+
/** Ratchets removed on purpose; `ratchet --against` accepts their absence. */
|
|
37
|
+
retired: RetiredRatchet[];
|
|
38
|
+
/** Reviewed room to raise a baseline; `ratchet --against` reads them from the target's manifest. */
|
|
39
|
+
allowances: Allowance[];
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface RetiredRatchet { id: string; why: string }
|
|
43
|
+
/** Lets a later change raise one key of a ratchet's baseline by `by`; that change deletes it. */
|
|
44
|
+
export interface Allowance { ratchet: string; key: string; by: number; why: string }
|
|
45
|
+
/** The key a pattern or max_lines ratchet counts under, and an allowance's default. */
|
|
46
|
+
export const TOTAL_KEY = 'total';
|
|
47
|
+
|
|
48
|
+
/** Key sets, exported so a test can compare them with factory.schema.json. */
|
|
49
|
+
export const MANIFEST_KEYS = ['version', 'pack', 'cli', 'baselines_dir', 'gates', 'ratchets', 'retired', 'allowances', 'risk_zones'] as const;
|
|
50
|
+
export const RETIRED_KEYS = ['id', 'why'] as const;
|
|
51
|
+
export const ALLOWANCE_KEYS = ['ratchet', 'key', 'by', 'why'] as const;
|
|
52
|
+
export const GATE_KEYS = ['id', 'run', 'tier'] as const;
|
|
53
|
+
export const RATCHET_KEYS = ['id', 'why', 'pattern', 'max_lines', 'run', 'show', 'include', 'exclude'] as const;
|
|
54
|
+
|
|
55
|
+
const ID_RE = /^[a-z0-9][a-z0-9_-]*$/;
|
|
56
|
+
|
|
57
|
+
type Obj = Record<string, unknown>;
|
|
58
|
+
const isObj = (v: unknown): v is Obj => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
59
|
+
const show = (v: unknown) => (v === null ? 'null' : Array.isArray(v) ? 'a list' : typeof v === 'object' ? 'a mapping' : JSON.stringify(v));
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Validates a parsed manifest. Returns every problem found, each as
|
|
63
|
+
* "<path>: <what was expected>", so one run lists everything to fix.
|
|
64
|
+
*/
|
|
65
|
+
export function validateManifest(raw: unknown): { manifest?: Manifest; errors: string[] } {
|
|
66
|
+
const errors: string[] = [];
|
|
67
|
+
const err = (path: string, msg: string) => { errors.push(`${path}: ${msg}`); };
|
|
68
|
+
if (!isObj(raw)) return { errors: [`(top level): expected a mapping with at least "version: 1", got ${show(raw)}`] };
|
|
69
|
+
|
|
70
|
+
const unknownKeys = (obj: Obj, keys: readonly string[], path: string) => {
|
|
71
|
+
for (const k of Object.keys(obj)) {
|
|
72
|
+
if (!keys.includes(k)) err(path ? `${path}.${k}` : k, `unknown key (allowed: ${keys.join(', ')})`);
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
const str = (obj: Obj, key: string, path: string, required: boolean): string | undefined => {
|
|
76
|
+
const v = obj[key];
|
|
77
|
+
if (v === undefined) { if (required) err(`${path}.${key}`, 'required, expected a non-empty string'); return undefined; }
|
|
78
|
+
if (typeof v !== 'string' || v.trim() === '') { err(`${path}.${key}`, `expected a non-empty string, got ${show(v)}`); return undefined; }
|
|
79
|
+
return v;
|
|
80
|
+
};
|
|
81
|
+
const globs = (obj: Obj, key: string, path: string, required: boolean): string[] => {
|
|
82
|
+
const v = obj[key];
|
|
83
|
+
if (v === undefined) { if (required) err(`${path}.${key}`, 'required, expected a list of glob patterns'); return []; }
|
|
84
|
+
if (!Array.isArray(v) || (required && v.length === 0)) { err(`${path}.${key}`, `expected a non-empty list of glob patterns, got ${show(v)}`); return []; }
|
|
85
|
+
const out: string[] = [];
|
|
86
|
+
v.forEach((g, i) => {
|
|
87
|
+
if (typeof g !== 'string') { err(`${path}.${key}[${i}]`, `expected a glob string, got ${show(g)}`); return; }
|
|
88
|
+
const problem = globProblem(g);
|
|
89
|
+
if (problem) err(`${path}.${key}[${i}]`, `glob "${g}" ${problem}`);
|
|
90
|
+
else out.push(g);
|
|
91
|
+
});
|
|
92
|
+
return out;
|
|
93
|
+
};
|
|
94
|
+
const ids = new Set<string>();
|
|
95
|
+
const id = (obj: Obj, path: string, what: string): string | undefined => {
|
|
96
|
+
const v = str(obj, 'id', path, true);
|
|
97
|
+
if (v === undefined) return undefined;
|
|
98
|
+
if (!ID_RE.test(v)) { err(`${path}.id`, `"${v}" is not a valid id (lowercase letters, digits, "-" and "_", starting with a letter or digit)`); return undefined; }
|
|
99
|
+
if (ids.has(`${what}:${v}`)) err(`${path}.id`, `duplicate ${what} id "${v}"`);
|
|
100
|
+
ids.add(`${what}:${v}`);
|
|
101
|
+
return v;
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
unknownKeys(raw, MANIFEST_KEYS, '');
|
|
105
|
+
if (raw.version !== 1) err('version', `expected 1, got ${show(raw.version)}`);
|
|
106
|
+
const pack = str(raw, 'pack', '(top level)', false);
|
|
107
|
+
const cli = str(raw, 'cli', '(top level)', false) ?? DEFAULT_CLI;
|
|
108
|
+
const baselinesDir = str(raw, 'baselines_dir', '(top level)', false) ?? DEFAULT_BASELINES_DIR;
|
|
109
|
+
if (globProblem(baselinesDir) || /[*?[{]/.test(baselinesDir)) err('baselines_dir', `expected a plain relative directory path, got ${JSON.stringify(baselinesDir)}`);
|
|
110
|
+
|
|
111
|
+
const gates: Gate[] = [];
|
|
112
|
+
if (raw.gates !== undefined && !Array.isArray(raw.gates)) err('gates', `expected a list of gates, got ${show(raw.gates)}`);
|
|
113
|
+
(Array.isArray(raw.gates) ? raw.gates : []).forEach((g, i) => {
|
|
114
|
+
const path = `gates[${i}]`;
|
|
115
|
+
if (!isObj(g)) { err(path, `expected a mapping with id, run and tier, got ${show(g)}`); return; }
|
|
116
|
+
unknownKeys(g, GATE_KEYS, path);
|
|
117
|
+
const gid = id(g, path, 'gate');
|
|
118
|
+
const run = str(g, 'run', path, true);
|
|
119
|
+
const tier = g.tier;
|
|
120
|
+
if (tier === undefined) err(`${path}.tier`, `required, expected one of ${TIERS.join(' | ')}`);
|
|
121
|
+
else if (!TIERS.includes(tier as Tier)) err(`${path}.tier`, `expected one of ${TIERS.join(' | ')}, got ${show(tier)}`);
|
|
122
|
+
if (gid && run && TIERS.includes(tier as Tier)) gates.push({ id: gid, run, tier: tier as Tier });
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
const ratchets: Ratchet[] = [];
|
|
126
|
+
if (raw.ratchets !== undefined && !Array.isArray(raw.ratchets)) err('ratchets', `expected a list of ratchets, got ${show(raw.ratchets)}`);
|
|
127
|
+
(Array.isArray(raw.ratchets) ? raw.ratchets : []).forEach((r, i) => {
|
|
128
|
+
const path = `ratchets[${i}]`;
|
|
129
|
+
if (!isObj(r)) { err(path, `expected a mapping, got ${show(r)}`); return; }
|
|
130
|
+
unknownKeys(r, RATCHET_KEYS, path);
|
|
131
|
+
const rid = id(r, path, 'ratchet');
|
|
132
|
+
const why = str(r, 'why', path, true);
|
|
133
|
+
const kinds = (['pattern', 'max_lines', 'run'] as const).filter((k) => r[k] !== undefined);
|
|
134
|
+
const kind = kinds[0];
|
|
135
|
+
if (kinds.length !== 1 || kind === undefined) {
|
|
136
|
+
err(path, `expected exactly one counter: pattern (regex), max_lines (number) or run (command); got ${kinds.length ? kinds.join(' and ') : 'none'}`);
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
if (kind === 'run') {
|
|
140
|
+
const run = str(r, 'run', path, true);
|
|
141
|
+
const showCmd = str(r, 'show', path, false);
|
|
142
|
+
for (const k of ['include', 'exclude']) if (r[k] !== undefined) err(`${path}.${k}`, 'not used by a run ratchet: the command chooses its own files');
|
|
143
|
+
if (rid && why && run) ratchets.push({ kind, id: rid, why, run, ...(showCmd !== undefined && { show: showCmd }) });
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
if (r.show !== undefined) err(`${path}.show`, `only a run ratchet takes show; a ${kind} ratchet lists its occurrences itself`);
|
|
147
|
+
const include = globs(r, 'include', path, true);
|
|
148
|
+
const exclude = globs(r, 'exclude', path, false);
|
|
149
|
+
if (kind === 'pattern') {
|
|
150
|
+
const pattern = str(r, 'pattern', path, true);
|
|
151
|
+
if (pattern !== undefined) {
|
|
152
|
+
try { new RegExp(pattern); } catch (e) { err(`${path}.pattern`, `not a valid regular expression: ${(e as Error).message}`); return; }
|
|
153
|
+
}
|
|
154
|
+
if (rid && why && pattern !== undefined && include.length) ratchets.push({ kind, id: rid, why, pattern, include, exclude });
|
|
155
|
+
} else {
|
|
156
|
+
const max = r.max_lines;
|
|
157
|
+
if (typeof max !== 'number' || !Number.isInteger(max) || max < 1) { err(`${path}.max_lines`, `expected a positive integer, got ${show(max)}`); return; }
|
|
158
|
+
if (rid && why && include.length) ratchets.push({ kind, id: rid, why, max_lines: max, include, exclude });
|
|
159
|
+
}
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
const retired: RetiredRatchet[] = [];
|
|
163
|
+
if (raw.retired !== undefined && !Array.isArray(raw.retired)) err('retired', `expected a list of {id, why}, got ${show(raw.retired)}`);
|
|
164
|
+
(Array.isArray(raw.retired) ? raw.retired : []).forEach((r, i) => {
|
|
165
|
+
const path = `retired[${i}]`;
|
|
166
|
+
if (!isObj(r)) { err(path, `expected a mapping with id and why, got ${show(r)}`); return; }
|
|
167
|
+
unknownKeys(r, RETIRED_KEYS, path);
|
|
168
|
+
const rid = id(r, path, 'retired ratchet');
|
|
169
|
+
const why = str(r, 'why', path, true);
|
|
170
|
+
if (rid && ratchets.some((x) => x.id === rid)) err(`${path}.id`, `"${rid}" is both a ratchet and retired; remove it from one of the two lists`);
|
|
171
|
+
if (rid && why) retired.push({ id: rid, why });
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
const allowances: Allowance[] = [];
|
|
175
|
+
if (raw.allowances !== undefined && !Array.isArray(raw.allowances)) err('allowances', `expected a list of {ratchet, key, by, why}, got ${show(raw.allowances)}`);
|
|
176
|
+
(Array.isArray(raw.allowances) ? raw.allowances : []).forEach((a, i) => {
|
|
177
|
+
const path = `allowances[${i}]`;
|
|
178
|
+
if (!isObj(a)) { err(path, `expected a mapping with ratchet, by and why, got ${show(a)}`); return; }
|
|
179
|
+
unknownKeys(a, ALLOWANCE_KEYS, path);
|
|
180
|
+
const ratchet = str(a, 'ratchet', path, true);
|
|
181
|
+
const known = ratchet !== undefined && ids.has(`ratchet:${ratchet}`);
|
|
182
|
+
if (ratchet !== undefined && !known) err(`${path}.ratchet`, `"${ratchet}" is not a ratchet in ratchets`);
|
|
183
|
+
const key = str(a, 'key', path, false) ?? TOTAL_KEY;
|
|
184
|
+
const kind = ratchets.find((x) => x.id === ratchet)?.kind;
|
|
185
|
+
if (kind !== undefined && kind !== 'run' && key !== TOTAL_KEY) err(`${path}.key`, `a ${kind} ratchet has the single key "${TOTAL_KEY}", got ${JSON.stringify(key)}`);
|
|
186
|
+
const by = a.by;
|
|
187
|
+
const byOk = typeof by === 'number' && Number.isInteger(by) && by >= 1;
|
|
188
|
+
if (by === undefined) err(`${path}.by`, 'required, expected a positive integer');
|
|
189
|
+
else if (!byOk) err(`${path}.by`, `expected a positive integer, got ${show(by)}`);
|
|
190
|
+
const why = str(a, 'why', path, true);
|
|
191
|
+
if (known && byOk && why) allowances.push({ ratchet, key, by, why });
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
const zones: Record<string, string[]> = {};
|
|
195
|
+
if (raw.risk_zones !== undefined && !isObj(raw.risk_zones)) err('risk_zones', `expected a mapping of zone name to glob list, got ${show(raw.risk_zones)}`);
|
|
196
|
+
if (isObj(raw.risk_zones)) {
|
|
197
|
+
for (const name of Object.keys(raw.risk_zones)) {
|
|
198
|
+
if (!ID_RE.test(name)) err(`risk_zones.${name}`, 'is not a valid zone name (lowercase letters, digits, "-" and "_")');
|
|
199
|
+
zones[name] = globs(raw.risk_zones, name, 'risk_zones', true);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
if (errors.length) return { errors };
|
|
204
|
+
return {
|
|
205
|
+
errors,
|
|
206
|
+
manifest: { version: 1, ...(pack !== undefined && { pack }), cli, baselines_dir: baselinesDir, gates, ratchets, risk_zones: zones, retired, allowances },
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
export function parseYaml(text: string, source: string): unknown {
|
|
211
|
+
try {
|
|
212
|
+
return Bun.YAML.parse(text);
|
|
213
|
+
} catch (e) {
|
|
214
|
+
throw new FactoryError(`${source} is not valid YAML: ${(e as Error).message}`);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
export function parseManifest(text: string, source: string): Manifest {
|
|
219
|
+
const { manifest, errors } = validateManifest(parseYaml(text, source));
|
|
220
|
+
if (!manifest) {
|
|
221
|
+
throw new FactoryError(`${source} is not a valid factory manifest:\n${errors.map((e) => ` - ${e}`).join('\n')}\n(the format is factory.schema.json, next to the factory CLI)`);
|
|
222
|
+
}
|
|
223
|
+
return manifest;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
export function loadManifest(root: string): Manifest {
|
|
227
|
+
const path = join(root, MANIFEST_FILE);
|
|
228
|
+
if (!existsSync(path)) throw new FactoryError(`no ${MANIFEST_FILE} at the repository root (${root})`);
|
|
229
|
+
return parseManifest(readFileSync(path, 'utf8'), MANIFEST_FILE);
|
|
230
|
+
}
|