checkchange 0.4.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/LICENSE +21 -0
- package/README.md +150 -0
- package/dist/attribution.d.ts +19 -0
- package/dist/attribution.js +175 -0
- package/dist/auto-coverage.d.ts +8 -0
- package/dist/auto-coverage.js +93 -0
- package/dist/cache.d.ts +70 -0
- package/dist/cache.js +458 -0
- package/dist/cli.d.ts +51 -0
- package/dist/cli.js +810 -0
- package/dist/complexity-providers/pythonASTComplexityProvider.d.ts +9 -0
- package/dist/complexity-providers/pythonASTComplexityProvider.js +148 -0
- package/dist/complexity-providers/pythonDescriptorProvider.d.ts +17 -0
- package/dist/complexity-providers/pythonDescriptorProvider.js +119 -0
- package/dist/complexity-providers.d.ts +6 -0
- package/dist/complexity-providers.js +1 -0
- package/dist/complexity.d.ts +14 -0
- package/dist/complexity.js +75 -0
- package/dist/coverage-providers/lcovProvider.d.ts +12 -0
- package/dist/coverage-providers/lcovProvider.js +126 -0
- package/dist/coverage.d.ts +28 -0
- package/dist/coverage.js +451 -0
- package/dist/crap.d.ts +31 -0
- package/dist/crap.js +84 -0
- package/dist/crapCalc.d.ts +5 -0
- package/dist/crapCalc.js +11 -0
- package/dist/delta.d.ts +100 -0
- package/dist/delta.js +214 -0
- package/dist/evidence.d.ts +201 -0
- package/dist/evidence.js +906 -0
- package/dist/execute.d.ts +59 -0
- package/dist/execute.js +92 -0
- package/dist/formatters/github.d.ts +5 -0
- package/dist/formatters/github.js +27 -0
- package/dist/formatters/index.d.ts +47 -0
- package/dist/formatters/index.js +14 -0
- package/dist/formatters/junit.d.ts +5 -0
- package/dist/formatters/junit.js +32 -0
- package/dist/formatters/sarif.d.ts +5 -0
- package/dist/formatters/sarif.js +35 -0
- package/dist/fs-safety.d.ts +10 -0
- package/dist/fs-safety.js +47 -0
- package/dist/git.d.ts +50 -0
- package/dist/git.js +137 -0
- package/dist/help.d.ts +40 -0
- package/dist/help.js +274 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +4 -0
- package/dist/providers/config.d.ts +41 -0
- package/dist/providers/config.js +172 -0
- package/dist/providers/genericCommand.d.ts +3 -0
- package/dist/providers/genericCommand.js +89 -0
- package/dist/providers/index.d.ts +7 -0
- package/dist/providers/index.js +4 -0
- package/dist/providers/prepare.d.ts +124 -0
- package/dist/providers/prepare.js +459 -0
- package/dist/providers/runner-detection.d.ts +30 -0
- package/dist/providers/runner-detection.js +207 -0
- package/dist/rules.d.ts +27 -0
- package/dist/rules.js +54 -0
- package/package.json +52 -0
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { ComplexityInfo } from '../complexity.ts';
|
|
2
|
+
import { type CoverageResult } from '../coverage.js';
|
|
3
|
+
export interface PythonASTComplexityProvider {
|
|
4
|
+
extensions: string[];
|
|
5
|
+
collectComplexity: (cwd: string) => Promise<ComplexityInfo[]>;
|
|
6
|
+
describe(): string;
|
|
7
|
+
readCoverage: (cwd: string, file?: string) => Promise<CoverageResult>;
|
|
8
|
+
}
|
|
9
|
+
export declare const pythonASTComplexityProvider: PythonASTComplexityProvider;
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import { basename, relative } from 'node:path';
|
|
3
|
+
import { readCoverage } from '../coverage.js';
|
|
4
|
+
export const pythonASTComplexityProvider = {
|
|
5
|
+
extensions: ['.py'],
|
|
6
|
+
collectComplexity: (cwd) => {
|
|
7
|
+
return new Promise((resolve) => {
|
|
8
|
+
try {
|
|
9
|
+
// Find all Python files in the cwd, pruning node_modules and .git directories
|
|
10
|
+
const findResult = spawnSync('find', [cwd, '-path', `${cwd}/node_modules`, '-prune', '-o', '-path', `${cwd}/.git`, '-prune', '-o', '-name', '*.py', '-type', 'f', '-print'], { encoding: 'utf8' });
|
|
11
|
+
if (findResult.status !== 0) {
|
|
12
|
+
resolve([]);
|
|
13
|
+
return;
|
|
14
|
+
}
|
|
15
|
+
const files = findResult.stdout
|
|
16
|
+
.trim()
|
|
17
|
+
.split('\n')
|
|
18
|
+
.filter(f => f.trim().length > 0);
|
|
19
|
+
if (files.length === 0) {
|
|
20
|
+
resolve([]);
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
// Validate file names to avoid problematic characters
|
|
24
|
+
const isValidFileName = (file) => {
|
|
25
|
+
const baseName = basename(file);
|
|
26
|
+
const regex = /^[a-zA-Z0-9._/-]+$/;
|
|
27
|
+
return regex.test(baseName) && !baseName.includes('..') && !baseName.includes('\n') && !baseName.includes(';') && !baseName.includes('|');
|
|
28
|
+
};
|
|
29
|
+
const validFiles = files.filter(isValidFileName);
|
|
30
|
+
if (validFiles.length === 0) {
|
|
31
|
+
resolve([]);
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
// Validate file names to avoid problematic characters
|
|
35
|
+
// const isValidFileName = (file: string) => {
|
|
36
|
+
// const regex = /^[a-zA-Z0-9._\/\-]+$/;
|
|
37
|
+
// return regex.test(file) && !file.includes('..') && !file.includes('\n') && !file.includes(';') && !file.includes('|');
|
|
38
|
+
// };
|
|
39
|
+
// const validFiles = files.filter(isValidFileName);
|
|
40
|
+
// if (validFiles.length === 0) {
|
|
41
|
+
// resolve([]);
|
|
42
|
+
// return;
|
|
43
|
+
// }
|
|
44
|
+
const complexityInfo = [];
|
|
45
|
+
for (const file of validFiles) {
|
|
46
|
+
// We'll create a Python script that uses ast to compute CC for each function in the file
|
|
47
|
+
const pythonScript = `
|
|
48
|
+
import ast
|
|
49
|
+
import json
|
|
50
|
+
import sys
|
|
51
|
+
|
|
52
|
+
def compute_cc(node):
|
|
53
|
+
"""Compute cyclomatic complexity for a given AST node."""
|
|
54
|
+
cc = 1 # Base complexity
|
|
55
|
+
for child in ast.walk(node):
|
|
56
|
+
if isinstance(child, (ast.If, ast.For, ast.While, ast.With, ast.IfExp)):
|
|
57
|
+
cc += 1
|
|
58
|
+
elif isinstance(child, ast.ExceptHandler):
|
|
59
|
+
cc += 1
|
|
60
|
+
elif isinstance(child, ast.Assert):
|
|
61
|
+
cc += 1
|
|
62
|
+
elif isinstance(child, ast.BoolOp):
|
|
63
|
+
# Each And or Or inside a BoolOp adds one point per operator
|
|
64
|
+
if isinstance(child.op, (ast.And, ast.Or)):
|
|
65
|
+
cc += len(child.values) - 1
|
|
66
|
+
return cc
|
|
67
|
+
|
|
68
|
+
def main():
|
|
69
|
+
if len(sys.argv) < 2:
|
|
70
|
+
print(json.dumps([]))
|
|
71
|
+
return
|
|
72
|
+
|
|
73
|
+
filename = sys.argv[1]
|
|
74
|
+
try:
|
|
75
|
+
with open(filename, 'r') as f:
|
|
76
|
+
content = f.read()
|
|
77
|
+
except Exception as e:
|
|
78
|
+
print(json.dumps([]))
|
|
79
|
+
return
|
|
80
|
+
|
|
81
|
+
try:
|
|
82
|
+
tree = ast.parse(content)
|
|
83
|
+
except SyntaxError:
|
|
84
|
+
print(json.dumps([]))
|
|
85
|
+
return
|
|
86
|
+
|
|
87
|
+
results = []
|
|
88
|
+
for node in ast.walk(tree):
|
|
89
|
+
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)):
|
|
90
|
+
# For lambdas, we don't have a name? We'll skip lambdas for now because they are anonymous.
|
|
91
|
+
if isinstance(node, ast.Lambda):
|
|
92
|
+
continue
|
|
93
|
+
cc = compute_cc(node)
|
|
94
|
+
# Get function name
|
|
95
|
+
name = node.name if hasattr(node, 'name') else '<lambda>'
|
|
96
|
+
# Get line numbers (1-indexed in AST)
|
|
97
|
+
line_start = node.lineno
|
|
98
|
+
line_end = getattr(node, 'end_lineno', line_start)
|
|
99
|
+
results.append({
|
|
100
|
+
'file': filename,
|
|
101
|
+
'method': name,
|
|
102
|
+
'lineStart': line_start,
|
|
103
|
+
'lineEnd': line_end,
|
|
104
|
+
'cc': cc
|
|
105
|
+
})
|
|
106
|
+
|
|
107
|
+
print(json.dumps(results))
|
|
108
|
+
|
|
109
|
+
if __name__ == '__main__':
|
|
110
|
+
main()
|
|
111
|
+
`;
|
|
112
|
+
const cmdResult = spawnSync('python3', ['-c', pythonScript, file], { encoding: 'utf8' });
|
|
113
|
+
if (cmdResult.status !== 0) {
|
|
114
|
+
// If there's an error, skip this file
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
let parsed = [];
|
|
118
|
+
try {
|
|
119
|
+
parsed = JSON.parse(cmdResult.stdout);
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
// If parsing fails, skip this file
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
for (const info of parsed) {
|
|
126
|
+
// Convert to relative path for consistency with other providers
|
|
127
|
+
const rel = relative(cwd, info.file);
|
|
128
|
+
complexityInfo.push({
|
|
129
|
+
file: rel.replace(/\\/g, '/'),
|
|
130
|
+
method: info.method,
|
|
131
|
+
lineStart: info.lineStart,
|
|
132
|
+
lineEnd: info.lineEnd,
|
|
133
|
+
cc: info.cc
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
resolve(complexityInfo);
|
|
138
|
+
}
|
|
139
|
+
catch {
|
|
140
|
+
resolve([]);
|
|
141
|
+
}
|
|
142
|
+
});
|
|
143
|
+
},
|
|
144
|
+
describe() {
|
|
145
|
+
return 'Python AST-based complexity provider';
|
|
146
|
+
},
|
|
147
|
+
readCoverage: (cwd, file) => readCoverage(cwd, file)
|
|
148
|
+
};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export interface MethodDescriptor {
|
|
2
|
+
functionName: string;
|
|
3
|
+
containerName: string | null;
|
|
4
|
+
displayName: string;
|
|
5
|
+
startLine: number;
|
|
6
|
+
endLine: number;
|
|
7
|
+
complexity: number;
|
|
8
|
+
bodySpan: {
|
|
9
|
+
startLine: number;
|
|
10
|
+
startColumn: number;
|
|
11
|
+
endLine: number;
|
|
12
|
+
endColumn: number;
|
|
13
|
+
};
|
|
14
|
+
expectsStatementCoverage: boolean;
|
|
15
|
+
expectsBranchCoverage: boolean;
|
|
16
|
+
}
|
|
17
|
+
export declare function parsePythonFileMethods(filePath: string): Promise<MethodDescriptor[]>;
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import { basename } from 'node:path';
|
|
3
|
+
function isValidFileName(file) {
|
|
4
|
+
const baseName = basename(file);
|
|
5
|
+
const regex = /^[a-zA-Z0-9._/-]+$/;
|
|
6
|
+
return regex.test(baseName) && !baseName.includes('..') && !baseName.includes('\n') && !baseName.includes(';') && !baseName.includes('|');
|
|
7
|
+
}
|
|
8
|
+
export async function parsePythonFileMethods(filePath) {
|
|
9
|
+
if (!isValidFileName(filePath)) {
|
|
10
|
+
throw new Error(`Invalid file name: ${filePath}`);
|
|
11
|
+
}
|
|
12
|
+
const pythonScript = `
|
|
13
|
+
import ast
|
|
14
|
+
import json
|
|
15
|
+
import sys
|
|
16
|
+
|
|
17
|
+
def compute_cc(node):
|
|
18
|
+
"""Compute cyclomatic complexity for a given AST node."""
|
|
19
|
+
cc = 1 # Base complexity
|
|
20
|
+
for child in ast.walk(node):
|
|
21
|
+
if isinstance(child, (ast.If, ast.For, ast.While, ast.With, ast.IfExp)):
|
|
22
|
+
cc += 1
|
|
23
|
+
elif isinstance(child, ast.ExceptHandler):
|
|
24
|
+
cc += 1
|
|
25
|
+
elif isinstance(child, ast.Assert):
|
|
26
|
+
cc += 1
|
|
27
|
+
elif isinstance(child, ast.BoolOp):
|
|
28
|
+
# Each And or Or inside a BoolOp adds one point per operator
|
|
29
|
+
if isinstance(child.op, (ast.And, ast.Or)):
|
|
30
|
+
cc += len(child.values) - 1
|
|
31
|
+
return cc
|
|
32
|
+
|
|
33
|
+
def main():
|
|
34
|
+
if len(sys.argv) < 2:
|
|
35
|
+
print(json.dumps([]))
|
|
36
|
+
return
|
|
37
|
+
|
|
38
|
+
filename = sys.argv[1]
|
|
39
|
+
try:
|
|
40
|
+
with open(filename, 'r') as f:
|
|
41
|
+
content = f.read()
|
|
42
|
+
except Exception as e:
|
|
43
|
+
print(json.dumps([]))
|
|
44
|
+
return
|
|
45
|
+
|
|
46
|
+
try:
|
|
47
|
+
tree = ast.parse(content)
|
|
48
|
+
except SyntaxError:
|
|
49
|
+
print(json.dumps([]))
|
|
50
|
+
return
|
|
51
|
+
|
|
52
|
+
results = []
|
|
53
|
+
for node in ast.walk(tree):
|
|
54
|
+
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
55
|
+
cc = compute_cc(node)
|
|
56
|
+
name = node.name
|
|
57
|
+
line_start = node.lineno
|
|
58
|
+
line_end = getattr(node, 'end_lineno', line_start)
|
|
59
|
+
col_offset = node.col_offset
|
|
60
|
+
end_col_offset = getattr(node, 'end_col_offset', col_offset)
|
|
61
|
+
|
|
62
|
+
# Determine container (class) name
|
|
63
|
+
container_name = None
|
|
64
|
+
for parent in ast.walk(tree):
|
|
65
|
+
if isinstance(parent, ast.ClassDef):
|
|
66
|
+
for item in parent.body:
|
|
67
|
+
if item is node:
|
|
68
|
+
container_name = parent.name
|
|
69
|
+
break
|
|
70
|
+
if container_name:
|
|
71
|
+
break
|
|
72
|
+
|
|
73
|
+
display_name = f"{container_name}.{name}" if container_name else name
|
|
74
|
+
|
|
75
|
+
results.append({
|
|
76
|
+
'functionName': name,
|
|
77
|
+
'containerName': container_name,
|
|
78
|
+
'displayName': display_name,
|
|
79
|
+
'startLine': line_start,
|
|
80
|
+
'endLine': line_end,
|
|
81
|
+
'complexity': cc,
|
|
82
|
+
'bodySpan': {
|
|
83
|
+
'startLine': line_start,
|
|
84
|
+
'startColumn': col_offset,
|
|
85
|
+
'endLine': line_end,
|
|
86
|
+
'endColumn': end_col_offset
|
|
87
|
+
},
|
|
88
|
+
'expectsStatementCoverage': True,
|
|
89
|
+
'expectsBranchCoverage': True
|
|
90
|
+
})
|
|
91
|
+
|
|
92
|
+
print(json.dumps(results))
|
|
93
|
+
|
|
94
|
+
if __name__ == '__main__':
|
|
95
|
+
main()
|
|
96
|
+
`;
|
|
97
|
+
const cmdResult = spawnSync('python3', ['-c', pythonScript, filePath], { encoding: 'utf8' });
|
|
98
|
+
if (cmdResult.status !== 0) {
|
|
99
|
+
throw new Error(`Python script failed with status ${cmdResult.status}: ${cmdResult.stderr}`);
|
|
100
|
+
}
|
|
101
|
+
let parsed;
|
|
102
|
+
try {
|
|
103
|
+
parsed = JSON.parse(cmdResult.stdout);
|
|
104
|
+
}
|
|
105
|
+
catch (e) {
|
|
106
|
+
throw new Error(`Failed to parse Python AST output: ${cmdResult.stdout}`, { cause: e });
|
|
107
|
+
}
|
|
108
|
+
return parsed.map(item => ({
|
|
109
|
+
functionName: item.functionName,
|
|
110
|
+
containerName: item.containerName,
|
|
111
|
+
displayName: item.displayName,
|
|
112
|
+
startLine: item.startLine,
|
|
113
|
+
endLine: item.endLine,
|
|
114
|
+
complexity: item.complexity,
|
|
115
|
+
bodySpan: item.bodySpan,
|
|
116
|
+
expectsStatementCoverage: item.expectsStatementCoverage,
|
|
117
|
+
expectsBranchCoverage: item.expectsBranchCoverage
|
|
118
|
+
}));
|
|
119
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { TraceRun } from './execute.js';
|
|
2
|
+
export declare const complexityProvenance: {
|
|
3
|
+
readonly tool: "@barney-media/crap-typescript-core";
|
|
4
|
+
readonly version: "0.5.0";
|
|
5
|
+
};
|
|
6
|
+
export interface ComplexityInfo {
|
|
7
|
+
file: string;
|
|
8
|
+
method: string;
|
|
9
|
+
lineStart: number;
|
|
10
|
+
lineEnd: number;
|
|
11
|
+
cc: number;
|
|
12
|
+
}
|
|
13
|
+
export declare function getGitTrackedCodeFiles(cwd: string): string[];
|
|
14
|
+
export declare function collectComplexity(cwd: string, trace?: TraceRun, changedFiles?: ReadonlySet<string>): Promise<ComplexityInfo[]>;
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { findAllTypeScriptFilesUnderSourceRoots, parseFileMethods } from '@barney-media/crap-typescript-core';
|
|
2
|
+
import { relative, resolve } from 'node:path';
|
|
3
|
+
import { execSync } from 'node:child_process';
|
|
4
|
+
// Provenance for the complexity lineage stage: native analyzer from the core package.
|
|
5
|
+
export const complexityProvenance = { tool: '@barney-media/crap-typescript-core', version: '0.5.0' };
|
|
6
|
+
export function getGitTrackedCodeFiles(cwd) {
|
|
7
|
+
try {
|
|
8
|
+
// Get list of tracked files, one per line
|
|
9
|
+
const output = execSync('git ls-files --cached --others --exclude-standard', { cwd, encoding: 'utf8' });
|
|
10
|
+
const lines = output.trim().split('\n');
|
|
11
|
+
const codeFiles = [];
|
|
12
|
+
for (const line of lines) {
|
|
13
|
+
const trimmed = line.trim();
|
|
14
|
+
if (/\.(ts|tsx|js|jsx|mjs|cjs)$/.test(trimmed)) {
|
|
15
|
+
// Convert to absolute path
|
|
16
|
+
codeFiles.push(resolve(cwd, trimmed));
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
return codeFiles;
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
// If git fails (not a repo, or any error), return empty array
|
|
23
|
+
return [];
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
export async function collectComplexity(cwd, trace, changedFiles) {
|
|
27
|
+
// Find all TypeScript files under the source roots
|
|
28
|
+
const sourceRootFiles = await findAllTypeScriptFilesUnderSourceRoots(cwd);
|
|
29
|
+
// Get all tracked code files in the repo (respects .gitignore)
|
|
30
|
+
const gitTrackedCode = getGitTrackedCodeFiles(cwd);
|
|
31
|
+
// Union of both lists, deduplicated
|
|
32
|
+
const fileSet = new Set();
|
|
33
|
+
for (const f of sourceRootFiles) {
|
|
34
|
+
fileSet.add(f);
|
|
35
|
+
}
|
|
36
|
+
for (const f of gitTrackedCode) {
|
|
37
|
+
fileSet.add(f);
|
|
38
|
+
}
|
|
39
|
+
const filePaths = Array.from(fileSet);
|
|
40
|
+
const complexityInfo = [];
|
|
41
|
+
for (const filePath of filePaths) {
|
|
42
|
+
const rel = relative(cwd, filePath).replace(/\\/g, '/');
|
|
43
|
+
if (changedFiles && !changedFiles.has(rel))
|
|
44
|
+
continue;
|
|
45
|
+
try {
|
|
46
|
+
const methodDescriptors = await parseFileMethods(filePath);
|
|
47
|
+
for (const descriptor of methodDescriptors) {
|
|
48
|
+
// Build method name: if containerName exists, use "containerName.functionName", else just functionName
|
|
49
|
+
const methodName = descriptor.containerName
|
|
50
|
+
? `${descriptor.containerName}.${descriptor.functionName}`
|
|
51
|
+
: descriptor.functionName;
|
|
52
|
+
complexityInfo.push({
|
|
53
|
+
file: rel,
|
|
54
|
+
method: methodName,
|
|
55
|
+
lineStart: descriptor.startLine,
|
|
56
|
+
lineEnd: descriptor.endLine,
|
|
57
|
+
cc: descriptor.complexity,
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
catch (error) {
|
|
62
|
+
// If parsing fails for a single file (e.g., stray temp malformed JS), skip file rather than failing entire collection.
|
|
63
|
+
// With a TraceRun the warning buffers there; without one the CLI console behavior is preserved.
|
|
64
|
+
const message = `Warning: failed to parse ${filePath}, skipping: ${error instanceof Error ? error.message : String(error)}`;
|
|
65
|
+
if (trace) {
|
|
66
|
+
trace.recordWarning('complexity', message);
|
|
67
|
+
}
|
|
68
|
+
else {
|
|
69
|
+
console.error(message);
|
|
70
|
+
}
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return complexityInfo;
|
|
75
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { coverageForMethods } from '@barney-media/crap-typescript-core';
|
|
2
|
+
type FileCoverage = NonNullable<Parameters<typeof coverageForMethods>[1]>;
|
|
3
|
+
/**
|
|
4
|
+
* Parse LCOV content and convert it to the same Map shape the core package's
|
|
5
|
+
* parseCoverageReport produces, so coverageForMethods can attribute methods.
|
|
6
|
+
* @param lcovContent The LCOV file content as string
|
|
7
|
+
* @param cwd Current working directory for path normalization
|
|
8
|
+
* @returns Map<filePath, { statements: Array<{ span: { startLine: number, startColumn: number, endLine: number, endColumn: number }, hits: number }>, branches: [], functions: [] }>
|
|
9
|
+
* Branches and functions are always empty: LCOV BRDA and FN/FNDA records are not parsed.
|
|
10
|
+
*/
|
|
11
|
+
export declare function parseLcovContent(lcovContent: string, cwd: string): Map<string, FileCoverage>;
|
|
12
|
+
export {};
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import * as path from 'node:path';
|
|
2
|
+
import * as fs from 'node:fs';
|
|
3
|
+
/**
|
|
4
|
+
* Parse LCOV content and convert it to the same Map shape the core package's
|
|
5
|
+
* parseCoverageReport produces, so coverageForMethods can attribute methods.
|
|
6
|
+
* @param lcovContent The LCOV file content as string
|
|
7
|
+
* @param cwd Current working directory for path normalization
|
|
8
|
+
* @returns Map<filePath, { statements: Array<{ span: { startLine: number, startColumn: number, endLine: number, endColumn: number }, hits: number }>, branches: [], functions: [] }>
|
|
9
|
+
* Branches and functions are always empty: LCOV BRDA and FN/FNDA records are not parsed.
|
|
10
|
+
*/
|
|
11
|
+
export function parseLcovContent(lcovContent, cwd) {
|
|
12
|
+
// Security: limit LCOV size to prevent OOM
|
|
13
|
+
const MAX_SIZE = 100 * 1024 * 1024; // 100MB
|
|
14
|
+
if (lcovContent.length > MAX_SIZE) {
|
|
15
|
+
throw new Error(`LCOV content exceeds maximum allowed size of ${MAX_SIZE} bytes`);
|
|
16
|
+
}
|
|
17
|
+
const result = new Map();
|
|
18
|
+
let currentFile = '';
|
|
19
|
+
// Keyed by LCOV line number so a repeated DA:<line> overwrites, as before.
|
|
20
|
+
const statements = {};
|
|
21
|
+
const lines = lcovContent.split('\n');
|
|
22
|
+
if (lines.length > 1_000_000) {
|
|
23
|
+
throw new Error('LCOV contains too many lines (over 1,000,000)');
|
|
24
|
+
}
|
|
25
|
+
for (const line of lines) {
|
|
26
|
+
const lineTrimmed = line.trim();
|
|
27
|
+
if (lineTrimmed.startsWith('SF:')) {
|
|
28
|
+
// Before starting a new file, finalize the previous one
|
|
29
|
+
if (currentFile && Object.keys(statements).length > 0) {
|
|
30
|
+
const normalized = normalizePath(currentFile, cwd);
|
|
31
|
+
if (normalized !== null) {
|
|
32
|
+
result.set(normalized, {
|
|
33
|
+
statements: Object.values(statements),
|
|
34
|
+
branches: [],
|
|
35
|
+
functions: []
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
// Reset for next file
|
|
39
|
+
Object.keys(statements).forEach(k => delete statements[k]);
|
|
40
|
+
}
|
|
41
|
+
// Extract file path (remove leading './' if present)
|
|
42
|
+
const filePath = lineTrimmed.substring(3).trim();
|
|
43
|
+
currentFile = filePath;
|
|
44
|
+
}
|
|
45
|
+
else if (lineTrimmed.startsWith('DA:')) {
|
|
46
|
+
// DA:lineNumber,hitCount
|
|
47
|
+
const parts = lineTrimmed.substring(3).split(',');
|
|
48
|
+
if (parts.length >= 2) {
|
|
49
|
+
const lineNumStr = parts[0];
|
|
50
|
+
const hitCountStr = parts[1];
|
|
51
|
+
const lineNum = parseInt(lineNumStr, 10);
|
|
52
|
+
const hitCount = parseInt(hitCountStr, 10);
|
|
53
|
+
if (!isNaN(lineNum) && !isNaN(hitCount)) {
|
|
54
|
+
// Use line number as the statement key
|
|
55
|
+
const key = lineNumStr;
|
|
56
|
+
statements[key] = {
|
|
57
|
+
// LCOV doesn't have column info, assume 0
|
|
58
|
+
span: { startLine: lineNum, startColumn: 0, endLine: lineNum, endColumn: 0 },
|
|
59
|
+
hits: hitCount
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
// We ignore FN/FNDA for function coverage and BRDA/BRF for branch coverage for simplicity.
|
|
65
|
+
// If needed, we can extend later.
|
|
66
|
+
}
|
|
67
|
+
// Handle the last file
|
|
68
|
+
if (currentFile && Object.keys(statements).length > 0) {
|
|
69
|
+
const normalized = normalizePath(currentFile, cwd);
|
|
70
|
+
if (normalized !== null) {
|
|
71
|
+
result.set(normalized, {
|
|
72
|
+
statements: Object.values(statements),
|
|
73
|
+
branches: [],
|
|
74
|
+
functions: []
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return result;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Check if an absolute file path is within the given cwd.
|
|
82
|
+
* @param filePath Absolute file path to check
|
|
83
|
+
* @param cwd Current working directory (absolute)
|
|
84
|
+
* @returns true if filePath is within cwd
|
|
85
|
+
*/
|
|
86
|
+
function isWithinCwd(filePath, cwd) {
|
|
87
|
+
// Ensure we are working with absolute paths for the check
|
|
88
|
+
if (!path.isAbsolute(filePath)) {
|
|
89
|
+
filePath = path.resolve(cwd, filePath);
|
|
90
|
+
}
|
|
91
|
+
const rel = path.relative(cwd, filePath);
|
|
92
|
+
return !rel.startsWith('..') && !path.isAbsolute(rel);
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Normalize a file path from LCOV to be relative to cwd if possible.
|
|
96
|
+
* Similar to the normalizeCoveragePaths function in coverage.ts.
|
|
97
|
+
* @returns normalized path within cwd, or null if the path escapes cwd and cannot be rebased
|
|
98
|
+
*/
|
|
99
|
+
function normalizePath(filePath, cwd) {
|
|
100
|
+
if (!path.isAbsolute(filePath)) {
|
|
101
|
+
const resolved = path.resolve(cwd, filePath);
|
|
102
|
+
const within = isWithinCwd(resolved, cwd);
|
|
103
|
+
return within ? resolved : null;
|
|
104
|
+
}
|
|
105
|
+
// If absolute, first check if it's already within cwd
|
|
106
|
+
if (isWithinCwd(filePath, cwd)) {
|
|
107
|
+
return filePath;
|
|
108
|
+
}
|
|
109
|
+
// Try to rebase to cwd by suffix (like normalizeCoveragePaths)
|
|
110
|
+
const segments = filePath.split(path.sep);
|
|
111
|
+
for (let i = 1; i < segments.length; i++) {
|
|
112
|
+
const candidate = path.join(cwd, ...segments.slice(i));
|
|
113
|
+
const rel = path.relative(cwd, candidate);
|
|
114
|
+
if (rel.startsWith('..') || path.isAbsolute(rel))
|
|
115
|
+
continue;
|
|
116
|
+
try {
|
|
117
|
+
if (fs.existsSync(candidate)) {
|
|
118
|
+
return candidate;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
// ignore
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
return null;
|
|
126
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { parseCoverageReport } from '@barney-media/crap-typescript-core';
|
|
2
|
+
type CoverageMap = Awaited<ReturnType<typeof parseCoverageReport>>;
|
|
3
|
+
import type { TraceRun } from './execute.js';
|
|
4
|
+
export declare const coverageProvenance: {
|
|
5
|
+
readonly tool: "@barney-media/crap-typescript-core";
|
|
6
|
+
readonly version: "0.5.0";
|
|
7
|
+
};
|
|
8
|
+
export interface CoverageResult {
|
|
9
|
+
available: boolean;
|
|
10
|
+
coverageMap: CoverageMap | null;
|
|
11
|
+
error: boolean;
|
|
12
|
+
reason?: string;
|
|
13
|
+
/** SHA-256 hex of the coverage artifact bytes as read (present only on a successful read). */
|
|
14
|
+
contentSha256?: string;
|
|
15
|
+
}
|
|
16
|
+
export declare const PYTHON_COVERAGE_FILES: readonly string[];
|
|
17
|
+
export declare function readCoverage(cwd: string, coverageFile?: string, trace?: TraceRun, autoGenerated?: boolean): Promise<CoverageResult>;
|
|
18
|
+
/**
|
|
19
|
+
* Detect the coverage format and dispatch to the matching parser.
|
|
20
|
+
*
|
|
21
|
+
* Routes:
|
|
22
|
+
* - LCOV: by extension (`.info`/`.lcov`) or content sniffing (TN:/SF:/DA: lines).
|
|
23
|
+
* - Python coverage JSON (files key + meta/summary/totals): transformed to Istanbul
|
|
24
|
+
* first, unless alreadyConverted (i.e. convertPythonCoverageToJson already ran).
|
|
25
|
+
* - Otherwise: parsed directly as Istanbul JSON.
|
|
26
|
+
*/
|
|
27
|
+
export declare function detectCoverageFormat(content: string, actualPath: string, cwd: string, isLcovByExt: boolean, alreadyConverted: boolean): Promise<CoverageMap>;
|
|
28
|
+
export {};
|