@bbcsoftwarefactory/cli 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/package.json +33 -6
- package/src/bbc.ts +39 -0
- package/src/bigo/complexity.ts +138 -0
- package/src/bigo/functions.ts +183 -0
- package/src/bigo/keywords.ts +41 -0
- package/src/bigo/lexical.ts +68 -0
- package/src/bigo/source-files.ts +80 -0
- package/src/change-lane/classification.ts +128 -0
- package/src/change-lane/git.ts +110 -0
- package/src/classify-change-lane.ts +140 -0
- package/src/diff-scope/git-diff.ts +161 -0
- package/src/extract-diff-scope.ts +130 -0
- package/src/measure-bigo.ts +86 -0
- package/src/render-workflow.ts +144 -0
- package/src/workflow/render.ts +40 -0
- package/src/workflow/schema.ts +141 -0
- package/README.md +0 -3
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* LAYER: Domain
|
|
3
|
+
* Contains: Change-lane policies and report construction.
|
|
4
|
+
* Rules: Risk takes precedence over file extensions; thresholds are strict.
|
|
5
|
+
* BigO: O(n) score:3
|
|
6
|
+
* keywords: [ChangeLanePolicy, LaneReport]
|
|
7
|
+
* GOAL: Classify paths and line totals without reading Git or the worktree.
|
|
8
|
+
*/
|
|
9
|
+
import { win32 } from 'node:path';
|
|
10
|
+
|
|
11
|
+
const largeLines = 300;
|
|
12
|
+
const largeFiles = 10;
|
|
13
|
+
const trivialExtensions = new Set(['.md', '.mdx', '.txt', '.svg', '.excalidraw', '.png', '.jpg', '.jpeg', '.webp', '.gif']);
|
|
14
|
+
const trivialNames = new Set([
|
|
15
|
+
'CHANGELOG.md', 'README.md', 'AGENTS.md', 'INSTALLATION.md', 'CONTRIBUTING.md',
|
|
16
|
+
'SUPPORT.md', 'SECURITY.md', 'LICENSE', 'NOTICE',
|
|
17
|
+
]);
|
|
18
|
+
|
|
19
|
+
const riskPatterns = [
|
|
20
|
+
/(^|\/)skills\/watcher-observability\//i,
|
|
21
|
+
/(^|\/)skills\/tool-depot\//i,
|
|
22
|
+
/(^|\/)skills\/workflow-auditor\/scripts\/audit-ledger\.py$/i,
|
|
23
|
+
/(^|\/)skills\/question-gate\/scripts\/triage-question\.py$/i,
|
|
24
|
+
/(^|\/)skills\/delivery-coordinator\/scripts\/check-worktree-guard\.py$/i,
|
|
25
|
+
/(^|\/)tools\/export-public\.py$/i,
|
|
26
|
+
/(^|\/)\.github\/workflows\//i,
|
|
27
|
+
/(^|\/)(?:auth|oauth|jwt|session|token|crypto|secret|permission|rbac|security|migration|migrations|prisma|schema|deploy|infra)(?:\/|[._-]|$)/i,
|
|
28
|
+
/\.sql$/i,
|
|
29
|
+
];
|
|
30
|
+
|
|
31
|
+
const plans = {
|
|
32
|
+
trivial: {
|
|
33
|
+
test_mode: 'proportional',
|
|
34
|
+
required_stages: ['specify', 'implement', 'quality', 'docs', 'commit_pr', 'review'],
|
|
35
|
+
skipped_stages: ['requirements-spec-full-prd', 'risk-scout', 'reproduce-runtime-red', 'verify-runtime-green'],
|
|
36
|
+
extra_checks: ['documentation-steward', 'validate-skills.py'],
|
|
37
|
+
},
|
|
38
|
+
standard: {
|
|
39
|
+
test_mode: 'tdd',
|
|
40
|
+
required_stages: ['specify', 'reproduce', 'implement', 'verify', 'quality', 'commit_pr', 'review'],
|
|
41
|
+
skipped_stages: ['risk-scout'],
|
|
42
|
+
extra_checks: ['code-quality-gate'],
|
|
43
|
+
},
|
|
44
|
+
'high-risk': {
|
|
45
|
+
test_mode: 'tdd',
|
|
46
|
+
required_stages: [
|
|
47
|
+
'specify', 'risk-scout', 'reproduce', 'implement', 'verify', 'quality', 'commit_pr', 'review', 'residual_risk',
|
|
48
|
+
],
|
|
49
|
+
skipped_stages: [],
|
|
50
|
+
extra_checks: ['risk-scout', 'code-quality-gate', 'human-security-review'],
|
|
51
|
+
},
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
type Lane = keyof typeof plans;
|
|
55
|
+
|
|
56
|
+
export interface ChangeSet {
|
|
57
|
+
files: readonly string[];
|
|
58
|
+
added: number;
|
|
59
|
+
removed: number;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export interface LaneReport {
|
|
63
|
+
lane: Lane;
|
|
64
|
+
reasons: readonly string[];
|
|
65
|
+
files_changed: number;
|
|
66
|
+
lines_added: number;
|
|
67
|
+
lines_removed: number;
|
|
68
|
+
lines_changed: number;
|
|
69
|
+
files: readonly string[];
|
|
70
|
+
test_mode: string;
|
|
71
|
+
required_stages: readonly string[];
|
|
72
|
+
skipped_stages: readonly string[];
|
|
73
|
+
extra_checks: readonly string[];
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function normalize(path: string): string {
|
|
77
|
+
return path.replaceAll('\\', '/');
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function isHighRisk(path: string): boolean {
|
|
81
|
+
// Python re.I adds these four case equivalents for ASCII letters in the patterns.
|
|
82
|
+
const norm = normalize(path)
|
|
83
|
+
.replace(/[İı]/g, 'i').replace(/ſ/g, 's').replace(/K/g, 'k');
|
|
84
|
+
// Python's $ also accepts the position just before a final newline.
|
|
85
|
+
const subject = norm.endsWith('\n') ? norm.slice(0, -1) : norm;
|
|
86
|
+
return riskPatterns.some((pattern) => pattern.test(subject));
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function isTrivial(path: string, windows: boolean): boolean {
|
|
90
|
+
const norm = normalize(path);
|
|
91
|
+
const local = windows ? norm.slice(win32.parse(norm).root.length) : norm;
|
|
92
|
+
// pathlib ignores trailing slash and "." components, but does not collapse "..".
|
|
93
|
+
const parts = local.split('/');
|
|
94
|
+
const name = parts.filter((part) => part !== '' && part !== '.').at(-1) ?? '';
|
|
95
|
+
const dot = name.lastIndexOf('.');
|
|
96
|
+
return trivialNames.has(name) || (dot > 0 && trivialExtensions.has(name.slice(dot).toLowerCase()));
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function decide({ files, added, removed }: ChangeSet, windows: boolean): [Lane, string[]] {
|
|
100
|
+
if (files.length === 0) return ['trivial', ['No changed files detected.']];
|
|
101
|
+
|
|
102
|
+
const hits = files.filter(isHighRisk);
|
|
103
|
+
const lines = added + removed;
|
|
104
|
+
const reasons: string[] = [];
|
|
105
|
+
if (hits.length > 0) reasons.push(`Touched high-risk path(s): ${hits.slice(0, 5).join(', ')}`);
|
|
106
|
+
if (lines > largeLines) reasons.push(`Large diff (${lines} lines > ${largeLines}).`);
|
|
107
|
+
if (files.length > largeFiles) reasons.push(`Broad change (${files.length} files > ${largeFiles}).`);
|
|
108
|
+
if (reasons.length > 0) return ['high-risk', reasons];
|
|
109
|
+
if (files.every((path) => isTrivial(path, windows))) {
|
|
110
|
+
return ['trivial', ['Only documentation, markdown, or visual assets changed.']];
|
|
111
|
+
}
|
|
112
|
+
return ['standard', ['Scoped code or skill change without high-risk paths or oversized diff.']];
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export function classify(change: ChangeSet, windows: boolean): LaneReport {
|
|
116
|
+
const { files, added, removed } = change;
|
|
117
|
+
const [lane, reasons] = decide(change, windows);
|
|
118
|
+
return {
|
|
119
|
+
lane,
|
|
120
|
+
reasons,
|
|
121
|
+
files_changed: files.length,
|
|
122
|
+
lines_added: added,
|
|
123
|
+
lines_removed: removed,
|
|
124
|
+
lines_changed: added + removed,
|
|
125
|
+
files,
|
|
126
|
+
...plans[lane],
|
|
127
|
+
};
|
|
128
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* LAYER: Infrastructure
|
|
3
|
+
* Contains: Git diff and working-tree statistics adapter.
|
|
4
|
+
* Rules: Read only; use Git's NUL-delimited paths and ignore untracked non-files.
|
|
5
|
+
* BigO: O(n log n) score:2
|
|
6
|
+
* keywords: [GitDiff, ChangeStatistics]
|
|
7
|
+
* GOAL: Collect the paths and line counts consumed by the classifier.
|
|
8
|
+
*/
|
|
9
|
+
import { spawnSync } from 'node:child_process';
|
|
10
|
+
import { readFileSync, statSync } from 'node:fs';
|
|
11
|
+
import type { ChangeSet } from './classification.ts';
|
|
12
|
+
|
|
13
|
+
export type GitSelection =
|
|
14
|
+
| { mode: 'working' | 'staged' }
|
|
15
|
+
| { mode: 'range' | 'head'; value: string };
|
|
16
|
+
|
|
17
|
+
const decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
|
|
18
|
+
const diff = ['-c', 'core.quotePath=false', 'diff', '--no-ext-diff', '--no-textconv'];
|
|
19
|
+
|
|
20
|
+
function git(args: readonly string[]): Buffer | undefined {
|
|
21
|
+
const result = spawnSync('git', args, {
|
|
22
|
+
env: { ...process.env, GIT_OPTIONAL_LOCKS: '0', GIT_NO_LAZY_FETCH: '1' },
|
|
23
|
+
timeout: 10_000,
|
|
24
|
+
maxBuffer: Number.MAX_SAFE_INTEGER,
|
|
25
|
+
});
|
|
26
|
+
return result.status === 0 && !result.error ? result.stdout : undefined;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function diffArguments(selection: GitSelection): string[] {
|
|
30
|
+
switch (selection.mode) {
|
|
31
|
+
case 'working':
|
|
32
|
+
return git(['rev-parse', '--verify', 'HEAD']) === undefined ? ['--staged'] : ['HEAD'];
|
|
33
|
+
case 'staged':
|
|
34
|
+
return ['--staged'];
|
|
35
|
+
case 'range':
|
|
36
|
+
return [selection.value];
|
|
37
|
+
case 'head':
|
|
38
|
+
return [`HEAD~${selection.value}..HEAD`];
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function paths(raw: Buffer): string[] | undefined {
|
|
43
|
+
try {
|
|
44
|
+
return decoder.decode(raw).split('\0').filter(Boolean);
|
|
45
|
+
} catch {
|
|
46
|
+
return undefined;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function isRegularFile(path: string): boolean {
|
|
51
|
+
try {
|
|
52
|
+
return statSync(path).isFile();
|
|
53
|
+
} catch {
|
|
54
|
+
return false;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function untrackedPaths(): string[] | undefined {
|
|
59
|
+
const raw = git(['-c', 'core.quotePath=false', 'ls-files', '--others', '--exclude-standard', '-z']);
|
|
60
|
+
if (raw === undefined) return [];
|
|
61
|
+
return paths(raw)?.filter(isRegularFile);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function trackedCounts(args: string[], files: string[]): [number, number] {
|
|
65
|
+
if (files.length === 0) return [0, 0];
|
|
66
|
+
const raw = git([...diff, ...args, '--numstat', '--', ...files]);
|
|
67
|
+
if (raw === undefined) return [0, 0];
|
|
68
|
+
let added = 0;
|
|
69
|
+
let removed = 0;
|
|
70
|
+
for (const row of raw.toString('utf8').split('\n')) {
|
|
71
|
+
const [plus = '', minus = ''] = row.split('\t', 2);
|
|
72
|
+
if (/^[0-9]+$/.test(plus)) added += Number(plus);
|
|
73
|
+
if (/^[0-9]+$/.test(minus)) removed += Number(minus);
|
|
74
|
+
}
|
|
75
|
+
return [added, removed];
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function countNewlines(path: string): number {
|
|
79
|
+
let data: Buffer;
|
|
80
|
+
try {
|
|
81
|
+
data = readFileSync(path);
|
|
82
|
+
} catch {
|
|
83
|
+
return 0;
|
|
84
|
+
}
|
|
85
|
+
let lines = 0;
|
|
86
|
+
for (const byte of data) {
|
|
87
|
+
if (byte === 0x0a) lines++;
|
|
88
|
+
}
|
|
89
|
+
return lines;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function sortedFiles(tracked: string[], untracked: string[]): string[] {
|
|
93
|
+
// UTF-8 byte sorting preserves Python's code-point order for valid UTF-8 names.
|
|
94
|
+
return Array.from(new Set([...tracked, ...untracked]), (file) => ({ file, bytes: Buffer.from(file) }))
|
|
95
|
+
.sort((a, b) => Buffer.compare(a.bytes, b.bytes))
|
|
96
|
+
.map(({ file }) => file);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function readGitChanges(selection: GitSelection): ChangeSet | undefined {
|
|
100
|
+
const args = diffArguments(selection);
|
|
101
|
+
const names = git([...diff, ...args, '--name-only', '-z']);
|
|
102
|
+
if (names === undefined) return undefined;
|
|
103
|
+
const tracked = paths(names);
|
|
104
|
+
const untracked = selection.mode === 'working' ? untrackedPaths() : [];
|
|
105
|
+
if (tracked === undefined || untracked === undefined) return undefined;
|
|
106
|
+
|
|
107
|
+
const [added, removed] = trackedCounts(args, tracked);
|
|
108
|
+
const untrackedLines = untracked.reduce((sum, path) => sum + countNewlines(path), 0);
|
|
109
|
+
return { files: sortedFiles(tracked, untracked), added: added + untrackedLines, removed };
|
|
110
|
+
}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* LAYER: Interface
|
|
3
|
+
* Contains: Change-lane command parsing and output formatting.
|
|
4
|
+
* Rules: Emit the legacy report format, with native CLI help and read-only Git arguments.
|
|
5
|
+
* BigO: O(n) score:3
|
|
6
|
+
* keywords: [ClassifyChangeLane, LaneArguments]
|
|
7
|
+
* GOAL: Translate a local change selection into a lane report and process status.
|
|
8
|
+
*/
|
|
9
|
+
import { EOL } from 'node:os';
|
|
10
|
+
import { classify, type LaneReport } from './change-lane/classification.ts';
|
|
11
|
+
import { readGitChanges, type GitSelection } from './change-lane/git.ts';
|
|
12
|
+
|
|
13
|
+
export const classifyChangeLaneUsage =
|
|
14
|
+
'bbc classify-change-lane [--working|--staged|--range A..B|--head N|--files <p1>...] [--format json|hud]';
|
|
15
|
+
|
|
16
|
+
type Selection = GitSelection | { mode: 'files'; files: string[] };
|
|
17
|
+
type Format = 'json' | 'hud';
|
|
18
|
+
type Parsed =
|
|
19
|
+
| { kind: 'help' }
|
|
20
|
+
| { kind: 'error'; message: string }
|
|
21
|
+
| { kind: 'run'; selection: Selection; format: Format };
|
|
22
|
+
|
|
23
|
+
function error(message: string): Parsed {
|
|
24
|
+
return { kind: 'error', message };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function explicitPaths(args: readonly string[], from: number): { files: string[]; next: number } {
|
|
28
|
+
const files: string[] = [];
|
|
29
|
+
let next = from;
|
|
30
|
+
while (next < args.length) {
|
|
31
|
+
const path = args[next];
|
|
32
|
+
if (path === undefined || path.startsWith('--')) break;
|
|
33
|
+
files.push(path);
|
|
34
|
+
next++;
|
|
35
|
+
}
|
|
36
|
+
return { files, next };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const selectionFlags = new Set(['--working', '--staged', '--range', '--head', '--files']);
|
|
40
|
+
|
|
41
|
+
function selectionError(selection: Selection): string | undefined {
|
|
42
|
+
if (selection.mode === 'head' && !/^[1-9][0-9]*$/.test(selection.value)) {
|
|
43
|
+
return `--head requires a positive integer: ${selection.value}`;
|
|
44
|
+
}
|
|
45
|
+
if (selection.mode === 'range' && selection.value.startsWith('-')) {
|
|
46
|
+
return '--range must not start with -';
|
|
47
|
+
}
|
|
48
|
+
if (selection.mode === 'files' && selection.files.length === 0) {
|
|
49
|
+
return '--files requires at least one path';
|
|
50
|
+
}
|
|
51
|
+
return undefined;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function replacementError(selection: Selection | undefined, flag: string | undefined): string | undefined {
|
|
55
|
+
if (!selection || !flag || !selectionFlags.has(flag)) return undefined;
|
|
56
|
+
if (flag !== `--${selection.mode}`) return `cannot combine --${selection.mode} with ${flag}`;
|
|
57
|
+
// Keep the existing conflict diagnostic, but never let a same-mode flag hide an invalid value.
|
|
58
|
+
return selectionError(selection);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function parse(args: readonly string[]): Parsed {
|
|
62
|
+
let selection: Selection | undefined;
|
|
63
|
+
let format: Format | undefined;
|
|
64
|
+
for (let i = 0; i < args.length; i++) {
|
|
65
|
+
const arg = args[i];
|
|
66
|
+
const value = args[i + 1];
|
|
67
|
+
const invalidReplacement = replacementError(selection, arg);
|
|
68
|
+
if (invalidReplacement !== undefined) return error(invalidReplacement);
|
|
69
|
+
switch (arg) {
|
|
70
|
+
case '-h':
|
|
71
|
+
case '--help':
|
|
72
|
+
return { kind: 'help' };
|
|
73
|
+
case '--working':
|
|
74
|
+
case '--staged':
|
|
75
|
+
selection = { mode: arg === '--working' ? 'working' : 'staged' };
|
|
76
|
+
break;
|
|
77
|
+
case '--range':
|
|
78
|
+
case '--head':
|
|
79
|
+
if (!value) return error(`${arg} requires an argument`);
|
|
80
|
+
selection = { mode: arg === '--range' ? 'range' : 'head', value };
|
|
81
|
+
i++;
|
|
82
|
+
break;
|
|
83
|
+
case '--files': {
|
|
84
|
+
const { files, next } = explicitPaths(args, i + 1);
|
|
85
|
+
selection = { mode: 'files', files };
|
|
86
|
+
i = next - 1;
|
|
87
|
+
break;
|
|
88
|
+
}
|
|
89
|
+
case '--format':
|
|
90
|
+
if (format !== undefined) return error('--format may only be specified once');
|
|
91
|
+
if (value !== 'json' && value !== 'hud') return error('--format must be json or hud');
|
|
92
|
+
format = value;
|
|
93
|
+
i++;
|
|
94
|
+
break;
|
|
95
|
+
default:
|
|
96
|
+
return error(`unknown option: ${arg}`);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
selection ??= { mode: 'working' };
|
|
101
|
+
const invalidSelection = selectionError(selection);
|
|
102
|
+
if (invalidSelection !== undefined) return error(invalidSelection);
|
|
103
|
+
return { kind: 'run', selection, format: format ?? 'json' };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const badges = { trivial: '🟢', standard: '🟡', 'high-risk': '🔴' };
|
|
107
|
+
|
|
108
|
+
function formatReport(report: LaneReport, format: Format): string {
|
|
109
|
+
if (format === 'hud') {
|
|
110
|
+
const { lane, files_changed: files, lines_changed: lines, reasons } = report;
|
|
111
|
+
return `🛣️ Lane: ${badges[lane]} ${lane} (${files} files, ${lines} lines) — ${reasons[0] ?? ''}`;
|
|
112
|
+
}
|
|
113
|
+
// Python json.dumps defaults to ASCII and escapes even DEL.
|
|
114
|
+
return JSON.stringify(report, null, 2).replace(/[\u007f-\uffff]/g, (char) =>
|
|
115
|
+
`\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function fail(message: string, status: number): number {
|
|
119
|
+
process.stderr.write(`error: ${message}\n`.replaceAll('\n', EOL));
|
|
120
|
+
return status;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export function classifyChangeLane(args: readonly string[]): number {
|
|
124
|
+
const parsed = parse(args);
|
|
125
|
+
if (parsed.kind === 'help') {
|
|
126
|
+
process.stdout.write(`Usage: ${classifyChangeLaneUsage}\nClassifies a change into trivial, standard, or high-risk.\n`
|
|
127
|
+
+ 'Do not combine different selection modes or repeat --format.\n');
|
|
128
|
+
return 0;
|
|
129
|
+
}
|
|
130
|
+
if (parsed.kind === 'error') return fail(parsed.message, 1);
|
|
131
|
+
|
|
132
|
+
const { selection, format } = parsed;
|
|
133
|
+
const change = selection.mode === 'files'
|
|
134
|
+
? { files: selection.files, added: 0, removed: 0 }
|
|
135
|
+
: readGitChanges(selection);
|
|
136
|
+
if (change === undefined) return fail('failed to inspect git diff', 2);
|
|
137
|
+
const report = classify(change, process.platform === 'win32');
|
|
138
|
+
process.stdout.write(`${formatReport(report, format)}\n`);
|
|
139
|
+
return 0;
|
|
140
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* LAYER: Infrastructure
|
|
3
|
+
* Contains: Git diff scope collection.
|
|
4
|
+
* Rules: Keep bytes intact with a latin1 round-trip and never rewrite git output.
|
|
5
|
+
* BigO: O(n) score:3
|
|
6
|
+
* keywords: [DiffScope, HunkParsing]
|
|
7
|
+
* GOAL: Turn a local Git diff into the sections the quality gate consumes.
|
|
8
|
+
*/
|
|
9
|
+
import { spawnSync } from 'node:child_process';
|
|
10
|
+
import { statSync } from 'node:fs';
|
|
11
|
+
import { readFileSync } from 'node:fs';
|
|
12
|
+
|
|
13
|
+
const codePattern = /\.(ts|tsx|mts|cts|js|jsx|mjs|cjs)$/;
|
|
14
|
+
const excludedPattern = /(^|\/)(dist|node_modules|graphify-out|\.next|\.vite|build|\.vercel|coverage)\/|^prisma\/generated\/|^server\/dist\//;
|
|
15
|
+
|
|
16
|
+
export const gates: readonly (readonly [string, RegExp | null])[] = [
|
|
17
|
+
['records', null],
|
|
18
|
+
['typesafe_candidates', /(:\s*any([^A-Za-z0-9_]|$)|\sas\s+any([^A-Za-z0-9_]|$)|\sas\s+[A-Za-z_]|!\.|!\[|@ts-ignore|@ts-expect-error|@ts-nocheck|<any>)/],
|
|
19
|
+
['earlyreturn_candidates', /(}\s*else(\s|$)|else\s+if\s*\(|^\s{12,}(if|for|while)\s*\(|\.then\s*\(|^\s*[?:]\s*(await\s+)?[A-Za-z0-9_$.]+\()/],
|
|
20
|
+
['bigo_candidates', /(\.(forEach|map|filter|find|some|includes|indexOf|reduce)\s*\(|for\s*\(|while\s*\(|\.\.\.acc)/],
|
|
21
|
+
];
|
|
22
|
+
|
|
23
|
+
export type Mode = 'working' | 'staged' | 'range' | 'head';
|
|
24
|
+
|
|
25
|
+
export interface ScopeRequest {
|
|
26
|
+
mode: Mode;
|
|
27
|
+
value: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface Record {
|
|
31
|
+
path: string;
|
|
32
|
+
line: number;
|
|
33
|
+
content: string;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const decode = (buffer: Buffer): string => buffer.toString('latin1');
|
|
37
|
+
|
|
38
|
+
function git(args: readonly string[], quiet: boolean): { stdout: Buffer; status: number } {
|
|
39
|
+
const result = spawnSync('git', [...args], {
|
|
40
|
+
stdio: ['ignore', 'pipe', quiet ? 'ignore' : 'inherit'],
|
|
41
|
+
});
|
|
42
|
+
if (result.error !== undefined || result.stdout === null) return { stdout: Buffer.alloc(0), status: 1 };
|
|
43
|
+
return { stdout: result.stdout, status: result.status ?? 1 };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function isTarget(path: string): boolean {
|
|
47
|
+
return codePattern.test(path) && !excludedPattern.test(path);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function yamlEscape(value: string): string {
|
|
51
|
+
const parts = value.split('\n');
|
|
52
|
+
if (parts.length > 1 && parts.at(-1) === '') parts.pop();
|
|
53
|
+
return parts.map((part) => part.replaceAll('\\', '\\\\').replaceAll('"', '\\"')).join('\\n');
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function awkQuote(value: string): string {
|
|
57
|
+
return value.replaceAll('\\', '\\\\').replaceAll('"', '\\"');
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function recordsOf(lines: readonly string[]): readonly string[] {
|
|
61
|
+
return lines.length > 0 && lines.at(-1) === '' ? lines.slice(0, -1) : lines;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function diffArgs(request: ScopeRequest, hasHead: boolean): string[] {
|
|
65
|
+
if (request.mode === 'staged') return ['--staged'];
|
|
66
|
+
if (request.mode === 'range') return [request.value];
|
|
67
|
+
if (request.mode === 'head') return [`HEAD~${request.value}..HEAD`];
|
|
68
|
+
return hasHead ? ['HEAD'] : ['--staged'];
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function hasHeadCommit(): boolean {
|
|
72
|
+
return git(['rev-parse', '--verify', 'HEAD'], true).status === 0;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function changedFiles(args: readonly string[]): string[] {
|
|
76
|
+
const names = git(['-c', 'core.quotePath=false', 'diff', ...args, '--name-only', '-z'], true);
|
|
77
|
+
return decode(names.stdout).split('\0').filter((path) => path !== '' && isTarget(path));
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function untrackedFiles(): string[] {
|
|
81
|
+
const others = git(['-c', 'core.quotePath=false', 'ls-files', '--others', '--exclude-standard', '-z'], true);
|
|
82
|
+
return decode(others.stdout)
|
|
83
|
+
.split('\0')
|
|
84
|
+
.filter((path) => path !== '' && isTarget(path))
|
|
85
|
+
.filter((path) => {
|
|
86
|
+
try {
|
|
87
|
+
return statSync(path, { throwIfNoEntry: false })?.isFile() === true;
|
|
88
|
+
} catch {
|
|
89
|
+
return false;
|
|
90
|
+
}
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function hunkStart(row: string): number {
|
|
95
|
+
const fields = row.split(/\s+/);
|
|
96
|
+
let start = fields[2] ?? '';
|
|
97
|
+
if (start.startsWith('+')) start = start.slice(1);
|
|
98
|
+
const digits = /^[0-9]*/.exec(start.split(',')[0] ?? '')?.[0] ?? '';
|
|
99
|
+
return digits === '' ? 0 : Number(digits);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function trackedRecords(args: readonly string[], files: readonly string[]): Record[] {
|
|
103
|
+
const diff = git(
|
|
104
|
+
['-c', 'core.quotePath=false', '-c', 'diff.noprefix=false', 'diff', ...args, '-U0', '--no-color', '--', ...files],
|
|
105
|
+
false,
|
|
106
|
+
);
|
|
107
|
+
const out: Record[] = [];
|
|
108
|
+
let current = '';
|
|
109
|
+
let line = 0;
|
|
110
|
+
for (const row of recordsOf(decode(diff.stdout).split('\n'))) {
|
|
111
|
+
if (row.startsWith('+++ b/')) {
|
|
112
|
+
current = row.slice(6);
|
|
113
|
+
line = 0;
|
|
114
|
+
} else if (row.startsWith('+++ /dev/null')) {
|
|
115
|
+
current = '';
|
|
116
|
+
line = 0;
|
|
117
|
+
} else if (row.startsWith('@@ ')) {
|
|
118
|
+
line = hunkStart(row);
|
|
119
|
+
} else if (row.startsWith('+') && !row.startsWith('+++')) {
|
|
120
|
+
if (current !== '' && line > 0) out.push({ path: current, line, content: row.slice(1) });
|
|
121
|
+
line += 1;
|
|
122
|
+
} else if (line > 0 && row.startsWith(' ')) {
|
|
123
|
+
line += 1;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return out;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export function untrackedRecords(path: string): Record[] {
|
|
130
|
+
let data: Buffer;
|
|
131
|
+
try {
|
|
132
|
+
data = readFileSync(path);
|
|
133
|
+
} catch {
|
|
134
|
+
return [];
|
|
135
|
+
}
|
|
136
|
+
return recordsOf(decode(data).split('\n')).map((content, index) => ({ path, line: index + 1, content }));
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export function countLines(args: readonly string[], files: readonly string[]): { added: number; removed: number } {
|
|
140
|
+
const stat = git(['-c', 'core.quotePath=false', 'diff', ...args, '--numstat', '--', ...files], false);
|
|
141
|
+
let added = 0;
|
|
142
|
+
let removed = 0;
|
|
143
|
+
for (const row of decode(stat.stdout).split('\n')) {
|
|
144
|
+
const columns = row.split('\t');
|
|
145
|
+
const first = columns[0] ?? '';
|
|
146
|
+
if (/^[0-9]+$/.test(first)) added += Number(first);
|
|
147
|
+
const second = columns[1] ?? '';
|
|
148
|
+
if (/^[0-9]+$/.test(second)) removed += Number(second);
|
|
149
|
+
}
|
|
150
|
+
return { added, removed };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export function untrackedLineCount(path: string): number {
|
|
154
|
+
try {
|
|
155
|
+
let total = 0;
|
|
156
|
+
for (const byte of readFileSync(path)) if (byte === 0x0a) total += 1;
|
|
157
|
+
return total;
|
|
158
|
+
} catch {
|
|
159
|
+
return 0;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* LAYER: Interface
|
|
3
|
+
* Contains: extract-diff-scope command.
|
|
4
|
+
* Rules: Emit the legacy YAML sections and exit statuses byte for byte.
|
|
5
|
+
* BigO: O(n^2) score:1
|
|
6
|
+
* keywords: [DiffScopeCommand, GateSections]
|
|
7
|
+
* GOAL: List the changed code lines the quality gates must inspect.
|
|
8
|
+
*/
|
|
9
|
+
import {
|
|
10
|
+
awkQuote,
|
|
11
|
+
changedFiles,
|
|
12
|
+
countLines,
|
|
13
|
+
diffArgs,
|
|
14
|
+
gates,
|
|
15
|
+
hasHeadCommit,
|
|
16
|
+
trackedRecords,
|
|
17
|
+
untrackedFiles,
|
|
18
|
+
untrackedLineCount,
|
|
19
|
+
untrackedRecords,
|
|
20
|
+
yamlEscape,
|
|
21
|
+
type Mode,
|
|
22
|
+
type Record,
|
|
23
|
+
type ScopeRequest,
|
|
24
|
+
} from './diff-scope/git-diff.ts';
|
|
25
|
+
import { EOL } from 'node:os';
|
|
26
|
+
|
|
27
|
+
export const extractDiffScopeUsage = 'bbc extract-diff-scope [--working|--staged|--range A..B|--head N]';
|
|
28
|
+
|
|
29
|
+
const usageText = `extract-diff-scope.py: extract added/modified TypeScript/JavaScript lines as
|
|
30
|
+
structured YAML for code-quality-gate (TypeSafe, EarlyReturn, BigO).
|
|
31
|
+
|
|
32
|
+
Usage:
|
|
33
|
+
python3 -I -B scripts/extract-diff-scope.py # working tree vs HEAD + untracked (default)
|
|
34
|
+
python3 -I -B scripts/extract-diff-scope.py --working # working tree vs HEAD + untracked
|
|
35
|
+
python3 -I -B scripts/extract-diff-scope.py --staged # staged diff only
|
|
36
|
+
python3 -I -B scripts/extract-diff-scope.py --range A..B # commit range
|
|
37
|
+
python3 -I -B scripts/extract-diff-scope.py --head N # last N commits (HEAD~N..HEAD)
|
|
38
|
+
python3 -I -B scripts/extract-diff-scope.py --help
|
|
39
|
+
`;
|
|
40
|
+
|
|
41
|
+
const native = (text: string): Buffer => Buffer.from(text.replaceAll('\n', EOL), 'latin1');
|
|
42
|
+
|
|
43
|
+
function parseArgs(args: readonly string[]): ScopeRequest | 'help' | undefined {
|
|
44
|
+
let mode: Mode = 'working';
|
|
45
|
+
let value = '';
|
|
46
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
47
|
+
const argument = args[index];
|
|
48
|
+
if (argument === '--working' || argument === '--staged') {
|
|
49
|
+
mode = argument.slice(2) as Mode;
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
if (argument === '--range' || argument === '--head') {
|
|
53
|
+
const next = args[index + 1];
|
|
54
|
+
if (next === undefined || next === '') {
|
|
55
|
+
process.stderr.write(native(`error: ${argument} requires ${argument === '--range' ? 'A..B' : 'N'}\n`));
|
|
56
|
+
return undefined;
|
|
57
|
+
}
|
|
58
|
+
mode = argument.slice(2) as Mode;
|
|
59
|
+
value = next;
|
|
60
|
+
index += 1;
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
if (argument === '--help' || argument === '-h') {
|
|
64
|
+
process.stdout.write(native(usageText));
|
|
65
|
+
return 'help';
|
|
66
|
+
}
|
|
67
|
+
process.stderr.write(native(`error: unknown option: ${argument}\n${usageText}`));
|
|
68
|
+
return undefined;
|
|
69
|
+
}
|
|
70
|
+
if (mode === 'head' && !/^[1-9][0-9]*$/.test(value)) {
|
|
71
|
+
process.stderr.write(native(`error: --head requires a positive integer: ${value}\n`));
|
|
72
|
+
return undefined;
|
|
73
|
+
}
|
|
74
|
+
return { mode, value };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function emit(lines: readonly string[]): number {
|
|
78
|
+
process.stdout.write(Buffer.from(`${lines.join('\n')}\n`, 'latin1'));
|
|
79
|
+
return 0;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function emptyScope(mode: Mode, value: string, files: readonly string[]): string[] {
|
|
83
|
+
const out = ['scope:', ` mode: "${mode}"`];
|
|
84
|
+
if (mode === 'range') out.push(` range: "${yamlEscape(value)}"`);
|
|
85
|
+
out.push(` files_changed: ${files.length}`);
|
|
86
|
+
return [
|
|
87
|
+
...out,
|
|
88
|
+
' lines_added: 0',
|
|
89
|
+
' lines_removed: 0',
|
|
90
|
+
' files: []',
|
|
91
|
+
' records: []',
|
|
92
|
+
' typesafe_candidates: []',
|
|
93
|
+
' earlyreturn_candidates: []',
|
|
94
|
+
' bigo_candidates: []',
|
|
95
|
+
];
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function extractDiffScope(args: readonly string[]): number {
|
|
99
|
+
const parsed = parseArgs(args);
|
|
100
|
+
if (parsed === undefined) return 1;
|
|
101
|
+
if (parsed === 'help') return 0;
|
|
102
|
+
const diff = diffArgs(parsed, hasHeadCommit());
|
|
103
|
+
const tracked = changedFiles(diff);
|
|
104
|
+
const untracked = parsed.mode === 'working' ? untrackedFiles() : [];
|
|
105
|
+
const files = [...tracked, ...untracked];
|
|
106
|
+
if (files.length === 0) return emit(emptyScope(parsed.mode, parsed.value, files));
|
|
107
|
+
|
|
108
|
+
const counted = tracked.length > 0 ? countLines(diff, tracked) : { added: 0, removed: 0 };
|
|
109
|
+
const added = counted.added + untracked.reduce((total, path) => total + untrackedLineCount(path), 0);
|
|
110
|
+
const header = ['scope:', ` mode: "${parsed.mode}"`];
|
|
111
|
+
if (parsed.mode === 'range') header.push(` range: "${yamlEscape(parsed.value)}"`);
|
|
112
|
+
header.push(` files_changed: ${files.length}`, ` lines_added: ${added}`, ` lines_removed: ${counted.removed}`, ' files:');
|
|
113
|
+
const out = [...header, ...files.map((path) => ` - "${yamlEscape(path)}"`)];
|
|
114
|
+
|
|
115
|
+
const records: Record[] = tracked.length > 0 ? trackedRecords(diff, tracked) : [];
|
|
116
|
+
for (const path of untracked) records.push(...untrackedRecords(path));
|
|
117
|
+
|
|
118
|
+
for (const [key, pattern] of gates) {
|
|
119
|
+
const rows = records.filter((row) => pattern === null || pattern.test(row.content));
|
|
120
|
+
if (rows.length === 0) {
|
|
121
|
+
out.push(` ${key}: []`);
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
out.push(` ${key}:`);
|
|
125
|
+
for (const row of rows) {
|
|
126
|
+
out.push(` - file: "${row.path}"`, ` line: ${row.line}`, ' added: true', ` content: "${awkQuote(row.content)}"`);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return emit(out);
|
|
130
|
+
}
|