ouch4ts 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/LICENSE +21 -0
- package/README.md +45 -2
- package/dist/cache.d.ts +33 -0
- package/dist/cache.js +29 -0
- package/dist/changes.d.ts +6 -0
- package/dist/changes.js +63 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +3 -0
- package/dist/cognitive.d.ts +9 -0
- package/dist/cognitive.js +192 -0
- package/dist/command.d.ts +4 -0
- package/dist/command.js +217 -0
- package/dist/comparison.d.ts +92 -0
- package/dist/comparison.js +243 -0
- package/dist/configuration.d.ts +9 -0
- package/dist/configuration.js +56 -0
- package/dist/cycles.d.ts +5 -0
- package/dist/cycles.js +73 -0
- package/dist/discovery.d.ts +1 -0
- package/dist/discovery.js +27 -0
- package/dist/files.d.ts +9 -0
- package/dist/files.js +53 -0
- package/dist/format.d.ts +5 -0
- package/dist/format.js +28 -0
- package/dist/git.d.ts +1 -0
- package/dist/git.js +13 -0
- package/dist/index.d.ts +60 -0
- package/dist/index.js +207 -0
- package/dist/lcov.d.ts +1 -0
- package/dist/lcov.js +49 -0
- package/dist/manifest.d.ts +3 -0
- package/dist/manifest.js +19 -0
- package/dist/package-manager.d.ts +2 -0
- package/dist/package-manager.js +121 -0
- package/dist/process.d.ts +1 -0
- package/dist/process.js +9 -0
- package/dist/project.d.ts +39 -0
- package/dist/project.js +54 -0
- package/dist/recursion.d.ts +3 -0
- package/dist/recursion.js +340 -0
- package/dist/report.d.ts +30 -0
- package/dist/report.js +57 -0
- package/dist/syntax.d.ts +21 -0
- package/dist/syntax.js +93 -0
- package/package.json +49 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Jeremy Wood
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,46 @@
|
|
|
1
|
-
#
|
|
1
|
+
# ouch4ts
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
`ouch4ts` reports file complexity and function maintenance scores for JavaScript,
|
|
4
|
+
TypeScript, and mixed projects. It provides a CLI, a typed ESM API, and an
|
|
5
|
+
[agent skill](skills/ouch4ts/SKILL.md).
|
|
6
|
+
The analyzer requires Node 22 or newer.
|
|
7
|
+
|
|
8
|
+
OUCH stands for Overall Upkeep and Change Hassle. It adds cognitive complexity to
|
|
9
|
+
CRAP, Change Risk Anti-Patterns:
|
|
10
|
+
|
|
11
|
+
```text
|
|
12
|
+
OUCH = cyclomatic² × (1 - coverage)³ + cyclomatic + cognitive
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Coverage is a fraction from 0 to 1 in the formula. A function with cyclomatic
|
|
16
|
+
complexity 2, cognitive complexity 1, and 50% coverage scores 3.5. Higher scores
|
|
17
|
+
identify functions worth examining for missing tests or simpler control flow.
|
|
18
|
+
Scores do not estimate maintenance hours or defect probability.
|
|
19
|
+
|
|
20
|
+
The scoring draws on [Uncle Bob's crap4clj](https://github.com/unclebob/crap4clj)
|
|
21
|
+
and [SonarSource's Cognitive Complexity whitepaper, version 1.7](https://www.sonarsource.com/docs/CognitiveComplexity.pdf).
|
|
22
|
+
|
|
23
|
+
## Documentation
|
|
24
|
+
|
|
25
|
+
The guides and references cover these tasks and details:
|
|
26
|
+
|
|
27
|
+
- [Analyze a project](docs/analyze-project.md):
|
|
28
|
+
build the analyzer, generate reports, compare commits, and install the agent skill.
|
|
29
|
+
- [CLI reference](docs/cli.md):
|
|
30
|
+
options, configuration, report fields, filtering, and exit codes.
|
|
31
|
+
- [Library reference](docs/library.md):
|
|
32
|
+
`analyze`, `analyzeReport`, and `AnalysisOptions`.
|
|
33
|
+
- [Measurement conventions](skills/ouch4ts/references/measurement.md):
|
|
34
|
+
score formulas, complexity rules, source selection, and coverage limits.
|
|
35
|
+
- [Develop and package ouch4ts](docs/development.md):
|
|
36
|
+
local checks, package contents, and release labels.
|
|
37
|
+
- [Release process](docs/releases.md):
|
|
38
|
+
previews, stable releases, maintenance branches, and publication recovery.
|
|
39
|
+
|
|
40
|
+
## Licenses
|
|
41
|
+
|
|
42
|
+
The analyzer and root npm package use the
|
|
43
|
+
[MIT license](LICENSE).
|
|
44
|
+
The companion skill and all files under `skills/ouch4ts` use the separate
|
|
45
|
+
[0BSD license](skills/ouch4ts/LICENSE).
|
|
46
|
+
The npm package excludes skill assets.
|
package/dist/cache.d.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { analyzeProject } from "./project.js";
|
|
2
|
+
type Report = Awaited<ReturnType<typeof analyzeProject>>;
|
|
3
|
+
export declare function readCache(path: string, commit: string, settingsKey: string): Promise<{
|
|
4
|
+
entries: ({
|
|
5
|
+
coverage: null;
|
|
6
|
+
crap: null;
|
|
7
|
+
ouch: null;
|
|
8
|
+
name: string;
|
|
9
|
+
file: string;
|
|
10
|
+
line: number;
|
|
11
|
+
endLine: number;
|
|
12
|
+
complexity: number;
|
|
13
|
+
cognitive: number;
|
|
14
|
+
} | {
|
|
15
|
+
coverage: number;
|
|
16
|
+
crap: number;
|
|
17
|
+
ouch: number;
|
|
18
|
+
name: string;
|
|
19
|
+
file: string;
|
|
20
|
+
line: number;
|
|
21
|
+
endLine: number;
|
|
22
|
+
complexity: number;
|
|
23
|
+
cognitive: number;
|
|
24
|
+
})[];
|
|
25
|
+
files: {
|
|
26
|
+
complexity: number;
|
|
27
|
+
cognitive: number;
|
|
28
|
+
functions: number;
|
|
29
|
+
file: string;
|
|
30
|
+
}[];
|
|
31
|
+
} | null>;
|
|
32
|
+
export declare function writeCache(path: string, commit: string, settingsKey: string, report: Report): Promise<void>;
|
|
33
|
+
export {};
|
package/dist/cache.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { isMissingFile, writeJson } from "./files.js";
|
|
3
|
+
import { isRecord, validatedReport } from "./report.js";
|
|
4
|
+
export async function readCache(path, commit, settingsKey) {
|
|
5
|
+
let data;
|
|
6
|
+
try {
|
|
7
|
+
data = JSON.parse(await readFile(path, "utf8"));
|
|
8
|
+
}
|
|
9
|
+
catch (error) {
|
|
10
|
+
if (isCacheMiss(error))
|
|
11
|
+
return null;
|
|
12
|
+
throw error;
|
|
13
|
+
}
|
|
14
|
+
return cachedReport(data, commit, settingsKey);
|
|
15
|
+
}
|
|
16
|
+
function isCacheMiss(error) {
|
|
17
|
+
return error instanceof SyntaxError || isMissingFile(error);
|
|
18
|
+
}
|
|
19
|
+
function cachedReport(data, commit, settingsKey) {
|
|
20
|
+
if (!isMatchingReport(data, commit, settingsKey))
|
|
21
|
+
return null;
|
|
22
|
+
return validatedReport(data);
|
|
23
|
+
}
|
|
24
|
+
function isMatchingReport(data, commit, settingsKey) {
|
|
25
|
+
return isRecord(data) && data.commit === commit && data.settingsKey === settingsKey;
|
|
26
|
+
}
|
|
27
|
+
export async function writeCache(path, commit, settingsKey, report) {
|
|
28
|
+
await writeJson(path, { commit, settingsKey, ...report });
|
|
29
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { analyze } from "./index.js";
|
|
2
|
+
/** Read the Git diff once, then match current-source function ranges against changed lines. */
|
|
3
|
+
export declare function changedSourceFilter(reference: string, cwd?: string): {
|
|
4
|
+
matchesFile: (file: string) => boolean;
|
|
5
|
+
matchesFunction: (entry: ReturnType<typeof analyze>[number]) => boolean;
|
|
6
|
+
};
|
package/dist/changes.js
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { resolve } from "node:path";
|
|
2
|
+
import { git } from "./git.js";
|
|
3
|
+
/** Read the Git diff once, then match current-source function ranges against changed lines. */
|
|
4
|
+
export function changedSourceFilter(reference, cwd = process.cwd()) {
|
|
5
|
+
const root = git(["rev-parse", "--show-toplevel"], cwd).trimEnd();
|
|
6
|
+
const commit = git(["rev-parse", "--verify", "--end-of-options", `${reference}^{commit}`], cwd).trim();
|
|
7
|
+
const base = git(["merge-base", commit, "HEAD"], cwd).trim();
|
|
8
|
+
const diff = git(["-c", "core.quotePath=false", "diff", "--no-color", "--no-ext-diff", "--no-textconv",
|
|
9
|
+
"--no-relative", "--src-prefix=a/", "--dst-prefix=b/", "--find-renames", "--unified=0",
|
|
10
|
+
"--inter-hunk-context=0", base, "--"], cwd);
|
|
11
|
+
const changes = changedRanges(diff, root);
|
|
12
|
+
return {
|
|
13
|
+
matchesFile: (file) => changes.has(resolve(cwd, file)),
|
|
14
|
+
matchesFunction: (entry) => (changes.get(resolve(cwd, entry.file)) ?? [])
|
|
15
|
+
.some(range => overlapsFunction(range, entry)),
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
function changedRanges(diff, root) {
|
|
19
|
+
const changes = new Map();
|
|
20
|
+
let file;
|
|
21
|
+
for (const line of diff.split("\n")) {
|
|
22
|
+
file = currentDiffFile(line, root, file);
|
|
23
|
+
if (file !== undefined)
|
|
24
|
+
addHunk(changes, file, line);
|
|
25
|
+
}
|
|
26
|
+
return changes;
|
|
27
|
+
}
|
|
28
|
+
function currentDiffFile(line, root, file) {
|
|
29
|
+
if (line.startsWith("diff --git "))
|
|
30
|
+
return undefined;
|
|
31
|
+
return file ?? fileFromCurrentSideHeader(line, root);
|
|
32
|
+
}
|
|
33
|
+
function fileFromCurrentSideHeader(line, root) {
|
|
34
|
+
if (line.startsWith("+++ "))
|
|
35
|
+
return currentFilePath(line, root);
|
|
36
|
+
}
|
|
37
|
+
function currentFilePath(header, root) {
|
|
38
|
+
const path = decodeGitPath(header.slice(4).replace(/\t$/, ""));
|
|
39
|
+
return path.startsWith("b/") ? resolve(root, path.slice(2)) : undefined;
|
|
40
|
+
}
|
|
41
|
+
function addHunk(changes, file, line) {
|
|
42
|
+
const hunk = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(line);
|
|
43
|
+
if (!hunk)
|
|
44
|
+
return;
|
|
45
|
+
const ranges = changes.get(file) ?? [];
|
|
46
|
+
ranges.push({ start: Number(hunk[1]), count: Number(hunk[2] ?? 1) });
|
|
47
|
+
changes.set(file, ranges);
|
|
48
|
+
}
|
|
49
|
+
function overlapsFunction({ start, count }, entry) {
|
|
50
|
+
const lastChangedLine = start + Math.max(count - 1, 0);
|
|
51
|
+
// A deletion requires the function to contain the following line as well.
|
|
52
|
+
const requiredEndLine = start + Number(count === 0);
|
|
53
|
+
return entry.line <= lastChangedLine && entry.endLine >= requiredEndLine;
|
|
54
|
+
}
|
|
55
|
+
// Git uses C escapes for special path characters even with core.quotePath disabled.
|
|
56
|
+
function decodeGitPath(path) {
|
|
57
|
+
if (!path.startsWith('"'))
|
|
58
|
+
return path;
|
|
59
|
+
const escapes = {
|
|
60
|
+
a: "\x07", b: "\b", f: "\f", n: "\n", r: "\r", t: "\t", v: "\v", '"': '"', "\\": "\\",
|
|
61
|
+
};
|
|
62
|
+
return path.slice(1, -1).replace(/\\([0-7]{1,3}|[abfnrtv"\\])/g, (_, token) => escapes[token] ?? String.fromCharCode(Number.parseInt(token, 8)));
|
|
63
|
+
}
|
package/dist/cli.d.ts
ADDED
package/dist/cli.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import ts from "typescript";
|
|
2
|
+
/** Measure a function and its nested functions using the Cognitive Complexity whitepaper. */
|
|
3
|
+
export declare function cognitiveComplexity(node: ts.FunctionLikeDeclaration, recursive: ReadonlySet<ts.SignatureDeclaration>): number;
|
|
4
|
+
/** File cognitive complexity counts each syntax node once, including module-level code. */
|
|
5
|
+
export declare function fileComplexity(source: ts.SourceFile, recursive: ReadonlySet<ts.SignatureDeclaration>): {
|
|
6
|
+
complexity: number;
|
|
7
|
+
cognitive: number;
|
|
8
|
+
functions: number;
|
|
9
|
+
};
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import ts from "typescript";
|
|
2
|
+
import { definitionExpressions, hasImplementation, isSimpleAssignment, unwrapExpression } from "./syntax.js";
|
|
3
|
+
/** Measure a function and its nested functions using the Cognitive Complexity whitepaper. */
|
|
4
|
+
export function cognitiveComplexity(node, recursive) {
|
|
5
|
+
const counter = new CognitiveCounter(recursive);
|
|
6
|
+
counter.visitFunction(node, 0, 0);
|
|
7
|
+
return counter.complexity;
|
|
8
|
+
}
|
|
9
|
+
class CognitiveCounter {
|
|
10
|
+
recursive;
|
|
11
|
+
complexity = 0;
|
|
12
|
+
countedLogical = new Set();
|
|
13
|
+
constructor(recursive) {
|
|
14
|
+
this.recursive = recursive;
|
|
15
|
+
}
|
|
16
|
+
visit(node, nesting, functionDepth) {
|
|
17
|
+
if (ts.isFunctionLike(node)) {
|
|
18
|
+
this.visitDefinition(node, nesting, functionDepth);
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
this.complexity += controlFlowIncrement(node, nesting) + logicalIncrement(node, this.countedLogical);
|
|
22
|
+
const nested = childrenWithDeeperNesting(node);
|
|
23
|
+
ts.forEachChild(node, child => {
|
|
24
|
+
this.visit(child, nesting + Number(nested.includes(child)), functionDepth);
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
visitDefinition(node, nesting, functionDepth) {
|
|
28
|
+
for (const expression of definitionExpressions(node))
|
|
29
|
+
this.visit(expression, nesting, functionDepth);
|
|
30
|
+
this.visitFunction(node, nesting, functionDepth);
|
|
31
|
+
}
|
|
32
|
+
visitFunction(node, nesting, functionDepth) {
|
|
33
|
+
if (!hasImplementation(node))
|
|
34
|
+
return;
|
|
35
|
+
this.complexity += Number(this.recursive.has(node));
|
|
36
|
+
const executable = !isDeclarativeFunction(node);
|
|
37
|
+
const nested = nesting + Number(isNestedExecutableFunction(functionDepth, executable));
|
|
38
|
+
const depth = functionDepth + Number(executable);
|
|
39
|
+
for (const parameter of node.parameters)
|
|
40
|
+
this.visit(parameter, nested, depth);
|
|
41
|
+
this.visit(node.body, nested, depth);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
function isNestedExecutableFunction(depth, executable) {
|
|
45
|
+
return depth > 0 && executable;
|
|
46
|
+
}
|
|
47
|
+
const declarationKinds = new Set([
|
|
48
|
+
ts.SyntaxKind.VariableStatement, ts.SyntaxKind.FunctionDeclaration, ts.SyntaxKind.ClassDeclaration,
|
|
49
|
+
ts.SyntaxKind.InterfaceDeclaration, ts.SyntaxKind.TypeAliasDeclaration, ts.SyntaxKind.EnumDeclaration,
|
|
50
|
+
ts.SyntaxKind.ModuleDeclaration,
|
|
51
|
+
]);
|
|
52
|
+
function isDeclarativeFunction(node) {
|
|
53
|
+
return isDeclarationBlock(node.body) && !hasStructuralCode(node.body) && !node.parameters.some(hasStructuralCode);
|
|
54
|
+
}
|
|
55
|
+
function isDeclarationBlock(body) {
|
|
56
|
+
return ts.isBlock(body) && body.statements.every(isDeclaration);
|
|
57
|
+
}
|
|
58
|
+
function isDeclaration(node) {
|
|
59
|
+
if (declarationKinds.has(node.kind))
|
|
60
|
+
return true;
|
|
61
|
+
if (!ts.isExpressionStatement(node))
|
|
62
|
+
return false;
|
|
63
|
+
return isDefinitionAssignment(node.expression);
|
|
64
|
+
}
|
|
65
|
+
function isDefinitionAssignment(node) {
|
|
66
|
+
node = unwrapExpression(node);
|
|
67
|
+
if (!isSimpleAssignment(node))
|
|
68
|
+
return false;
|
|
69
|
+
const value = unwrapExpression(node.right);
|
|
70
|
+
return definitionKinds.has(value.kind);
|
|
71
|
+
}
|
|
72
|
+
const definitionKinds = new Set([
|
|
73
|
+
ts.SyntaxKind.FunctionExpression, ts.SyntaxKind.ArrowFunction, ts.SyntaxKind.ClassExpression,
|
|
74
|
+
]);
|
|
75
|
+
function hasStructuralCode(node) {
|
|
76
|
+
if (ts.isFunctionLike(node))
|
|
77
|
+
return definitionExpressions(node).some(hasStructuralCode);
|
|
78
|
+
return isStructural(node) || ts.forEachChild(node, hasStructuralCode) === true;
|
|
79
|
+
}
|
|
80
|
+
/** File cognitive complexity counts each syntax node once, including module-level code. */
|
|
81
|
+
export function fileComplexity(source, recursive) {
|
|
82
|
+
const syntax = new FileSyntaxCounter();
|
|
83
|
+
syntax.visit(source);
|
|
84
|
+
const counter = new CognitiveCounter(recursive);
|
|
85
|
+
counter.visit(source, 0, 0);
|
|
86
|
+
return { complexity: syntax.complexity, cognitive: counter.complexity, functions: syntax.functions };
|
|
87
|
+
}
|
|
88
|
+
class FileSyntaxCounter {
|
|
89
|
+
complexity = 0;
|
|
90
|
+
functions = 0;
|
|
91
|
+
visit(node) {
|
|
92
|
+
const implemented = hasImplementation(node);
|
|
93
|
+
this.functions += Number(implemented);
|
|
94
|
+
this.complexity += Number(implemented) + Number(isFileDecision(node));
|
|
95
|
+
ts.forEachChild(node, child => this.visit(child));
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
function isFileDecision(node) {
|
|
99
|
+
return fileDecisionKinds.has(node.kind) || isLogicalExpression(node);
|
|
100
|
+
}
|
|
101
|
+
const fileDecisionKinds = new Set([
|
|
102
|
+
ts.SyntaxKind.IfStatement, ts.SyntaxKind.ConditionalExpression, ts.SyntaxKind.ForStatement,
|
|
103
|
+
ts.SyntaxKind.ForInStatement, ts.SyntaxKind.ForOfStatement, ts.SyntaxKind.WhileStatement,
|
|
104
|
+
ts.SyntaxKind.DoStatement, ts.SyntaxKind.CaseClause, ts.SyntaxKind.DefaultClause,
|
|
105
|
+
]);
|
|
106
|
+
function isStructural(node) {
|
|
107
|
+
if (ts.isIfStatement(node))
|
|
108
|
+
return !(ts.isIfStatement(node.parent) && node.parent.elseStatement === node);
|
|
109
|
+
return isNestingStructure(node);
|
|
110
|
+
}
|
|
111
|
+
function controlFlowIncrement(node, nesting) {
|
|
112
|
+
if (ts.isIfStatement(node))
|
|
113
|
+
return conditionIncrement(node, nesting);
|
|
114
|
+
if (isNestingStructure(node))
|
|
115
|
+
return nesting + 1;
|
|
116
|
+
return Number(isLabeledJump(node));
|
|
117
|
+
}
|
|
118
|
+
function isLabeledJump(node) {
|
|
119
|
+
return (ts.isBreakStatement(node) || ts.isContinueStatement(node)) && node.label !== undefined;
|
|
120
|
+
}
|
|
121
|
+
function conditionIncrement(node, nesting) {
|
|
122
|
+
const condition = isElseIf(node) ? 1 : nesting + 1;
|
|
123
|
+
return condition + Number(hasFinalElse(node));
|
|
124
|
+
}
|
|
125
|
+
function isElseIf(node) {
|
|
126
|
+
return ts.isIfStatement(node.parent) && node.parent.elseStatement === node;
|
|
127
|
+
}
|
|
128
|
+
function hasFinalElse(node) {
|
|
129
|
+
return node.elseStatement !== undefined && !ts.isIfStatement(node.elseStatement);
|
|
130
|
+
}
|
|
131
|
+
function isNestingStructure(node) {
|
|
132
|
+
return ts.isIterationStatement(node, false) || ts.isSwitchStatement(node) ||
|
|
133
|
+
ts.isCatchClause(node) || ts.isConditionalExpression(node);
|
|
134
|
+
}
|
|
135
|
+
function childrenWithDeeperNesting(node) {
|
|
136
|
+
if (ts.isIterationStatement(node, false))
|
|
137
|
+
return [node.statement];
|
|
138
|
+
if (ts.isCaseBlock(node))
|
|
139
|
+
return node.clauses;
|
|
140
|
+
return catchBody(node) ?? conditionalBranches(node);
|
|
141
|
+
}
|
|
142
|
+
function catchBody(node) {
|
|
143
|
+
if (ts.isCatchClause(node))
|
|
144
|
+
return [node.block];
|
|
145
|
+
}
|
|
146
|
+
function conditionalBranches(node) {
|
|
147
|
+
if (ts.isConditionalExpression(node))
|
|
148
|
+
return [node.whenTrue, node.whenFalse];
|
|
149
|
+
if (!ts.isIfStatement(node))
|
|
150
|
+
return [];
|
|
151
|
+
return ifBranchesWithDeeperNesting(node);
|
|
152
|
+
}
|
|
153
|
+
function ifBranchesWithDeeperNesting(node) {
|
|
154
|
+
return hasFinalElse(node) ? [node.thenStatement, node.elseStatement] : [node.thenStatement];
|
|
155
|
+
}
|
|
156
|
+
const logicalOperators = new Set([
|
|
157
|
+
ts.SyntaxKind.AmpersandAmpersandToken, ts.SyntaxKind.BarBarToken, ts.SyntaxKind.QuestionQuestionToken,
|
|
158
|
+
]);
|
|
159
|
+
function isLogicalExpression(node) {
|
|
160
|
+
return ts.isBinaryExpression(node) && logicalOperators.has(node.operatorToken.kind);
|
|
161
|
+
}
|
|
162
|
+
function logicalIncrement(node, counted) {
|
|
163
|
+
if (!isUncountedLogicalExpression(node, counted))
|
|
164
|
+
return 0;
|
|
165
|
+
const sequence = logicalSequence(node);
|
|
166
|
+
for (const expression of sequence)
|
|
167
|
+
counted.add(expression);
|
|
168
|
+
return logicalSequenceCost(sequence);
|
|
169
|
+
}
|
|
170
|
+
function isUncountedLogicalExpression(node, counted) {
|
|
171
|
+
return isBooleanLogicalExpression(node) && !counted.has(node);
|
|
172
|
+
}
|
|
173
|
+
function isBooleanLogicalExpression(node) {
|
|
174
|
+
return isLogicalExpression(node) && node.operatorToken.kind !== ts.SyntaxKind.QuestionQuestionToken;
|
|
175
|
+
}
|
|
176
|
+
function logicalSequenceCost(sequence) {
|
|
177
|
+
let complexity = 0;
|
|
178
|
+
let previous;
|
|
179
|
+
for (const expression of sequence) {
|
|
180
|
+
const operator = expression.operatorToken.kind;
|
|
181
|
+
if (operator !== previous)
|
|
182
|
+
complexity++;
|
|
183
|
+
previous = operator;
|
|
184
|
+
}
|
|
185
|
+
return complexity;
|
|
186
|
+
}
|
|
187
|
+
function logicalSequence(node) {
|
|
188
|
+
node = unwrapExpression(node);
|
|
189
|
+
if (!isBooleanLogicalExpression(node))
|
|
190
|
+
return [];
|
|
191
|
+
return [...logicalSequence(node.left), node, ...logicalSequence(node.right)];
|
|
192
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/** Report command errors and return the process exit code. */
|
|
2
|
+
export declare function runCommandLine(args: string[], cwd: string): Promise<0 | 1>;
|
|
3
|
+
/** Run a report in the supplied project without changing the process working directory. */
|
|
4
|
+
export declare function runCli(args: string[], cwd: string): Promise<void>;
|
package/dist/command.js
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
import { realpath } from "node:fs/promises";
|
|
2
|
+
import { resolve } from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { parseArgs } from "node:util";
|
|
5
|
+
import { changedSourceFilter } from "./changes.js";
|
|
6
|
+
import { analyzeProject, warnUnknownCoverage } from "./project.js";
|
|
7
|
+
import { compareProject } from "./comparison.js";
|
|
8
|
+
import { loadConfiguration } from "./configuration.js";
|
|
9
|
+
import { readManifest } from "./manifest.js";
|
|
10
|
+
import { writeJson } from "./files.js";
|
|
11
|
+
import { formatCoverage, formatDelta, formatPair, formatScore, formatTable } from "./format.js";
|
|
12
|
+
/** Report command errors and return the process exit code. */
|
|
13
|
+
export async function runCommandLine(args, cwd) {
|
|
14
|
+
try {
|
|
15
|
+
await runCli(args, cwd);
|
|
16
|
+
return 0;
|
|
17
|
+
}
|
|
18
|
+
catch (error) {
|
|
19
|
+
console.error(`ouch4ts: ${errorMessage(error)}`);
|
|
20
|
+
return 1;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
function errorMessage(error) {
|
|
24
|
+
return error instanceof Error ? error.message : String(error);
|
|
25
|
+
}
|
|
26
|
+
function parseOptions(args) {
|
|
27
|
+
return parseArgs({ args, allowPositionals: true, options: {
|
|
28
|
+
help: { type: "boolean", short: "h" },
|
|
29
|
+
version: { type: "boolean" },
|
|
30
|
+
format: { type: "string" },
|
|
31
|
+
project: { type: "string" },
|
|
32
|
+
config: { type: "string" },
|
|
33
|
+
"no-config": { type: "boolean" },
|
|
34
|
+
"output-dir": { type: "string" },
|
|
35
|
+
"use-existing-coverage": { type: "boolean" },
|
|
36
|
+
"source-root": { type: "string", multiple: true },
|
|
37
|
+
exclude: { type: "string", multiple: true },
|
|
38
|
+
lcov: { type: "string" },
|
|
39
|
+
"coverage-command": { type: "string" },
|
|
40
|
+
since: { type: "string" },
|
|
41
|
+
compare: { type: "string" },
|
|
42
|
+
"setup-command": { type: "string" },
|
|
43
|
+
refresh: { type: "boolean" },
|
|
44
|
+
} });
|
|
45
|
+
}
|
|
46
|
+
/** Run a report in the supplied project without changing the process working directory. */
|
|
47
|
+
export async function runCli(args, cwd) {
|
|
48
|
+
const { values, positionals } = parseOptions(args);
|
|
49
|
+
if (values.help) {
|
|
50
|
+
console.log(`Usage: ouch4ts [options] [path-fragment ...]
|
|
51
|
+
|
|
52
|
+
--project <directory> Project to analyze. Default: launching directory
|
|
53
|
+
--config <file> JSON config, relative to launching directory
|
|
54
|
+
--no-config Ignore project-local ouch4ts.config.json
|
|
55
|
+
--source-root <path> Source directory, repeatable. Default: src
|
|
56
|
+
--exclude <glob> Exclude project-relative paths, repeatable. Quote globs.
|
|
57
|
+
--lcov <path> LCOV report. Default: coverage/lcov.info
|
|
58
|
+
--coverage-command <cmd> Shell command. Default: <package-manager> run test:coverage
|
|
59
|
+
--use-existing-coverage Read coverage without running tests or checking freshness
|
|
60
|
+
--since <ref> Show functions changed since the merge base with ref
|
|
61
|
+
--compare <ref> Compare merge-base and HEAD scores in temporary checkouts
|
|
62
|
+
--setup-command <cmd> Comparison setup. Default: detected manager's frozen install
|
|
63
|
+
--refresh Regenerate both comparison reports instead of using cache
|
|
64
|
+
--format <table|json> Stdout format. Default: table
|
|
65
|
+
--output-dir <directory> Report and comparison cache storage. Default: .metrics
|
|
66
|
+
--version Show the package version
|
|
67
|
+
-h, --help Show this help
|
|
68
|
+
|
|
69
|
+
Paths and commands use the selected project. Config overrides defaults; flags override config.
|
|
70
|
+
Repeated flags replace configured lists. Case-sensitive path fragments filter stdout with OR matching.
|
|
71
|
+
File rows sort by cognitive complexity or its delta; function rows sort by OUCH or its delta.
|
|
72
|
+
Complete reports write ouch.json or ouch-comparison.json in the output directory.
|
|
73
|
+
Fresh coverage runs a shell command; comparisons also install dependencies in temporary checkouts.
|
|
74
|
+
Diagnostics and command output use stderr. Failures exit 1; unknown coverage stays null/N/A.`);
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
if (values.version) {
|
|
78
|
+
const manifest = await readManifest(fileURLToPath(new URL("../", import.meta.url)));
|
|
79
|
+
if (typeof manifest.version !== "string")
|
|
80
|
+
throw new Error("Package version is missing");
|
|
81
|
+
console.log(manifest.version);
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
validateReportMode(values);
|
|
85
|
+
const format = reportFormat(values.format);
|
|
86
|
+
const configPath = values.config === undefined ? undefined : resolve(cwd, values.config);
|
|
87
|
+
cwd = await realpath(resolve(cwd, values.project ?? "."));
|
|
88
|
+
const config = await loadConfiguration(cwd, configPath, values["no-config"] ?? false);
|
|
89
|
+
const options = projectOptions(values, cwd, config);
|
|
90
|
+
if (values.compare !== undefined) {
|
|
91
|
+
const report = await compareProject(values.compare, {
|
|
92
|
+
...options, refresh: values.refresh ?? false,
|
|
93
|
+
});
|
|
94
|
+
await writeReport(options.outputDir, "ouch-comparison.json", report);
|
|
95
|
+
const files = report.files.filter(entry => matchesPath(entry.file, positionals));
|
|
96
|
+
const entries = report.entries.filter(entry => matchesPath(entry.file, positionals));
|
|
97
|
+
console.log(format === "json" ? JSON.stringify({ ...report, entries, files })
|
|
98
|
+
: formatFileComparison(files) + "\n\n" + formatComparison(entries));
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
await reportCurrent(options, values.since, positionals, format);
|
|
102
|
+
}
|
|
103
|
+
function reportFormat(value) {
|
|
104
|
+
if (value === undefined || value === "table")
|
|
105
|
+
return "table";
|
|
106
|
+
if (value === "json")
|
|
107
|
+
return "json";
|
|
108
|
+
throw new Error("--format must be table or json");
|
|
109
|
+
}
|
|
110
|
+
async function reportCurrent(options, since, positionals, format) {
|
|
111
|
+
const changes = since === undefined ? undefined : changedSourceFilter(since, options.cwd);
|
|
112
|
+
const report = await analyzeProject(options);
|
|
113
|
+
await writeReport(options.outputDir, "ouch.json", report);
|
|
114
|
+
const entries = report.entries.filter(entry => changes?.matchesFunction(entry) ?? true)
|
|
115
|
+
.filter(entry => matchesPath(entry.file, positionals));
|
|
116
|
+
const files = report.files.filter(entry => changes?.matchesFile(entry.file) ?? true)
|
|
117
|
+
.filter(entry => matchesPath(entry.file, positionals));
|
|
118
|
+
console.log(format === "json" ? JSON.stringify({ entries, files }) : formatFiles(files) + "\n\n" + formatReport(entries));
|
|
119
|
+
warnUnknownCoverage(report.entries);
|
|
120
|
+
}
|
|
121
|
+
function formatFiles(files) {
|
|
122
|
+
const rows = [["File", "CC", "Cog", "Functions"], ...files.map(entry => [
|
|
123
|
+
entry.file, String(entry.complexity), String(entry.cognitive), String(entry.functions),
|
|
124
|
+
])];
|
|
125
|
+
return formatTable("File complexity", rows, 1);
|
|
126
|
+
}
|
|
127
|
+
function formatReport(entries) {
|
|
128
|
+
const rows = [["Function", "File", "CC", "Cog", "Cov%", "CRAP", "OUCH"], ...entries.map(entry => [
|
|
129
|
+
entry.name, `${entry.file}:${entry.line}`, String(entry.complexity), String(entry.cognitive),
|
|
130
|
+
formatCoverage(entry.coverage), formatScore(entry.crap), formatScore(entry.ouch),
|
|
131
|
+
])];
|
|
132
|
+
return formatTable("OUCH Report", rows);
|
|
133
|
+
}
|
|
134
|
+
function formatComparison(entries) {
|
|
135
|
+
const rows = [["Function", "File", "CC base/head", "Cog base/head", "Cov% base/head",
|
|
136
|
+
"CRAP base", "CRAP head", "CRAP delta", "OUCH base", "OUCH head", "Delta", "Status"],
|
|
137
|
+
...entries.map(entry => [entry.name, entry.file,
|
|
138
|
+
formatPair(entry.base?.complexity, entry.head?.complexity), formatPair(entry.base?.cognitive, entry.head?.cognitive),
|
|
139
|
+
`${sideScore(entry.base, "coverage")} / ${sideScore(entry.head, "coverage")}`,
|
|
140
|
+
sideScore(entry.base, "crap"), sideScore(entry.head, "crap"), formatDelta(entry.delta.crap),
|
|
141
|
+
sideScore(entry.base, "ouch"), sideScore(entry.head, "ouch"), formatDelta(entry.delta.ouch), entry.status,
|
|
142
|
+
])];
|
|
143
|
+
return formatTable("OUCH Comparison", rows) + (entries.length === 0 ? "\nNo matching function metric changes." : "");
|
|
144
|
+
}
|
|
145
|
+
function formatFileComparison(entries) {
|
|
146
|
+
const rows = [["File", "CC base/head", "CC delta", "Cog base/head", "Cog delta", "Functions base/head", "Status"],
|
|
147
|
+
...entries.map(entry => [entry.file,
|
|
148
|
+
fileScorePair(entry, "complexity"), formatDelta(entry.delta.complexity),
|
|
149
|
+
fileScorePair(entry, "cognitive"), formatDelta(entry.delta.cognitive),
|
|
150
|
+
fileScorePair(entry, "functions"), entry.status,
|
|
151
|
+
])];
|
|
152
|
+
return formatTable("File complexity comparison", rows, 1);
|
|
153
|
+
}
|
|
154
|
+
function fileScorePair(entry, field) {
|
|
155
|
+
return formatPair(entry.base?.[field], entry.head?.[field]);
|
|
156
|
+
}
|
|
157
|
+
function sideScore(entry, field) {
|
|
158
|
+
if (entry === null)
|
|
159
|
+
return "-";
|
|
160
|
+
return formatScore(entry[field]);
|
|
161
|
+
}
|
|
162
|
+
function validateReportMode(values) {
|
|
163
|
+
validateNonEmptyOptions(values);
|
|
164
|
+
if (values.config !== undefined && values["no-config"]) {
|
|
165
|
+
throw new Error("--config cannot combine with --no-config");
|
|
166
|
+
}
|
|
167
|
+
if (values["coverage-command"] !== undefined && values["use-existing-coverage"]) {
|
|
168
|
+
throw new Error("--coverage-command cannot combine with --use-existing-coverage");
|
|
169
|
+
}
|
|
170
|
+
if (values.compare === undefined)
|
|
171
|
+
return validateCurrentReport(values);
|
|
172
|
+
if (hasCurrentReportOptions(values)) {
|
|
173
|
+
throw new Error("--compare cannot combine with --since or --use-existing-coverage");
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
function validateCurrentReport(values) {
|
|
177
|
+
if (values.refresh)
|
|
178
|
+
throw new Error("--refresh requires --compare");
|
|
179
|
+
if (values["setup-command"] !== undefined)
|
|
180
|
+
throw new Error("--setup-command requires --compare");
|
|
181
|
+
}
|
|
182
|
+
function hasCurrentReportOptions(values) {
|
|
183
|
+
return values.since !== undefined || values["use-existing-coverage"] === true;
|
|
184
|
+
}
|
|
185
|
+
function validateNonEmptyOptions(values) {
|
|
186
|
+
for (const pattern of values.exclude ?? [])
|
|
187
|
+
validateNonEmptyValue("exclude", pattern);
|
|
188
|
+
for (const root of values["source-root"] ?? [])
|
|
189
|
+
validateNonEmptyValue("source-root", root);
|
|
190
|
+
for (const option of ["project", "config", "output-dir", "lcov", "since", "compare", "coverage-command", "setup-command"]) {
|
|
191
|
+
validateNonEmptyValue(option, values[option]);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
function validateNonEmptyValue(option, value) {
|
|
195
|
+
if (value?.trim() === "")
|
|
196
|
+
throw new Error(`--${option} must not be empty`);
|
|
197
|
+
if (value?.includes("\0"))
|
|
198
|
+
throw new Error(`--${option} must not contain NUL characters`);
|
|
199
|
+
}
|
|
200
|
+
function projectOptions(values, cwd, config) {
|
|
201
|
+
return {
|
|
202
|
+
cwd, sourceRoots: values["source-root"] ?? config.sourceRoots ?? ["src"],
|
|
203
|
+
exclude: values.exclude ?? config.exclude ?? [], lcov: values.lcov ?? config.lcov ?? "coverage/lcov.info",
|
|
204
|
+
coverageCommand: values["coverage-command"] ?? config.coverageCommand,
|
|
205
|
+
setupCommand: values["setup-command"] ?? config.setupCommand,
|
|
206
|
+
outputDir: resolve(cwd, values["output-dir"] ?? config.outputDir ?? ".metrics"),
|
|
207
|
+
useExistingCoverage: values["use-existing-coverage"] ?? false,
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
function matchesPath(file, filters) {
|
|
211
|
+
if (filters.length === 0)
|
|
212
|
+
return true;
|
|
213
|
+
return filters.some(filter => file.includes(filter));
|
|
214
|
+
}
|
|
215
|
+
async function writeReport(outputDir, filename, report) {
|
|
216
|
+
await writeJson(resolve(outputDir, filename), report);
|
|
217
|
+
}
|