@bbcsoftwarefactory/cli 0.0.0-stage → 0.1.1

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