@swayamkothari/codepulse 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/README.md +240 -2
- package/bin/codepulse.js +6 -0
- package/package.json +60 -4
- package/src/analyzers/complexity/cognitive.js +170 -0
- package/src/analyzers/complexity/cyclomatic.js +96 -0
- package/src/analyzers/complexity/index.js +232 -0
- package/src/analyzers/dependencies/cycle-detector.js +107 -0
- package/src/analyzers/dependencies/graph-builder.js +118 -0
- package/src/analyzers/dependencies/import-extractor.js +85 -0
- package/src/analyzers/dependencies/index.js +152 -0
- package/src/analyzers/duplication/index.js +366 -0
- package/src/analyzers/duplication/normalizer.js +238 -0
- package/src/analyzers/index.js +9 -0
- package/src/analyzers/smells/index.js +213 -0
- package/src/cli/argument-parser.js +45 -0
- package/src/cli/commands/analyze.js +146 -0
- package/src/cli/commands/compare.js +121 -0
- package/src/cli/commands/history.js +91 -0
- package/src/cli/commands/init.js +51 -0
- package/src/cli/commands/rules.js +110 -0
- package/src/config/loader.js +142 -0
- package/src/config/validator.js +130 -0
- package/src/core/analyzer.js +198 -0
- package/src/core/file-filter.js +95 -0
- package/src/core/project-scanner.js +119 -0
- package/src/history/comparison-engine.js +86 -0
- package/src/history/snapshot-manager.js +190 -0
- package/src/index.js +16 -0
- package/src/reporters/html.js +313 -0
- package/src/reporters/json.js +45 -0
- package/src/reporters/terminal.js +197 -0
- package/src/rules/defaults.js +145 -0
- package/src/rules/registry.js +75 -0
- package/src/scoring/score-calculator.js +299 -0
- package/src/scoring/weights.js +53 -0
- package/src/utils/ast-utils.js +173 -0
- package/src/utils/file-utils.js +64 -0
- package/src/utils/logger.js +54 -0
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Code Smell Analyzer
|
|
3
|
+
*
|
|
4
|
+
* Detects:
|
|
5
|
+
* • Large files (too many lines)
|
|
6
|
+
* • Magic numbers (unexplained numeric literals)
|
|
7
|
+
* • Empty catch blocks
|
|
8
|
+
* • Unused variables (scope-aware via Babel's binding analysis)
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { walkAST, getLine, getColumn, countLines } from '../../utils/ast-utils.js';
|
|
12
|
+
import { getRule } from '../../rules/registry.js';
|
|
13
|
+
import { registerDefaultRules } from '../../rules/defaults.js';
|
|
14
|
+
|
|
15
|
+
export const name = 'smells';
|
|
16
|
+
|
|
17
|
+
// ── Large File ─────────────────────────────────────────────────────────────
|
|
18
|
+
|
|
19
|
+
function checkLargeFile(fileResult, threshold, severity) {
|
|
20
|
+
if (fileResult.lines <= threshold) return [];
|
|
21
|
+
return [{
|
|
22
|
+
ruleId: 'smell/large-file',
|
|
23
|
+
severity,
|
|
24
|
+
filePath: fileResult.path,
|
|
25
|
+
line: 1,
|
|
26
|
+
column: 0,
|
|
27
|
+
message: `File has ${fileResult.lines} lines (threshold: ${threshold})`,
|
|
28
|
+
why: 'Large files usually violate the single-responsibility principle — they are harder to navigate, review, and test.',
|
|
29
|
+
suggestion: 'Split this file into focused modules. Group related exports into their own files.',
|
|
30
|
+
}];
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// ── Magic Numbers ──────────────────────────────────────────────────────────
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Contexts in which a numeric literal is NOT a magic number:
|
|
37
|
+
* • Right-hand side of a const/let/var declaration (it's being named)
|
|
38
|
+
* • Default parameter value
|
|
39
|
+
* • Array length checks (n.length === 0 / 1 are acceptable)
|
|
40
|
+
* • Exponent in Math.pow / ** operator (small integers are conventional)
|
|
41
|
+
*/
|
|
42
|
+
function isMagicNumberContext(path) {
|
|
43
|
+
const { parent } = path;
|
|
44
|
+
if (!parent) return true;
|
|
45
|
+
|
|
46
|
+
switch (parent.type) {
|
|
47
|
+
// const TIMEOUT = 5000; — this names the number
|
|
48
|
+
case 'VariableDeclarator':
|
|
49
|
+
return false;
|
|
50
|
+
|
|
51
|
+
// function f(x = 0) — conventional default
|
|
52
|
+
case 'AssignmentPattern':
|
|
53
|
+
return false;
|
|
54
|
+
|
|
55
|
+
// { key: 42 } — object values flagged; object keys are always string-like
|
|
56
|
+
case 'ObjectProperty':
|
|
57
|
+
return parent.key === path.node; // skip if it's the key, flag if value
|
|
58
|
+
|
|
59
|
+
// Array elements ARE flagged — [1, 2, 3] likely magic
|
|
60
|
+
// Switch cases: case 42: — flag these
|
|
61
|
+
default:
|
|
62
|
+
return true;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function checkMagicNumbers(fileResult, ignoreSet, severity) {
|
|
67
|
+
const findings = [];
|
|
68
|
+
|
|
69
|
+
walkAST(fileResult.ast, {
|
|
70
|
+
NumericLiteral(path) {
|
|
71
|
+
const value = path.node.value;
|
|
72
|
+
if (ignoreSet.has(value)) return;
|
|
73
|
+
|
|
74
|
+
if (!isMagicNumberContext(path)) return;
|
|
75
|
+
|
|
76
|
+
// Additional allowances: very simple indices and exponents
|
|
77
|
+
// Skip if inside a unary minus (the actual value is negative — handled by parent)
|
|
78
|
+
if (path.parent?.type === 'UnaryExpression' && path.parent.operator === '-') return;
|
|
79
|
+
|
|
80
|
+
findings.push({
|
|
81
|
+
ruleId: 'smell/magic-numbers',
|
|
82
|
+
severity,
|
|
83
|
+
filePath: fileResult.path,
|
|
84
|
+
line: getLine(path.node),
|
|
85
|
+
column: getColumn(path.node),
|
|
86
|
+
message: `Magic number ${value} — give it a named constant`,
|
|
87
|
+
why: 'Unnamed literals scatter meaning across the codebase. When the value needs to change, you must find every occurrence.',
|
|
88
|
+
suggestion: `Extract to a named constant: \`const VALUE = ${value};\``,
|
|
89
|
+
});
|
|
90
|
+
},
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
return findings;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// ── Empty Catch ────────────────────────────────────────────────────────────
|
|
97
|
+
|
|
98
|
+
function checkEmptyCatch(fileResult, severity) {
|
|
99
|
+
const findings = [];
|
|
100
|
+
|
|
101
|
+
walkAST(fileResult.ast, {
|
|
102
|
+
CatchClause(path) {
|
|
103
|
+
const { body } = path.node;
|
|
104
|
+
|
|
105
|
+
// body.body is the array of statements; empty means no handling at all
|
|
106
|
+
if (!body.body || body.body.length === 0) {
|
|
107
|
+
findings.push({
|
|
108
|
+
ruleId: 'smell/empty-catch',
|
|
109
|
+
severity,
|
|
110
|
+
filePath: fileResult.path,
|
|
111
|
+
line: getLine(path.node),
|
|
112
|
+
column: getColumn(path.node),
|
|
113
|
+
message: 'Empty catch block silently swallows errors',
|
|
114
|
+
why: 'An empty catch makes it impossible to know an error occurred. Silent failures are notoriously hard to debug.',
|
|
115
|
+
suggestion: 'At minimum log the error: `catch (err) { console.error(err); }`. If intentional, add a comment explaining why.',
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
},
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
return findings;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// ── Unused Variables ───────────────────────────────────────────────────────
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Uses Babel traverse's scope analysis to find declared-but-unreferenced bindings.
|
|
128
|
+
*
|
|
129
|
+
* We only report on `let` / `const` / `var` VariableDeclarator nodes whose
|
|
130
|
+
* declared name is a plain Identifier (destructuring is excluded — it's too
|
|
131
|
+
* easy to get false positives there). Names matching the ignore pattern
|
|
132
|
+
* (default: /^_/) are skipped.
|
|
133
|
+
*/
|
|
134
|
+
function checkUnusedVars(fileResult, ignorePattern, severity) {
|
|
135
|
+
const findings = [];
|
|
136
|
+
const re = new RegExp(ignorePattern);
|
|
137
|
+
|
|
138
|
+
walkAST(fileResult.ast, {
|
|
139
|
+
VariableDeclaration(path) {
|
|
140
|
+
for (const declarator of path.node.declarations) {
|
|
141
|
+
// Skip destructuring patterns
|
|
142
|
+
if (declarator.id.type !== 'Identifier') continue;
|
|
143
|
+
|
|
144
|
+
const varName = declarator.id.name;
|
|
145
|
+
|
|
146
|
+
// Respect the ignore-prefix convention
|
|
147
|
+
if (re.test(varName)) continue;
|
|
148
|
+
|
|
149
|
+
const binding = path.scope.getBinding(varName);
|
|
150
|
+
if (!binding) continue;
|
|
151
|
+
|
|
152
|
+
// references: read usages. constantViolations: write-only reassignments.
|
|
153
|
+
// A variable with 0 references and 0 violations is never read.
|
|
154
|
+
if (binding.references === 0 && binding.constantViolations.length === 0) {
|
|
155
|
+
findings.push({
|
|
156
|
+
ruleId: 'smell/unused-vars',
|
|
157
|
+
severity,
|
|
158
|
+
filePath: fileResult.path,
|
|
159
|
+
line: getLine(declarator.id),
|
|
160
|
+
column: getColumn(declarator.id),
|
|
161
|
+
message: `Variable "${varName}" is declared but never used`,
|
|
162
|
+
why: 'Unused variables clutter the code, may indicate incomplete refactoring, and confuse readers who try to understand their purpose.',
|
|
163
|
+
suggestion: `Remove "${varName}", or prefix with "_" if it must remain (e.g. for destructuring).`,
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
},
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
return findings;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// ── Analyzer entry point ───────────────────────────────────────────────────
|
|
174
|
+
|
|
175
|
+
export async function analyze(fileResults, config) {
|
|
176
|
+
registerDefaultRules();
|
|
177
|
+
const findings = [];
|
|
178
|
+
|
|
179
|
+
const largeFileRule = getRule('smell/large-file');
|
|
180
|
+
const magicNumRule = getRule('smell/magic-numbers');
|
|
181
|
+
const emptyCatchRule = getRule('smell/empty-catch');
|
|
182
|
+
const unusedVarsRule = getRule('smell/unused-vars');
|
|
183
|
+
|
|
184
|
+
const largeFileThreshold = config?.thresholds?.fileLength ?? largeFileRule?.defaultOptions?.threshold ?? 500;
|
|
185
|
+
const magicIgnore = new Set(config?.thresholds?.magicNumberIgnore ?? magicNumRule?.defaultOptions?.ignore ?? [0, 1, -1, 2, 100]);
|
|
186
|
+
const unusedVarsPattern = config?.thresholds?.unusedVarsIgnore ?? unusedVarsRule?.defaultOptions?.ignorePattern ?? '^_';
|
|
187
|
+
|
|
188
|
+
for (const fileResult of fileResults) {
|
|
189
|
+
if (!fileResult.ast || fileResult.error) continue;
|
|
190
|
+
|
|
191
|
+
if (largeFileRule?.enabled !== false) {
|
|
192
|
+
findings.push(...checkLargeFile(fileResult, largeFileThreshold, largeFileRule.severity));
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
if (magicNumRule?.enabled !== false) {
|
|
196
|
+
findings.push(...checkMagicNumbers(fileResult, magicIgnore, magicNumRule.severity));
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
if (emptyCatchRule?.enabled !== false) {
|
|
200
|
+
findings.push(...checkEmptyCatch(fileResult, emptyCatchRule.severity));
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
if (unusedVarsRule?.enabled !== false) {
|
|
204
|
+
findings.push(...checkUnusedVars(fileResult, unusedVarsPattern, unusedVarsRule.severity));
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// Attach file-level metrics for the scoring engine
|
|
208
|
+
fileResult.metrics.lines = fileResult.lines;
|
|
209
|
+
fileResult.metrics.smellCount = findings.filter(f => f.filePath === fileResult.path).length;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
return findings;
|
|
213
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { Command } from 'commander';
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { dirname, join } from 'node:path';
|
|
5
|
+
import { setLevel } from '../utils/logger.js';
|
|
6
|
+
|
|
7
|
+
import { registerAnalyzeCommand } from './commands/analyze.js';
|
|
8
|
+
import { registerCompareCommand } from './commands/compare.js';
|
|
9
|
+
import { registerHistoryCommand } from './commands/history.js';
|
|
10
|
+
import { registerInitCommand } from './commands/init.js';
|
|
11
|
+
import { registerRulesCommand } from './commands/rules.js';
|
|
12
|
+
|
|
13
|
+
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
14
|
+
const pkg = JSON.parse(readFileSync(join(__dirname, '../../package.json'), 'utf8'));
|
|
15
|
+
|
|
16
|
+
export function createCLI() {
|
|
17
|
+
const program = new Command();
|
|
18
|
+
|
|
19
|
+
program
|
|
20
|
+
.name('codepulse')
|
|
21
|
+
.description('Intelligent JavaScript code health analyzer')
|
|
22
|
+
.version(pkg.version, '-v, --version', 'Print version number')
|
|
23
|
+
.option('--no-color', 'Disable colored output')
|
|
24
|
+
.option('--verbose', 'Enable verbose logging')
|
|
25
|
+
.hook('preAction', (thisCommand) => {
|
|
26
|
+
if (thisCommand.opts().noColor) {
|
|
27
|
+
process.env.NO_COLOR = '1';
|
|
28
|
+
process.env.FORCE_COLOR = '0';
|
|
29
|
+
}
|
|
30
|
+
if (thisCommand.opts().verbose) {
|
|
31
|
+
setLevel('verbose');
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
registerAnalyzeCommand(program);
|
|
36
|
+
registerCompareCommand(program);
|
|
37
|
+
registerHistoryCommand(program);
|
|
38
|
+
registerInitCommand(program);
|
|
39
|
+
registerRulesCommand(program);
|
|
40
|
+
|
|
41
|
+
// Show help by default if no command is given
|
|
42
|
+
program.addHelpCommand('help [command]', 'Display help for a command');
|
|
43
|
+
|
|
44
|
+
return program;
|
|
45
|
+
}
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { ProjectScanner } from '../../core/project-scanner.js';
|
|
3
|
+
import { Analyzer } from '../../core/analyzer.js';
|
|
4
|
+
import { loadConfig } from '../../config/loader.js';
|
|
5
|
+
import { validateConfig } from '../../config/validator.js';
|
|
6
|
+
import { complexityAnalyzer, smellsAnalyzer, duplicationAnalyzer, dependencyAnalyzer } from '../../analyzers/index.js';
|
|
7
|
+
import * as logger from '../../utils/logger.js';
|
|
8
|
+
import { renderTerminal } from '../../reporters/terminal.js';
|
|
9
|
+
import { renderJson } from '../../reporters/json.js';
|
|
10
|
+
import { renderHtml } from '../../reporters/html.js';
|
|
11
|
+
import { SnapshotManager } from '../../history/snapshot-manager.js';
|
|
12
|
+
|
|
13
|
+
const SEVERITY_ORDER = { critical: 4, high: 3, medium: 2, low: 1 };
|
|
14
|
+
|
|
15
|
+
export function registerAnalyzeCommand(program) {
|
|
16
|
+
program
|
|
17
|
+
.command('analyze')
|
|
18
|
+
.description('Analyze a JavaScript project or directory')
|
|
19
|
+
.argument('[target]', 'Directory or file to analyze', '.')
|
|
20
|
+
.option('-f, --format <format>', 'Output format: terminal | json | html', 'terminal')
|
|
21
|
+
.option('-o, --output <path>', 'Write report to this file path')
|
|
22
|
+
.option('-s, --severity <level>', 'Minimum severity to report: critical|high|medium|low', 'low')
|
|
23
|
+
.option('--save', 'Save a snapshot for historical comparison')
|
|
24
|
+
.option('--label <text>', 'Label for the saved snapshot (requires --save)')
|
|
25
|
+
.option('--config <path>', 'Path to config file (default: ./codepulse.config.js)')
|
|
26
|
+
.option('--ignore <patterns...>', 'Additional ignore glob patterns')
|
|
27
|
+
.option('--fail-on <severity>', 'Exit 1 if any issue at this severity or above is found')
|
|
28
|
+
.option('--max-warnings <number>', 'Exit 1 if total warning count exceeds this number', parseInt)
|
|
29
|
+
.option('--quiet', 'Suppress all output except errors (useful in CI)')
|
|
30
|
+
.action(async (target, options) => {
|
|
31
|
+
if (options.quiet) logger.setLevel('error');
|
|
32
|
+
|
|
33
|
+
try {
|
|
34
|
+
const resolvedTarget = path.resolve(target);
|
|
35
|
+
const config = await loadConfig(options.config);
|
|
36
|
+
|
|
37
|
+
// Merge CLI ignores into config
|
|
38
|
+
if (options.ignore) {
|
|
39
|
+
config.ignore = [...(config.ignore ?? []), ...options.ignore];
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// ── Validate config ────────────────────────────────────────────────
|
|
43
|
+
const { valid, errors: cfgErrors, warnings: cfgWarnings } = validateConfig(config);
|
|
44
|
+
cfgWarnings.forEach(w => logger.warn(`Config: ${w}`));
|
|
45
|
+
if (!valid) {
|
|
46
|
+
cfgErrors.forEach(e => logger.error(`Config error: ${e}`));
|
|
47
|
+
process.exit(2);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// ── Scan ───────────────────────────────────────────────────────────
|
|
51
|
+
const spinner = await _spinner(`Scanning ${resolvedTarget} …`);
|
|
52
|
+
const scanner = new ProjectScanner({
|
|
53
|
+
rootDir: resolvedTarget,
|
|
54
|
+
ignore: config.ignore,
|
|
55
|
+
extensions: config.extensions,
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
let files, skipped;
|
|
59
|
+
try {
|
|
60
|
+
({ files, skipped } = await scanner.scan());
|
|
61
|
+
} catch (err) {
|
|
62
|
+
spinner.fail(err.message);
|
|
63
|
+
process.exit(1);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
spinner.succeed(`Found ${files.length} file${files.length !== 1 ? 's' : ''}`);
|
|
67
|
+
|
|
68
|
+
if (files.length === 0) {
|
|
69
|
+
logger.warn('No JavaScript files found to analyze.');
|
|
70
|
+
process.exit(0);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// ── Analyze ────────────────────────────────────────────────────────
|
|
74
|
+
const analyzeSpinner = await _spinner(`Analyzing ${files.length} files …`);
|
|
75
|
+
const analyzer = new Analyzer({ config, files, rootDir: resolvedTarget });
|
|
76
|
+
|
|
77
|
+
analyzer.registerAnalyzer(complexityAnalyzer);
|
|
78
|
+
analyzer.registerAnalyzer(smellsAnalyzer);
|
|
79
|
+
analyzer.registerAnalyzer(duplicationAnalyzer);
|
|
80
|
+
analyzer.registerAnalyzer(dependencyAnalyzer);
|
|
81
|
+
|
|
82
|
+
const result = await analyzer.analyze();
|
|
83
|
+
analyzeSpinner.succeed(`Analysis complete — ${result.duration}ms`);
|
|
84
|
+
|
|
85
|
+
// ── Report ─────────────────────────────────────────────────────────
|
|
86
|
+
await _report(result, options, config);
|
|
87
|
+
|
|
88
|
+
// ── Save snapshot ──────────────────────────────────────────────────
|
|
89
|
+
if (options.save) {
|
|
90
|
+
const manager = new SnapshotManager(resolvedTarget);
|
|
91
|
+
const snap = manager.save(result, { label: options.label });
|
|
92
|
+
logger.success(`Snapshot saved: ${snap.id}`);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// ── Exit codes ─────────────────────────────────────────────────────
|
|
96
|
+
_handleExitCodes(result, options);
|
|
97
|
+
|
|
98
|
+
} catch (err) {
|
|
99
|
+
logger.error(err.message);
|
|
100
|
+
if (process.env.CODEPULSE_DEBUG) console.error(err.stack);
|
|
101
|
+
process.exit(1);
|
|
102
|
+
}
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
async function _report(result, options, _config) {
|
|
107
|
+
const fmt = options.format ?? 'terminal';
|
|
108
|
+
|
|
109
|
+
switch (fmt) {
|
|
110
|
+
case 'json':
|
|
111
|
+
await renderJson(result, options);
|
|
112
|
+
break;
|
|
113
|
+
case 'html':
|
|
114
|
+
await renderHtml(result, options);
|
|
115
|
+
break;
|
|
116
|
+
default:
|
|
117
|
+
await renderTerminal(result, options);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function _handleExitCodes(result, options) {
|
|
122
|
+
if (options.failOn) {
|
|
123
|
+
const threshold = SEVERITY_ORDER[options.failOn];
|
|
124
|
+
if (threshold !== undefined) {
|
|
125
|
+
const hasFailures = result.issues.some(
|
|
126
|
+
i => (SEVERITY_ORDER[i.severity] ?? 0) >= threshold
|
|
127
|
+
);
|
|
128
|
+
if (hasFailures) {
|
|
129
|
+
logger.error(`Exiting with code 1: issues at severity "${options.failOn}" or above found.`);
|
|
130
|
+
process.exit(1);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
if (options.maxWarnings !== undefined) {
|
|
136
|
+
if (result.issues.length > options.maxWarnings) {
|
|
137
|
+
logger.error(`Exiting with code 1: ${result.issues.length} issues exceed --max-warnings ${options.maxWarnings}.`);
|
|
138
|
+
process.exit(1);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
async function _spinner(text) {
|
|
144
|
+
const { default: ora } = await import('ora');
|
|
145
|
+
return ora({ text, isSilent: process.env.CI === 'true' }).start();
|
|
146
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { SnapshotManager } from '../../history/snapshot-manager.js';
|
|
3
|
+
import { compare } from '../../history/comparison-engine.js';
|
|
4
|
+
import * as logger from '../../utils/logger.js';
|
|
5
|
+
|
|
6
|
+
export function registerCompareCommand(program) {
|
|
7
|
+
program
|
|
8
|
+
.command('compare')
|
|
9
|
+
.description('Compare two snapshots (or latest vs previous)')
|
|
10
|
+
.argument('[target]', 'Project directory (default: .)', '.')
|
|
11
|
+
.argument('[snapshotA]', 'Baseline snapshot ID (default: second-most-recent)')
|
|
12
|
+
.argument('[snapshotB]', 'Current snapshot ID (default: most-recent)')
|
|
13
|
+
.option('--json', 'Output diff as JSON')
|
|
14
|
+
.action(async (target, snapshotA, snapshotB, options) => {
|
|
15
|
+
const { default: chalk } = await import('chalk');
|
|
16
|
+
const rootDir = path.resolve(target);
|
|
17
|
+
const manager = new SnapshotManager(rootDir);
|
|
18
|
+
const all = manager.list(); // most-recent first
|
|
19
|
+
|
|
20
|
+
if (all.length < 2 && !(snapshotA && snapshotB)) {
|
|
21
|
+
logger.warn('Need at least 2 saved snapshots to compare.');
|
|
22
|
+
logger.warn('Run `codepulse analyze . --save` to record snapshots.');
|
|
23
|
+
process.exit(1);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// Resolve snapshot IDs
|
|
27
|
+
const idA = snapshotA ?? all[1]?.id;
|
|
28
|
+
const idB = snapshotB ?? all[0]?.id;
|
|
29
|
+
|
|
30
|
+
const snapA = manager.load(idA);
|
|
31
|
+
const snapB = manager.load(idB);
|
|
32
|
+
|
|
33
|
+
if (!snapA) { logger.error(`Snapshot not found: ${idA}`); process.exit(1); }
|
|
34
|
+
if (!snapB) { logger.error(`Snapshot not found: ${idB}`); process.exit(1); }
|
|
35
|
+
|
|
36
|
+
const diff = compare(snapA, snapB);
|
|
37
|
+
|
|
38
|
+
if (options.json) {
|
|
39
|
+
console.log(JSON.stringify(diff, null, 2));
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
_renderDiff(chalk, diff);
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// ── Terminal renderer ─────────────────────────────────────────────────────────
|
|
48
|
+
|
|
49
|
+
function _renderDiff(chalk, diff) {
|
|
50
|
+
const W = 70;
|
|
51
|
+
const div = chalk.dim('─'.repeat(W));
|
|
52
|
+
|
|
53
|
+
const tsA = new Date(diff.snapshotA.timestamp).toLocaleString();
|
|
54
|
+
const tsB = new Date(diff.snapshotB.timestamp).toLocaleString();
|
|
55
|
+
|
|
56
|
+
console.log('\n' + chalk.bold.cyan('CODEPULSE') + chalk.dim(' — Comparison Report'));
|
|
57
|
+
console.log(div);
|
|
58
|
+
console.log(` ${chalk.dim('Baseline:')} ${chalk.white(tsA)} ${chalk.dim(diff.snapshotA.id)}` +
|
|
59
|
+
(diff.snapshotA.label ? chalk.dim(` "${diff.snapshotA.label}"`) : ''));
|
|
60
|
+
console.log(` ${chalk.dim('Current: ')} ${chalk.white(tsB)} ${chalk.dim(diff.snapshotB.id)}` +
|
|
61
|
+
(diff.snapshotB.label ? chalk.dim(` "${diff.snapshotB.label}"`) : ''));
|
|
62
|
+
console.log(div);
|
|
63
|
+
|
|
64
|
+
// ── Overall ───────────────────────────────────────────────────────────────
|
|
65
|
+
const ov = diff.overall;
|
|
66
|
+
const trendColor = diff.trend === 'improved' ? chalk.green
|
|
67
|
+
: diff.trend === 'regressed' ? chalk.red
|
|
68
|
+
: chalk.gray;
|
|
69
|
+
const trendIcon = diff.trend === 'improved' ? '▲' : diff.trend === 'regressed' ? '▼' : '●';
|
|
70
|
+
|
|
71
|
+
const beforeStr = ov.before !== null ? String(ov.before) : 'n/a';
|
|
72
|
+
const afterStr = ov.after !== null ? String(ov.after) : 'n/a';
|
|
73
|
+
const deltaStr = ov.delta !== null ? _deltaStr(ov.delta) : '—';
|
|
74
|
+
|
|
75
|
+
console.log(`\n ${chalk.bold('Overall Score:')} ${chalk.white(beforeStr)} → ${_scoreColor(chalk, ov.after ?? 0)(afterStr)} ${trendColor(trendIcon + ' ' + deltaStr)} ${trendColor('[' + diff.trend + ']')}`);
|
|
76
|
+
|
|
77
|
+
// ── Breakdown ─────────────────────────────────────────────────────────────
|
|
78
|
+
console.log(`\n ${chalk.bold('Dimension breakdown:')}`);
|
|
79
|
+
const dims = ['complexity', 'duplication', 'maintainability', 'dependencies', 'hygiene'];
|
|
80
|
+
for (const dim of dims) {
|
|
81
|
+
const d = diff.breakdown[dim];
|
|
82
|
+
const lbl = _cap(dim).padEnd(16);
|
|
83
|
+
const bef = d.before !== null ? String(d.before).padStart(3) : ' n/a';
|
|
84
|
+
const aft = d.after !== null ? _scoreColor(chalk, d.after)(String(d.after).padStart(3)) : ' n/a';
|
|
85
|
+
const dlt = d.delta !== null ? _deltaColor(chalk, d.delta)(_deltaStr(d.delta).padStart(5)) : ' —';
|
|
86
|
+
console.log(` ${chalk.dim(lbl)} ${bef} → ${aft} ${dlt}`);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// ── Metrics ───────────────────────────────────────────────────────────────
|
|
90
|
+
console.log(`\n ${chalk.bold('Metrics:')}`);
|
|
91
|
+
const { totalLines, issueCount, filesAnalyzed } = diff.metrics;
|
|
92
|
+
console.log(` ${'Total lines'.padEnd(16)} ${totalLines.before} → ${totalLines.after} ${_deltaColor(chalk, totalLines.delta)(_deltaStr(totalLines.delta))}`);
|
|
93
|
+
console.log(` ${'Issues'.padEnd(16)} ${issueCount.before} → ${issueCount.after} ${_deltaColor(chalk, -issueCount.delta)(_deltaStr(-issueCount.delta))}`);
|
|
94
|
+
console.log(` ${'Files analyzed'.padEnd(16)} ${filesAnalyzed.before} → ${filesAnalyzed.after} ${_deltaColor(chalk, filesAnalyzed.delta)(_deltaStr(filesAnalyzed.delta))}`);
|
|
95
|
+
|
|
96
|
+
console.log('\n' + div + '\n');
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// ── Utils ─────────────────────────────────────────────────────────────────────
|
|
100
|
+
|
|
101
|
+
function _deltaStr(d) {
|
|
102
|
+
if (d === null) return '—';
|
|
103
|
+
if (d > 0) return `+${d}`;
|
|
104
|
+
if (d < 0) return `${d}`;
|
|
105
|
+
return '±0';
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function _deltaColor(chalk, d) {
|
|
109
|
+
if (d === null || d === 0) return chalk.gray;
|
|
110
|
+
return d > 0 ? chalk.green : chalk.red;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function _scoreColor(chalk, score) {
|
|
114
|
+
if (score >= 80) return chalk.green.bold;
|
|
115
|
+
if (score >= 60) return chalk.yellow.bold;
|
|
116
|
+
return chalk.red.bold;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function _cap(str) {
|
|
120
|
+
return str.charAt(0).toUpperCase() + str.slice(1);
|
|
121
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { SnapshotManager } from '../../history/snapshot-manager.js';
|
|
3
|
+
import * as logger from '../../utils/logger.js';
|
|
4
|
+
|
|
5
|
+
export function registerHistoryCommand(program) {
|
|
6
|
+
program
|
|
7
|
+
.command('history')
|
|
8
|
+
.description('Show code health history over time')
|
|
9
|
+
.argument('[target]', 'Project directory (default: .)', '.')
|
|
10
|
+
.option('-n, --limit <n>', 'Number of snapshots to display', parseInt, 10)
|
|
11
|
+
.option('--json', 'Output as JSON')
|
|
12
|
+
.option('--delete <id>', 'Delete a snapshot by ID')
|
|
13
|
+
.action(async (target, options) => {
|
|
14
|
+
const { default: chalk } = await import('chalk');
|
|
15
|
+
const rootDir = path.resolve(target);
|
|
16
|
+
const manager = new SnapshotManager(rootDir);
|
|
17
|
+
|
|
18
|
+
// ── Delete mode ─────────────────────────────────────────────────────
|
|
19
|
+
if (options.delete) {
|
|
20
|
+
const ok = manager.delete(options.delete);
|
|
21
|
+
if (ok) {
|
|
22
|
+
logger.success(`Snapshot deleted: ${options.delete}`);
|
|
23
|
+
} else {
|
|
24
|
+
logger.error(`Snapshot not found: ${options.delete}`);
|
|
25
|
+
process.exit(1);
|
|
26
|
+
}
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// ── List mode ────────────────────────────────────────────────────────
|
|
31
|
+
const all = manager.list();
|
|
32
|
+
|
|
33
|
+
if (all.length === 0) {
|
|
34
|
+
console.log(chalk.yellow('No snapshots found.'));
|
|
35
|
+
console.log(chalk.dim(' Run `codepulse analyze . --save` to record your first snapshot.'));
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const entries = all.slice(0, options.limit ?? 10);
|
|
40
|
+
|
|
41
|
+
if (options.json) {
|
|
42
|
+
console.log(JSON.stringify(entries, null, 2));
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
_renderHistory(chalk, entries, all.length);
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// ── Terminal renderer ─────────────────────────────────────────────────────────
|
|
51
|
+
|
|
52
|
+
function _renderHistory(chalk, entries, totalCount) {
|
|
53
|
+
const W = 70;
|
|
54
|
+
const div = chalk.dim('─'.repeat(W));
|
|
55
|
+
|
|
56
|
+
console.log('\n' + chalk.bold.cyan('CODEPULSE') + chalk.dim(' — Snapshot History'));
|
|
57
|
+
console.log(div);
|
|
58
|
+
console.log(
|
|
59
|
+
` ${'Timestamp'.padEnd(22)}` +
|
|
60
|
+
`${'Score'.padEnd(8)}` +
|
|
61
|
+
`${'Issues'.padEnd(10)}` +
|
|
62
|
+
`${'Files'.padEnd(8)}` +
|
|
63
|
+
`Label`
|
|
64
|
+
);
|
|
65
|
+
console.log(div);
|
|
66
|
+
|
|
67
|
+
for (const entry of entries) {
|
|
68
|
+
const ts = new Date(entry.timestamp).toLocaleString().padEnd(22);
|
|
69
|
+
const score = entry.overall !== null
|
|
70
|
+
? _scoreColor(chalk, entry.overall)(String(entry.overall).padEnd(8))
|
|
71
|
+
: chalk.dim('n/a'.padEnd(8));
|
|
72
|
+
const issues = String(entry.issueCount ?? 0).padEnd(10);
|
|
73
|
+
const files = String(entry.filesAnalyzed ?? 0).padEnd(8);
|
|
74
|
+
const label = entry.label ? chalk.dim(`"${entry.label}"`) : '';
|
|
75
|
+
|
|
76
|
+
console.log(` ${chalk.dim(ts)}${score}${issues}${files}${label}`);
|
|
77
|
+
console.log(chalk.dim(` id: ${entry.id}`));
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
if (totalCount > entries.length) {
|
|
81
|
+
console.log(chalk.dim(`\n Showing ${entries.length} of ${totalCount}. Use --limit N to see more.`));
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
console.log('\n' + div + '\n');
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function _scoreColor(chalk, score) {
|
|
88
|
+
if (score >= 80) return chalk.green.bold;
|
|
89
|
+
if (score >= 60) return chalk.yellow.bold;
|
|
90
|
+
return chalk.red.bold;
|
|
91
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
|
|
4
|
+
const CONFIG_TEMPLATE = `/** @type {import('codepulse').Config} */
|
|
5
|
+
export default {
|
|
6
|
+
// Directories/glob patterns to ignore (extends built-in defaults)
|
|
7
|
+
ignore: [],
|
|
8
|
+
|
|
9
|
+
// File extensions to analyze
|
|
10
|
+
extensions: ['.js', '.mjs', '.cjs', '.jsx'],
|
|
11
|
+
|
|
12
|
+
// Rule configuration
|
|
13
|
+
// Values: 'off' | { severity: 'critical'|'high'|'medium'|'low', options: {...} }
|
|
14
|
+
rules: {
|
|
15
|
+
// 'complexity/cyclomatic': { severity: 'high', options: { threshold: 10 } },
|
|
16
|
+
// 'smell/empty-catch': 'off',
|
|
17
|
+
// 'smell/magic-numbers': { severity: 'low', options: { ignore: [0, 1, -1] } },
|
|
18
|
+
},
|
|
19
|
+
|
|
20
|
+
// Scoring weights (should conceptually sum to 1.0)
|
|
21
|
+
scoring: {
|
|
22
|
+
weights: {
|
|
23
|
+
complexity: 0.30,
|
|
24
|
+
duplication: 0.20,
|
|
25
|
+
maintainability: 0.25,
|
|
26
|
+
dependencies: 0.15,
|
|
27
|
+
hygiene: 0.10,
|
|
28
|
+
},
|
|
29
|
+
},
|
|
30
|
+
};
|
|
31
|
+
`;
|
|
32
|
+
|
|
33
|
+
export function registerInitCommand(program) {
|
|
34
|
+
program
|
|
35
|
+
.command('init')
|
|
36
|
+
.description('Create a codepulse.config.js in the current directory')
|
|
37
|
+
.option('--force', 'Overwrite existing config')
|
|
38
|
+
.action(async (options) => {
|
|
39
|
+
const { default: chalk } = await import('chalk');
|
|
40
|
+
const dest = path.join(process.cwd(), 'codepulse.config.js');
|
|
41
|
+
|
|
42
|
+
if (fs.existsSync(dest) && !options.force) {
|
|
43
|
+
console.log(chalk.yellow(`codepulse.config.js already exists. Use --force to overwrite.`));
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
fs.writeFileSync(dest, CONFIG_TEMPLATE, 'utf8');
|
|
48
|
+
console.log(chalk.green('✔') + ' Created ' + chalk.bold('codepulse.config.js'));
|
|
49
|
+
console.log(chalk.dim(' Edit it to customise rules, thresholds, and ignored paths.'));
|
|
50
|
+
});
|
|
51
|
+
}
|