-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlint.ts
More file actions
373 lines (338 loc) · 11.3 KB
/
Copy pathlint.ts
File metadata and controls
373 lines (338 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
import { fileURLToPath } from 'node:url';
import { readFile, rm, writeFile } from 'node:fs/promises';
import { parse } from '@bomb.sh/args';
import { x } from 'tinyexec';
import type { JSONReport as KnipJSONReport } from 'knip';
import type { CommandContext } from '../context.ts';
import { getPublicSurface } from '../surface.ts';
import { local } from '../utils.ts';
const oxlintConfig = fileURLToPath(new URL('../../oxlintrc.json', import.meta.url));
/**
* Rules that only apply to the public API surface (see `surface.ts`).
* Moved from the global ruleset into `overrides` at runtime.
*/
const SURFACE_RULES = [
'bombshell-dev/exported-function-async',
'bombshell-dev/require-export-jsdoc',
];
/**
* Generate the effective oxlint config for the project at `cwd`.
*
* Surface-scoped rules are lifted out of the shared config's global ruleset
* and re-applied via `overrides` limited to the package's public API surface,
* so internal modules aren't held to public-API conventions. Written into the
* project root because oxlint resolves `overrides.files` relative to the
* config location; deleted after the run.
*/
async function withEffectiveConfig<T>(run: (configPath: string) => Promise<T>): Promise<T> {
const cwd = process.cwd();
const base = JSON.parse(await readFile(oxlintConfig, 'utf-8'));
delete base.$schema;
// jsPlugins paths are relative to the shared config — make them absolute
// so the generated copy can live anywhere.
if (Array.isArray(base.jsPlugins)) {
base.jsPlugins = base.jsPlugins.map((plugin: string) =>
fileURLToPath(new URL(plugin, new URL('../../oxlintrc.json', import.meta.url))),
);
}
const surface = await getPublicSurface(new URL(`file://${cwd}/`));
const scoped: Record<string, unknown> = {};
for (const rule of SURFACE_RULES) {
if (base.rules?.[rule] !== undefined) {
scoped[rule] = base.rules[rule];
delete base.rules[rule];
}
}
if (surface.length > 0 && Object.keys(scoped).length > 0) {
base.overrides = [...(base.overrides ?? []), { files: surface, rules: scoped }];
}
const configPath = `${cwd}/.bsh.oxlintrc.json`;
await writeFile(configPath, JSON.stringify(base, null, 2));
try {
return await run(configPath);
} finally {
await rm(configPath, { force: true });
}
}
// -- Types --
interface Violation {
tool: 'oxlint' | 'publint' | 'knip' | 'tsc';
level: 'error' | 'warning' | 'suggestion';
code: string;
message: string;
file?: string;
line?: number;
column?: number;
}
// -- Tool Runners --
export async function runOxlint(targets: string[], fix?: boolean): Promise<Violation[]> {
return withEffectiveConfig(async (config) => {
const args = ['-c', config, '--format=json', ...targets];
if (fix) args.push('--fix');
const result = await x(local('oxlint'), args, { throwOnError: false });
try {
const json = JSON.parse(result.stdout);
return (json.diagnostics ?? []).map(
(d: {
message: string;
code: string;
severity: string;
filename?: string;
labels?: Array<{ span?: { line?: number; column?: number } }>;
}) => ({
tool: 'oxlint' as const,
level: d.severity === 'error' ? 'error' : 'warning',
code: d.code ?? 'unknown',
message: d.message,
file: d.filename,
line: d.labels?.[0]?.span?.line,
column: d.labels?.[0]?.span?.column,
}),
);
} catch {
// in some cases, failures or no-ops do not produce valid JSON
// fallback to raw output rather than throwing an error
console.info(result.stdout);
return [];
}
});
}
/**
* Mechanically fix knip-reported issues. Dependency hygiene (removing unused
* deps from package.json) always runs with `--fix`; dead-code fixes (unused
* exports/types) only run in `--strict` mode, matching the report tiers.
* Unused files are never deleted automatically.
*/
export async function runKnipFix(strict?: boolean): Promise<void> {
const types = strict ? 'dependencies,exports,types' : 'dependencies';
await x(local('knip'), ['--fix', '--fix-type', types, '--no-progress'], {
throwOnError: false,
});
}
/**
* Knip dead-code issue kinds (unused exports/types/files) fire constantly
* mid-implementation — an export is "unused" until its consumer exists.
* They only carry signal as a commit-time gate, so they require `--strict`.
* Dependency hygiene issues are stable and always reported.
*/
export async function runKnip(options?: { strict?: boolean }): Promise<Violation[]> {
const args = ['--no-progress', '--reporter', 'json'];
const result = await x(local('knip'), args, { throwOnError: false });
if (!result.stdout.trim()) return [];
const json: KnipJSONReport = JSON.parse(result.stdout);
const violations: Violation[] = [];
for (const issue of json.issues) {
for (const dep of issue.dependencies ?? []) {
violations.push({
tool: 'knip',
level: 'warning',
code: 'unused-dependency',
message: `Unused dependency '${dep.name}'`,
file: issue.file,
line: dep.line,
column: dep.col,
});
}
for (const dep of issue.devDependencies ?? []) {
violations.push({
tool: 'knip',
level: 'warning',
code: 'unused-devDependency',
message: `Unused devDependency '${dep.name}'`,
file: issue.file,
line: dep.line,
column: dep.col,
});
}
if (!options?.strict) continue;
for (const exp of issue.exports ?? []) {
violations.push({
tool: 'knip',
level: 'warning',
code: 'unused-export',
message: `Unused export '${exp.name}'`,
file: issue.file,
line: exp.line,
column: exp.col,
});
}
for (const t of issue.types ?? []) {
violations.push({
tool: 'knip',
level: 'warning',
code: 'unused-type',
message: `Unused type '${t.name}'`,
file: issue.file,
line: t.line,
column: t.col,
});
}
for (const file of issue.files ?? []) {
violations.push({
tool: 'knip',
level: 'warning',
code: 'unused-file',
message: `Unused file`,
file: issue.file,
line: file.line,
column: file.col,
});
}
}
return violations;
}
async function runTypeScript(targets: string[]): Promise<Violation[]> {
// Always run in project mode: passing files on the command line makes
// tsgo skip the tsconfig (TS5112). Explicit targets filter the report
// after the fact instead.
const result = await x(local('tsgo'), ['--noEmit', '--pretty', 'false'], {
throwOnError: false,
});
const output = result.stdout + result.stderr;
if (!output.trim()) return [];
const violations: Violation[] = [];
const re = /^(.+)\((\d+),(\d+)\): (error|warning) (TS\d+): (.+)$/gm;
let match: RegExpExecArray | null;
while ((match = re.exec(output)) !== null) {
violations.push({
tool: 'tsc',
level: match[4] === 'error' ? 'error' : 'warning',
code: match[5]!,
message: match[6]!,
file: match[1]!,
line: Number(match[2]),
column: Number(match[3]),
});
}
if (targets.length === 0) return violations;
const prefixes = targets.map((t) => t.replace(/^\.\//, ''));
return violations.filter((v) => v.file && prefixes.some((p) => v.file!.startsWith(p)));
}
// -- Output --
const colors = {
error: '\x1b[31m',
warning: '\x1b[33m',
suggestion: '\x1b[34m',
dim: '\x1b[2m',
reset: '\x1b[0m',
};
function printViolation(v: Violation) {
const loc = v.line != null ? ` ${v.line}:${v.column ?? 0}` : ' -';
const color = colors[v.level];
const tag = `${v.tool}/${v.code}`;
console.log(
`${colors.dim}${loc.padEnd(10)}${colors.reset}${color}${v.level.padEnd(12)}${colors.reset}${v.message} ${colors.dim}${tag}${colors.reset}`,
);
}
function countByLevel(violations: Violation[]) {
const counts = { error: 0, warning: 0, suggestion: 0 };
for (const v of violations) counts[v.level]++;
return counts;
}
function printSummary(violations: Violation[]) {
const counts = countByLevel(violations);
const parts = [];
if (counts.error)
parts.push(`${colors.error}${counts.error} error${counts.error > 1 ? 's' : ''}${colors.reset}`);
if (counts.warning)
parts.push(
`${colors.warning}${counts.warning} warning${counts.warning > 1 ? 's' : ''}${colors.reset}`,
);
if (counts.suggestion)
parts.push(
`${colors.suggestion}${counts.suggestion} suggestion${counts.suggestion > 1 ? 's' : ''}${colors.reset}`,
);
console.log(parts.length > 0 ? `\n${parts.join(', ')}` : '\nNo issues found.');
}
/**
* Print violations grouped by file. Errors are always shown in full.
* Warnings collapse to a per-rule count unless `warnings` is set — they
* don't affect the exit code, so a wall of them buries actual failures.
*/
export function printViolations(violations: Violation[], options?: { warnings?: boolean }) {
const showWarnings = options?.warnings ?? false;
const visible = showWarnings ? violations : violations.filter((v) => v.level === 'error');
const grouped = new Map<string, Violation[]>();
for (const v of visible) {
const key = v.file ?? '(project)';
if (!grouped.has(key)) grouped.set(key, []);
grouped.get(key)!.push(v);
}
for (const [file, items] of grouped) {
console.log(`\n${file}`);
for (const v of items) printViolation(v);
}
if (!showWarnings) {
const hidden = violations.filter((v) => v.level !== 'error');
if (hidden.length > 0) {
const byRule = new Map<string, number>();
for (const v of hidden) {
const tag = `${v.tool}/${v.code}`;
byRule.set(tag, (byRule.get(tag) ?? 0) + 1);
}
console.log(
`\n${colors.dim}${hidden.length} warning${hidden.length > 1 ? 's' : ''} hidden (run with --warnings to show):${colors.reset}`,
);
for (const [tag, count] of [...byRule].sort((a, b) => b[1] - a[1])) {
console.log(`${colors.dim} ${count} × ${tag}${colors.reset}`);
}
}
}
printSummary(violations);
}
/** Machine-readable report for agents and CI. */
export function printJson(violations: Violation[]) {
console.log(JSON.stringify({ summary: countByLevel(violations), violations }, null, 2));
}
// -- Main --
async function collectViolations(
targets: string[],
options?: { strict?: boolean },
): Promise<Violation[]> {
// oxlint honors targets (default: project-wide); tsgo runs in project
// mode unless the user explicitly narrowed the target set.
const explicit = targets.length > 0;
const results = await Promise.allSettled([
runOxlint(explicit ? targets : ['.']),
runKnip({ strict: options?.strict }),
runTypeScript(explicit ? targets : []),
]);
const violations: Violation[] = [];
for (const result of results) {
if (result.status === 'fulfilled') {
violations.push(...result.value);
} else {
console.error(result.reason);
}
}
return violations;
}
export async function lint(ctx: CommandContext) {
const args = parse(ctx.args, {
boolean: ['fix', 'strict', 'warnings'],
string: ['format'],
});
const targets = args._.map(String);
const json = args.format === 'json';
const print = (violations: Violation[]) =>
json ? printJson(violations) : printViolations(violations, { warnings: args.warnings });
if (args.fix) {
await runOxlint(targets.length > 0 ? targets : ['.'], true);
await runKnipFix(args.strict);
// Report remaining
const remaining = await collectViolations(targets, { strict: args.strict });
if (remaining.length > 0) {
print(remaining);
if (remaining.some((v) => v.level === 'error')) process.exit(1);
return;
}
if (!json) console.log('No issues found.');
return;
}
// Default: report only
const violations = await collectViolations(targets, { strict: args.strict });
print(violations);
if (violations.some((v) => v.level === 'error')) {
process.exit(1);
}
}