crap-ts 0.2.0 → 1.0.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/src/cli.js CHANGED
@@ -6,7 +6,6 @@ import { fileURLToPath } from "node:url";
6
6
  import { parseArgs } from "node:util";
7
7
 
8
8
  import { runCrapAudit } from "./crap-runner.js";
9
- import { buildCrapScores } from "./crap-score.js";
10
9
 
11
10
  const helpText = `crap-ts
12
11
 
@@ -14,24 +13,20 @@ Run a focused TypeScript quality audit.
14
13
 
15
14
  Usage:
16
15
  crap-ts score [--coverage-file coverage/unit/coverage-final.json] [--coverage-command "npm run test:coverage"]
17
- crap-ts score --metrics complexity-metrics.json --coverage-file coverage/coverage-summary.json [--max-crap 30]
18
-
19
- Legacy:
20
- crap-ts --metrics complexity-metrics.json --coverage-file coverage/coverage-summary.json
21
16
 
22
17
  Options:
23
18
  --config <path> Config file path. Defaults to .crap-ts.json when present.
24
19
  --coverage-file <path>
25
- Istanbul coverage JSON path.
20
+ Istanbul coverage-final.json path. Repeat to merge several runs.
26
21
  --coverage-command <cmd>
27
22
  Command to generate coverage before scoring.
28
23
  --all Print every analyzed function instead of applying --limit.
29
- --include <text> Only analyze coverage files whose path contains this text.
30
- --limit <n> Number of rows to print for direct CRAP audit. Defaults to 20.
31
- --metrics <path> JSON file with [{ "file", "name", "complexity" }] entries.
24
+ --include <text> Only analyze source files whose path contains this text.
25
+ --exclude <text> Skip source files whose path contains this text.
26
+ --json Print the full JSON report (schema version 1) instead of text.
27
+ --limit <n> Number of rows to print in the text report. Defaults to 20.
32
28
  --min-lines <n> Ignore functions shorter than this. Defaults to 10.
33
- --max <n> Fail direct CRAP audit when any row is above this score. Defaults to 30.
34
- --max-crap <n> Fail CRAP scoring when any row is above this score.
29
+ --max <n> Fail when any function's CRAP score is above this. Defaults to 30.
35
30
  --warn <n> Warn, without failing, when any row is above this score.
36
31
  --report-only Print CRAP report without failing on threshold.
37
32
  --skip-coverage Do not run the coverage command.
@@ -41,30 +36,27 @@ Options:
41
36
  const defaultConfigPath = ".crap-ts.json";
42
37
 
43
38
  export function parseCliArgs(argv, { cwd = process.cwd() } = {}) {
44
- const command = getCommand(argv);
45
- const args = command === "legacy" ? argv : argv.slice(1);
46
- const { positionals, values } = parseArgs({
39
+ const [command, ...args] = argv;
40
+ const { values } = parseArgs({
47
41
  args,
48
- allowPositionals: true,
49
42
  options: {
50
43
  all: { type: "boolean" },
51
44
  config: { type: "string" },
52
- "coverage-file": { type: "string" },
45
+ "coverage-file": { type: "string", multiple: true },
53
46
  "coverage-command": { type: "string" },
47
+ exclude: { type: "string", multiple: true },
54
48
  help: { type: "boolean", short: "h" },
55
49
  include: { type: "string", multiple: true },
50
+ json: { type: "boolean" },
56
51
  limit: { type: "string" },
57
52
  max: { type: "string" },
58
- "max-crap": { type: "string" },
59
- metrics: { type: "string" },
60
53
  "min-lines": { type: "string" },
61
54
  "report-only": { type: "boolean" },
62
55
  "skip-coverage": { type: "boolean" },
63
56
  warn: { type: "string" },
64
57
  },
65
58
  });
66
- const config =
67
- command === "help" || values.help ? {} : readConfig(values.config, cwd);
59
+ const config = values.help ? {} : readConfig(values.config, cwd);
68
60
 
69
61
  return applyDefaults(
70
62
  mergeConfigWithCli(config, {
@@ -72,15 +64,14 @@ export function parseCliArgs(argv, { cwd = process.cwd() } = {}) {
72
64
  all: values.all,
73
65
  configPath: values.config,
74
66
  coverageCommand: values["coverage-command"],
75
- coveragePath: values["coverage-file"],
67
+ coveragePaths: values["coverage-file"],
68
+ excludes: values.exclude,
76
69
  help: values.help,
77
70
  includes: values.include,
71
+ json: values.json,
78
72
  limit: parseOptionalNumber(values.limit, "--limit"),
79
- maxCrap: parseOptionalNumber(values["max-crap"], "--max-crap"),
80
73
  maxScore: parseOptionalNumber(values.max, "--max"),
81
- metricsPath: values.metrics,
82
74
  minLines: parseOptionalNumber(values["min-lines"], "--min-lines"),
83
- paths: positionals,
84
75
  reportOnly: values["report-only"],
85
76
  skipCoverage: values["skip-coverage"],
86
77
  warnScore: parseOptionalNumber(values.warn, "--warn"),
@@ -89,96 +80,40 @@ export function parseCliArgs(argv, { cwd = process.cwd() } = {}) {
89
80
  }
90
81
 
91
82
  export async function main(argv = process.argv.slice(2)) {
92
- const options = parseCliArgs(argv);
83
+ const [command] = argv;
93
84
 
94
- if (options.help || options.command === "help") {
85
+ if (!command || ["help", "--help", "-h"].includes(command)) {
95
86
  console.log(helpText);
96
87
  return 0;
97
88
  }
98
89
 
99
- if (
100
- options.command === "score" ||
101
- options.metricsPath ||
102
- options.coveragePath
103
- ) {
104
- return runScore(options);
105
- }
106
-
107
- if (options.command !== "legacy") {
108
- console.error(`Unknown command: ${options.command}`);
90
+ if (command !== "score") {
91
+ console.error(
92
+ `Unknown command: ${command}. Run \`crap-ts score\`; see \`crap-ts --help\`.`,
93
+ );
109
94
  return 2;
110
95
  }
111
96
 
112
- console.error(
113
- "Usage error: run `crap-ts score --help` for supported commands.",
114
- );
115
- return 2;
116
- }
117
-
118
- async function runScore(options) {
119
- if (!options.metricsPath) {
120
- return runCrapAudit(options);
121
- }
122
-
123
- if (!options.coveragePath) {
124
- console.error("CRAP scoring requires both --metrics and --coverage-file.");
125
- return 2;
126
- }
97
+ let options;
127
98
 
128
- if (
129
- options.maxCrap &&
130
- options.warnScore !== undefined &&
131
- options.warnScore > options.maxCrap
132
- ) {
133
- console.error(
134
- `CRAP warn (${options.warnScore}) must not exceed max-crap (${options.maxCrap}).`,
135
- );
99
+ try {
100
+ options = parseCliArgs(argv);
101
+ } catch (error) {
102
+ console.error(`Usage error: ${error.message}`);
136
103
  return 2;
137
104
  }
138
105
 
139
- const metrics = JSON.parse(readFileSync(options.metricsPath, "utf8"));
140
- const coverageSummary = JSON.parse(
141
- readFileSync(options.coveragePath, "utf8"),
142
- );
143
- const scores = buildCrapScores({ coverageSummary, metrics });
144
- const failingScores = options.maxCrap
145
- ? scores.filter((score) => score.crap > options.maxCrap)
146
- : [];
147
- const warningScores =
148
- options.warnScore === undefined
149
- ? []
150
- : scores.filter(
151
- (score) =>
152
- score.crap > options.warnScore &&
153
- !(options.maxCrap && score.crap > options.maxCrap),
154
- );
155
-
156
- console.log(JSON.stringify(scores, null, 2));
157
-
158
- if (warningScores.length > 0) {
159
- console.error(
160
- `CRAP warning: ${warningScores.length} row(s) above ${options.warnScore}.`,
161
- );
106
+ if (options.help) {
107
+ console.log(helpText);
108
+ return 0;
162
109
  }
163
110
 
164
- if (failingScores.length > 0) {
165
- console.error(
166
- `CRAP threshold failed: ${failingScores.length} row(s) exceeded ${options.maxCrap}.`,
167
- );
111
+ try {
112
+ return await runCrapAudit(options);
113
+ } catch (error) {
114
+ console.error(`Error: ${error.message}`);
168
115
  return 1;
169
116
  }
170
-
171
- return 0;
172
- }
173
-
174
- function getCommand(argv) {
175
- const firstArg = argv[0];
176
-
177
- if (firstArg === "score" || firstArg === "help") {
178
- return firstArg;
179
- }
180
-
181
- return "legacy";
182
117
  }
183
118
 
184
119
  function parseOptionalNumber(value, label) {
@@ -221,19 +156,54 @@ function mergeConfigWithCli(config, cliOptions) {
221
156
  };
222
157
  }
223
158
 
159
+ const configKeys = new Set([
160
+ "all",
161
+ "coverageCommand",
162
+ "coverageFile",
163
+ "exclude",
164
+ "include",
165
+ "json",
166
+ "limit",
167
+ "max",
168
+ "minLines",
169
+ "reportOnly",
170
+ "skipCoverage",
171
+ "warn",
172
+ ]);
173
+
224
174
  function normalizeConfig(config) {
175
+ if (!config || typeof config !== "object" || Array.isArray(config)) {
176
+ throw new TypeError(`${defaultConfigPath} must contain a JSON object.`);
177
+ }
178
+
179
+ const unknownKeys = Object.keys(config).filter((key) => !configKeys.has(key));
180
+
181
+ if (unknownKeys.length > 0) {
182
+ throw new TypeError(
183
+ `Unknown ${defaultConfigPath} key(s): ${unknownKeys.join(", ")}.`,
184
+ );
185
+ }
186
+
225
187
  return stripUndefined({
226
- all: config.all,
227
- coverageCommand: config.coverageCommand,
228
- coveragePath: config.coverageFile,
188
+ all: parseConfigType(config.all, "all", "boolean"),
189
+ coverageCommand: parseConfigType(
190
+ config.coverageCommand,
191
+ "coverageCommand",
192
+ "string",
193
+ ),
194
+ coveragePaths: normalizeConfigList(config.coverageFile, "coverageFile"),
195
+ excludes: normalizeConfigList(config.exclude, "exclude"),
229
196
  includes: normalizeConfigList(config.include, "include"),
197
+ json: parseConfigType(config.json, "json", "boolean"),
230
198
  limit: parseConfigNumber(config.limit, "limit"),
231
- maxCrap: parseConfigNumber(config.maxCrap, "maxCrap"),
232
199
  maxScore: parseConfigNumber(config.max, "max"),
233
- metricsPath: config.metrics,
234
200
  minLines: parseConfigNumber(config.minLines, "minLines"),
235
- reportOnly: config.reportOnly,
236
- skipCoverage: config.skipCoverage,
201
+ reportOnly: parseConfigType(config.reportOnly, "reportOnly", "boolean"),
202
+ skipCoverage: parseConfigType(
203
+ config.skipCoverage,
204
+ "skipCoverage",
205
+ "boolean",
206
+ ),
237
207
  warnScore: parseConfigNumber(config.warn, "warn"),
238
208
  });
239
209
  }
@@ -252,6 +222,14 @@ function parseConfigNumber(value, label) {
252
222
  return value;
253
223
  }
254
224
 
225
+ function parseConfigType(value, label, type) {
226
+ if (value !== undefined && typeof value !== type) {
227
+ throw new TypeError(`${label} must be a ${type} in ${defaultConfigPath}.`);
228
+ }
229
+
230
+ return value;
231
+ }
232
+
255
233
  function normalizeConfigList(value, label) {
256
234
  if (value === undefined) {
257
235
  return undefined;
@@ -275,7 +253,9 @@ function applyDefaults(options) {
275
253
  ...options,
276
254
  all: options.all ?? false,
277
255
  help: options.help ?? false,
256
+ excludes: options.excludes ?? [],
278
257
  includes: options.includes ?? [],
258
+ json: options.json ?? false,
279
259
  reportOnly: options.reportOnly ?? false,
280
260
  skipCoverage: options.skipCoverage ?? false,
281
261
  };
@@ -1,33 +1,54 @@
1
+ interface SourcePosition {
2
+ line: number;
3
+ column: number;
4
+ }
5
+
6
+ interface SourceRange {
7
+ start: SourcePosition;
8
+ end: { line: number; column: number | null };
9
+ }
10
+
11
+ /** One file's entry from an Istanbul `coverage-final.json`. Branch data is ignored. */
12
+ export interface FileCoverage {
13
+ statementMap: Record<string, SourceRange>;
14
+ s: Record<string, number>;
15
+ fnMap: Record<string, { loc: SourceRange }>;
16
+ f: Record<string, number>;
17
+ }
18
+
1
19
  export interface FunctionRisk {
2
- complexity: number;
3
- coveragePercent: number;
4
- crapScore: number;
5
- endLine: number;
6
20
  filePath: string;
7
- lineCount: number;
8
21
  name: string;
22
+ /** One-based line of the function's first token. */
9
23
  startLine: number;
10
- }
11
-
12
- export interface CoverageFunction {
13
- coveragePercent: number;
14
- declarationLine: number;
24
+ /** One-based column of the function's first token. */
25
+ startColumn: number;
15
26
  endLine: number;
16
- startLine: number;
27
+ lineCount: number;
28
+ complexity: number;
29
+ /** Percentage in [0, 100]. */
30
+ coveragePercent: number;
31
+ /** Statements whose start lies in this function and not in a nested one. */
32
+ statements: number;
33
+ coveredStatements: number;
34
+ /** `statements`: owned statement counters; `function`: the function's own counter (no owned statements); `ignored`: no counter, under a coverage ignore comment; `missing`: no counter and no ignore comment (no coverage entry, or added after the coverage run). */
35
+ evidence: "statements" | "function" | "ignored" | "missing";
36
+ crapScore: number;
17
37
  }
18
38
 
19
- export function extractCoverageFunctions(
20
- coverageJson: Record<string, unknown>,
21
- ): Map<string, CoverageFunction[]>;
22
-
39
+ /**
40
+ * Score every function with a body in one source file.
41
+ * A function without counters (or without `coverage`) reports 0% coverage and
42
+ * `evidence: "missing"`, or `"ignored"` when a coverage ignore comment covers it.
43
+ */
23
44
  export function analyzeFileRisk(input: {
24
- coverageFunctions: CoverageFunction[];
45
+ coverage?: FileCoverage;
25
46
  filePath: string;
26
- minLines: number;
47
+ /** Drop functions shorter than this many lines. Defaults to 1. */
48
+ minLines?: number;
27
49
  sourceFilePath?: string;
28
50
  sourceText: string;
29
51
  }): Promise<FunctionRisk[]>;
30
52
 
31
- export function formatRiskLine(risk: FunctionRisk): string;
32
-
53
+ /** 1 plus one per decision point in `node`, excluding nested functions. */
33
54
  export function calculateCyclomaticComplexity(node: unknown): number;