@yuu1111/comment-check 1.0.0 → 2.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/README.ja.md ADDED
@@ -0,0 +1,49 @@
1
+ [English](README.md)
2
+
3
+ # @yuu1111/comment-check
4
+
5
+ baselineを持つ小さなcomment検査 抑制commentとplaceholder commentの増殖を止める
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ bun add -D @yuu1111/comment-check
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ 現在の検出を一度baselineへ記録し、新しく出たものだけを失敗にする
16
+
17
+ ```bash
18
+ comment-check --update-baseline .
19
+ comment-check .
20
+ ```
21
+
22
+ ```
23
+ src/queue.ts:18:2 undocumented-directive TypeScript directive needs a description
24
+ Checked 42 files: 1 new, 0 resolved, 3 baselined
25
+ ```
26
+
27
+ ## Rules
28
+
29
+ | Rule | 検出対象 |
30
+ |------|---------|
31
+ | `broad-suppression` | `biome-ignore-all`、`@ts-nocheck`、ruleを書いていない `eslint-disable` |
32
+ | `undocumented-directive` | 説明の無い `@ts-ignore` と `@ts-expect-error` |
33
+ | `placeholder-comment` | `TODO`、`FIXME`、`XXX`、`HACK` |
34
+ | `separator-comment` | 記号だけで作った装飾comment |
35
+
36
+ ## Options
37
+
38
+ | Option | Description |
39
+ |--------|-------------|
40
+ | `--baseline <path>` | 読み書きするbaseline file(既定は `comment-baseline.json`) |
41
+ | `--ignore <path>` | 検査から外すpath 複数指定できる |
42
+ | `--update-baseline` | baselineを現在の検出で置き換える |
43
+ | `--json` | 新規と解消済みの検出をJSONで出力する |
44
+
45
+ ## Notes
46
+
47
+ 生成物のディレクトリなどProjectが持つpathは `--ignore` で検査から外す 例えば `--ignore src/generated`
48
+
49
+ baselineはrule、file、comment本文をキーにするため、行が動いてもそのcommentを新規とは報告しない Biomeは `biome-ignore` の理由と未使用の抑制を既に扱うため、このcheckerはBiomeが読まないcommentの細部だけを担当する
package/README.md CHANGED
@@ -1,3 +1,5 @@
1
+ [日本語](README.ja.md)
2
+
1
3
  # @yuu1111/comment-check
2
4
 
3
5
  Small comment checker with a baseline, used to keep suppressions and placeholder
package/dist/cli.js ADDED
@@ -0,0 +1,586 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+
4
+ // src/scan.ts
5
+ import { readFileSync } from "fs";
6
+ import { relative as relative2 } from "path";
7
+
8
+ // ../shared/src/files.ts
9
+ import { readdirSync, statSync } from "fs";
10
+ import { extname, join, relative, resolve } from "path";
11
+ var IGNORED_DIRECTORIES = new Set([
12
+ "build",
13
+ "coverage",
14
+ "dist",
15
+ "node_modules",
16
+ "out",
17
+ "vendor"
18
+ ]);
19
+ function normalizePath(path) {
20
+ return path.split("\\").join("/").replace(/^\.\//, "").replace(/\/+$/, "");
21
+ }
22
+ function isIgnored(path, ignores) {
23
+ return ignores.some((ignore) => path === ignore || path.startsWith(`${ignore}/`));
24
+ }
25
+ function walk(directory, extensions, files) {
26
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
27
+ if (entry.name.startsWith(".")) {
28
+ continue;
29
+ }
30
+ const path = join(directory, entry.name);
31
+ if (entry.isDirectory()) {
32
+ if (!IGNORED_DIRECTORIES.has(entry.name)) {
33
+ walk(path, extensions, files);
34
+ }
35
+ continue;
36
+ }
37
+ if (entry.isFile() && extensions.has(extname(entry.name))) {
38
+ files.add(path);
39
+ }
40
+ }
41
+ }
42
+ function collectFiles(targets, options) {
43
+ const cwd = options.cwd ?? process.cwd();
44
+ const ignores = options.ignores ?? [];
45
+ const files = new Set;
46
+ for (const target of targets) {
47
+ const absolute = resolve(cwd, target);
48
+ let stats;
49
+ try {
50
+ stats = statSync(absolute);
51
+ } catch {
52
+ continue;
53
+ }
54
+ if (stats.isFile()) {
55
+ if (options.extensions.has(extname(absolute)) && !isIgnored(normalizePath(target), ignores)) {
56
+ files.add(absolute);
57
+ }
58
+ continue;
59
+ }
60
+ walk(absolute, options.extensions, files);
61
+ }
62
+ return [...files].filter((file) => !isIgnored(normalizePath(relative(cwd, file)), ignores)).sort();
63
+ }
64
+
65
+ // ../shared/src/findings.ts
66
+ function compareFindings(left, right) {
67
+ if (left.file !== right.file) {
68
+ return left.file < right.file ? -1 : 1;
69
+ }
70
+ if (left.line !== right.line) {
71
+ return left.line - right.line;
72
+ }
73
+ return left.column - right.column;
74
+ }
75
+ function formatLocation(finding) {
76
+ return `${finding.file}:${finding.line}:${finding.column}`;
77
+ }
78
+
79
+ // src/comments.ts
80
+ var REGEX_PRECEDING_CHARACTERS = new Set("(,=:[!&|?{};".split(""));
81
+ var REGEX_PRECEDING_KEYWORDS = new Set([
82
+ "await",
83
+ "case",
84
+ "delete",
85
+ "do",
86
+ "else",
87
+ "in",
88
+ "instanceof",
89
+ "new",
90
+ "of",
91
+ "return",
92
+ "throw",
93
+ "typeof",
94
+ "void",
95
+ "yield"
96
+ ]);
97
+ function isIdentifierCharacter(character) {
98
+ return /[A-Za-z0-9_$]/.test(character);
99
+ }
100
+ function skipString(source, start, quote) {
101
+ let index = start + 1;
102
+ while (index < source.length) {
103
+ const character = source[index] ?? "";
104
+ if (character === "\\") {
105
+ index += 2;
106
+ continue;
107
+ }
108
+ if (character === quote) {
109
+ return index + 1;
110
+ }
111
+ if (character === `
112
+ `) {
113
+ return index;
114
+ }
115
+ index += 1;
116
+ }
117
+ return index;
118
+ }
119
+ function isRegexStart(source, index) {
120
+ let previous = index - 1;
121
+ while (previous >= 0 && /\s/.test(source[previous] ?? "")) {
122
+ previous -= 1;
123
+ }
124
+ if (previous < 0) {
125
+ return true;
126
+ }
127
+ const character = source[previous] ?? "";
128
+ if (REGEX_PRECEDING_CHARACTERS.has(character)) {
129
+ return true;
130
+ }
131
+ if (!isIdentifierCharacter(character)) {
132
+ return false;
133
+ }
134
+ let wordStart = previous;
135
+ while (wordStart >= 0 && isIdentifierCharacter(source[wordStart] ?? "")) {
136
+ wordStart -= 1;
137
+ }
138
+ return REGEX_PRECEDING_KEYWORDS.has(source.slice(wordStart + 1, previous + 1));
139
+ }
140
+ function skipRegex(source, start) {
141
+ let index = start + 1;
142
+ let inClass = false;
143
+ while (index < source.length) {
144
+ const character = source[index] ?? "";
145
+ if (character === "\\") {
146
+ index += 2;
147
+ continue;
148
+ }
149
+ if (character === `
150
+ `) {
151
+ return start;
152
+ }
153
+ if (inClass) {
154
+ inClass = character !== "]";
155
+ index += 1;
156
+ continue;
157
+ }
158
+ if (character === "[") {
159
+ inClass = true;
160
+ index += 1;
161
+ continue;
162
+ }
163
+ if (character === "/") {
164
+ return index + 1;
165
+ }
166
+ index += 1;
167
+ }
168
+ return start;
169
+ }
170
+ function currentMode(state) {
171
+ return state.modes[state.modes.length - 1] ?? "code";
172
+ }
173
+ function stepComment(state, source) {
174
+ const character = source[state.index] ?? "";
175
+ const next = source[state.index + 1] ?? "";
176
+ if (character !== "/" || next !== "/" && next !== "*") {
177
+ return false;
178
+ }
179
+ if (next === "/") {
180
+ const newline = source.indexOf(`
181
+ `, state.index);
182
+ const stop2 = newline === -1 ? source.length : newline;
183
+ state.comments.push({
184
+ end: stop2,
185
+ kind: "line",
186
+ start: state.index,
187
+ text: source.slice(state.index + 2, stop2)
188
+ });
189
+ state.index = stop2;
190
+ return true;
191
+ }
192
+ const close = source.indexOf("*/", state.index + 2);
193
+ const stop = close === -1 ? source.length : close + 2;
194
+ state.comments.push({
195
+ end: stop,
196
+ kind: "block",
197
+ start: state.index,
198
+ text: source.slice(state.index + 2, Math.max(state.index + 2, stop - 2))
199
+ });
200
+ state.index = stop;
201
+ return true;
202
+ }
203
+ function stepString(state, source) {
204
+ const character = source[state.index] ?? "";
205
+ if (character !== "'" && character !== '"') {
206
+ return false;
207
+ }
208
+ state.index = skipString(source, state.index, character);
209
+ return true;
210
+ }
211
+ function stepTemplateStart(state, source) {
212
+ if (source[state.index] !== "`") {
213
+ return false;
214
+ }
215
+ state.modes.push("template");
216
+ state.index += 1;
217
+ return true;
218
+ }
219
+ function stepRegex(state, source) {
220
+ if (source[state.index] !== "/" || !isRegexStart(source, state.index)) {
221
+ return false;
222
+ }
223
+ const stop = skipRegex(source, state.index);
224
+ if (stop <= state.index) {
225
+ return false;
226
+ }
227
+ state.index = stop;
228
+ return true;
229
+ }
230
+ function stepTemplate(state, source) {
231
+ const character = source[state.index] ?? "";
232
+ if (character === "\\") {
233
+ state.index += 2;
234
+ return;
235
+ }
236
+ if (character === "`") {
237
+ state.modes.pop();
238
+ state.index += 1;
239
+ return;
240
+ }
241
+ if (character === "$" && source[state.index + 1] === "{") {
242
+ state.modes.push("expression");
243
+ state.braces.push(1);
244
+ state.index += 2;
245
+ return;
246
+ }
247
+ state.index += 1;
248
+ }
249
+ function stepExpression(state, source) {
250
+ const character = source[state.index] ?? "";
251
+ const depth = state.braces[state.braces.length - 1] ?? 0;
252
+ if (character === "{") {
253
+ state.braces[state.braces.length - 1] = depth + 1;
254
+ } else if (character === "}") {
255
+ state.braces[state.braces.length - 1] = depth - 1;
256
+ if (depth - 1 === 0) {
257
+ state.modes.pop();
258
+ state.braces.pop();
259
+ }
260
+ }
261
+ state.index += 1;
262
+ }
263
+ function step(state, source) {
264
+ if (currentMode(state) === "template") {
265
+ stepTemplate(state, source);
266
+ return;
267
+ }
268
+ if (stepComment(state, source) || stepString(state, source) || stepTemplateStart(state, source) || stepRegex(state, source)) {
269
+ return;
270
+ }
271
+ stepExpression(state, source);
272
+ }
273
+ function extractComments(source) {
274
+ const shebang = source.startsWith("#!") ? source.indexOf(`
275
+ `) : 0;
276
+ const state = {
277
+ braces: [],
278
+ comments: [],
279
+ index: Math.max(0, shebang),
280
+ modes: ["code"]
281
+ };
282
+ while (state.index < source.length) {
283
+ step(state, source);
284
+ }
285
+ return state.comments;
286
+ }
287
+
288
+ // src/rules.ts
289
+ var PLACEHOLDER_PATTERN = /\b(TODO|FIXME|XXX|HACK)\b/;
290
+ var SEPARATOR_PATTERN = /^[-=*_#~+./\\|]{4,}$/;
291
+ var DIRECTIVE_PATTERN = /^@ts-(?:ignore|expect-error)\b([\s\S]*)$/;
292
+ function normalizeComment(body) {
293
+ return body.split(`
294
+ `).map((line) => line.replace(/^\s*\*+\s?/, "")).join(" ").replace(/\s+/g, " ").trim();
295
+ }
296
+ function classifyComment(body) {
297
+ const text = normalizeComment(body);
298
+ if (text === "") {
299
+ return null;
300
+ }
301
+ if (/^(?:biome-ignore-all|@ts-nocheck)\b/.test(text) || /^eslint-disable(?:-next-line|-line)?\s*$/.test(text)) {
302
+ return "broad-suppression";
303
+ }
304
+ const directive = DIRECTIVE_PATTERN.exec(text);
305
+ if (directive) {
306
+ return (directive[1] ?? "").replace(/^[\s:\u2014-]+/, "") === "" ? "undocumented-directive" : null;
307
+ }
308
+ if (PLACEHOLDER_PATTERN.test(text)) {
309
+ return "placeholder-comment";
310
+ }
311
+ if (SEPARATOR_PATTERN.test(text)) {
312
+ return "separator-comment";
313
+ }
314
+ return null;
315
+ }
316
+
317
+ // src/scan.ts
318
+ var SUPPORTED_EXTENSIONS = new Set([
319
+ ".cjs",
320
+ ".cts",
321
+ ".js",
322
+ ".jsx",
323
+ ".mjs",
324
+ ".mts",
325
+ ".ts",
326
+ ".tsx"
327
+ ]);
328
+ function positionAt(source, offset) {
329
+ let line = 1;
330
+ let lineStart = 0;
331
+ for (let index = 0;index < offset; index += 1) {
332
+ if (source[index] === `
333
+ `) {
334
+ line += 1;
335
+ lineStart = index + 1;
336
+ }
337
+ }
338
+ return { line, column: offset - lineStart + 1 };
339
+ }
340
+ function scanSource(source, file) {
341
+ const findings = [];
342
+ for (const comment of extractComments(source)) {
343
+ const rule = classifyComment(comment.text);
344
+ if (rule === null) {
345
+ continue;
346
+ }
347
+ const position = positionAt(source, comment.start);
348
+ findings.push({
349
+ column: position.column,
350
+ file,
351
+ line: position.line,
352
+ rule,
353
+ text: normalizeComment(comment.text)
354
+ });
355
+ }
356
+ return findings;
357
+ }
358
+ function scanFile(file, cwd = process.cwd()) {
359
+ return scanSource(readFileSync(file, "utf8"), normalizePath(relative2(cwd, file)));
360
+ }
361
+ function scanFiles(files, cwd = process.cwd()) {
362
+ const findings = [];
363
+ for (const file of files) {
364
+ findings.push(...scanFile(file, cwd));
365
+ }
366
+ return findings.sort(compareFindings);
367
+ }
368
+
369
+ // ../shared/src/baseline.ts
370
+ import { existsSync, readFileSync as readFileSync2, writeFileSync } from "fs";
371
+
372
+ // ../shared/src/json.ts
373
+ function isJsonObject(value) {
374
+ return typeof value === "object" && value !== null && !Array.isArray(value);
375
+ }
376
+
377
+ // ../shared/src/baseline.ts
378
+ function entryKey(entry) {
379
+ return [entry.engine ?? "", entry.rule, entry.file, entry.text].join("\x00");
380
+ }
381
+ function compareEntries(left, right) {
382
+ const leftKey = entryKey(left);
383
+ const rightKey = entryKey(right);
384
+ if (leftKey === rightKey) {
385
+ return 0;
386
+ }
387
+ return leftKey < rightKey ? -1 : 1;
388
+ }
389
+ function toEntry(finding) {
390
+ const entry = {
391
+ count: 1,
392
+ file: finding.file,
393
+ rule: finding.rule,
394
+ text: finding.text
395
+ };
396
+ if (finding.engine !== undefined) {
397
+ entry.engine = finding.engine;
398
+ }
399
+ return entry;
400
+ }
401
+ function createBaseline(findings) {
402
+ const entries = new Map;
403
+ for (const finding of findings) {
404
+ const key = entryKey(finding);
405
+ const existing = entries.get(key);
406
+ if (existing) {
407
+ existing.count += 1;
408
+ continue;
409
+ }
410
+ entries.set(key, toEntry(finding));
411
+ }
412
+ return { entries: [...entries.values()].sort(compareEntries), version: 1 };
413
+ }
414
+ function compareWithBaseline(findings, baseline) {
415
+ const remaining = new Map;
416
+ for (const entry of baseline.entries) {
417
+ const key = entryKey(entry);
418
+ remaining.set(key, (remaining.get(key) ?? 0) + entry.count);
419
+ }
420
+ const added = [];
421
+ for (const finding of findings) {
422
+ const key = entryKey(finding);
423
+ const count = remaining.get(key) ?? 0;
424
+ if (count > 0) {
425
+ remaining.set(key, count - 1);
426
+ continue;
427
+ }
428
+ added.push(finding);
429
+ }
430
+ const resolved = baseline.entries.filter((entry) => (remaining.get(entryKey(entry)) ?? 0) > 0);
431
+ return { added, resolved };
432
+ }
433
+ function isBaselineEntry(value) {
434
+ if (!isJsonObject(value)) {
435
+ return false;
436
+ }
437
+ return (value.engine === undefined || typeof value.engine === "string") && typeof value.file === "string" && typeof value.rule === "string" && typeof value.text === "string" && typeof value.count === "number";
438
+ }
439
+ function readBaseline(path, label) {
440
+ if (!existsSync(path)) {
441
+ return { entries: [], version: 1 };
442
+ }
443
+ const value = JSON.parse(readFileSync2(path, "utf8"));
444
+ if (!isJsonObject(value) || !Array.isArray(value.entries) || !value.entries.every(isBaselineEntry)) {
445
+ throw new Error(`${path} is not a ${label} baseline`);
446
+ }
447
+ return { entries: value.entries, version: 1 };
448
+ }
449
+ function writeBaseline(path, baseline) {
450
+ writeFileSync(path, `${JSON.stringify(baseline, null, "\t")}
451
+ `);
452
+ }
453
+
454
+ // ../shared/src/cli.ts
455
+ function addValue(values, name, value) {
456
+ const list = values.get(name);
457
+ if (list === undefined) {
458
+ values.set(name, [value]);
459
+ return;
460
+ }
461
+ list.push(value);
462
+ }
463
+ function addTarget(targets, argument) {
464
+ if (argument.startsWith("-")) {
465
+ throw new Error(`unknown option: ${argument}`);
466
+ }
467
+ targets.push(argument);
468
+ }
469
+ function optionName(argument) {
470
+ const separator = argument.indexOf("=");
471
+ return separator === -1 ? argument.slice(2) : argument.slice(2, separator);
472
+ }
473
+ function inlineValue(argument) {
474
+ const separator = argument.indexOf("=");
475
+ return separator === -1 ? undefined : argument.slice(separator + 1);
476
+ }
477
+ function consumeValue(values, argv, index, name) {
478
+ const value = argv[index + 1];
479
+ if (value === undefined) {
480
+ return 0;
481
+ }
482
+ addValue(values, name, value);
483
+ return 1;
484
+ }
485
+ function parseArgv(argv, spec) {
486
+ const flags = new Set;
487
+ const values = new Map;
488
+ const valueNames = new Set(spec.values ?? []);
489
+ const flagNames = new Set(spec.flags ?? []);
490
+ const targets = [];
491
+ for (let index = 0;index < argv.length; index += 1) {
492
+ const argument = argv[index] ?? "";
493
+ if (!argument.startsWith("--")) {
494
+ addTarget(targets, argument);
495
+ continue;
496
+ }
497
+ const name = optionName(argument);
498
+ if (valueNames.has(name)) {
499
+ const inline = inlineValue(argument);
500
+ if (inline !== undefined) {
501
+ addValue(values, name, inline);
502
+ continue;
503
+ }
504
+ index += consumeValue(values, argv, index, name);
505
+ continue;
506
+ }
507
+ if (flagNames.has(name) && argument.indexOf("=") === -1) {
508
+ flags.add(name);
509
+ continue;
510
+ }
511
+ throw new Error(`unknown option: ${argument}`);
512
+ }
513
+ return { flags, targets, values };
514
+ }
515
+ function wantsHelp(argv) {
516
+ return argv.includes("--help") || argv.includes("-h");
517
+ }
518
+ function runCli(main) {
519
+ async function execute() {
520
+ try {
521
+ process.exit(await main(process.argv.slice(2)));
522
+ } catch (error) {
523
+ console.error(error instanceof Error ? error.message : String(error));
524
+ process.exit(2);
525
+ }
526
+ }
527
+ execute();
528
+ }
529
+
530
+ // src/cli.ts
531
+ var DEFAULT_BASELINE = "comment-baseline.json";
532
+ var RULE_MESSAGES = {
533
+ "broad-suppression": "file-wide suppression hides too much",
534
+ "placeholder-comment": "placeholder comment should be resolved or tracked",
535
+ "separator-comment": "decorative separator comment adds no information",
536
+ "undocumented-directive": "TypeScript directive needs a description"
537
+ };
538
+ var USAGE = "Usage: comment-check [--baseline <path>] [--ignore <path>] [--update-baseline] [--json] [path...]";
539
+ function parseArguments(argv) {
540
+ const parsed = parseArgv(argv, {
541
+ flags: ["json", "update-baseline"],
542
+ values: ["baseline", "ignore"]
543
+ });
544
+ return {
545
+ baselinePath: parsed.values.get("baseline")?.at(-1) ?? DEFAULT_BASELINE,
546
+ ignores: (parsed.values.get("ignore") ?? []).map(normalizePath),
547
+ json: parsed.flags.has("json"),
548
+ targets: parsed.targets.length > 0 ? parsed.targets : ["."],
549
+ update: parsed.flags.has("update-baseline")
550
+ };
551
+ }
552
+ function describeFinding(finding) {
553
+ const message = RULE_MESSAGES[finding.rule] ?? "";
554
+ return `${formatLocation(finding)} ${finding.rule} ${message}`.trimEnd();
555
+ }
556
+ function main(argv) {
557
+ if (wantsHelp(argv)) {
558
+ console.log(USAGE);
559
+ return 0;
560
+ }
561
+ const options = parseArguments(argv);
562
+ const files = collectFiles(options.targets, {
563
+ cwd: process.cwd(),
564
+ extensions: SUPPORTED_EXTENSIONS,
565
+ ignores: options.ignores
566
+ });
567
+ const findings = scanFiles(files);
568
+ if (options.update) {
569
+ const baseline2 = createBaseline(findings);
570
+ writeBaseline(options.baselinePath, baseline2);
571
+ console.log(`Recorded ${baseline2.entries.length} entries in ${options.baselinePath}`);
572
+ return 0;
573
+ }
574
+ const baseline = readBaseline(options.baselinePath, "comment");
575
+ const comparison = compareWithBaseline(findings, baseline);
576
+ if (options.json) {
577
+ console.log(JSON.stringify({ added: comparison.added, resolved: comparison.resolved }, null, "\t"));
578
+ } else {
579
+ for (const finding of comparison.added) {
580
+ console.log(describeFinding(finding));
581
+ }
582
+ console.log(`Checked ${files.length} files: ${comparison.added.length} new, ${comparison.resolved.length} resolved, ${baseline.entries.length} baselined`);
583
+ }
584
+ return comparison.added.length > 0 ? 1 : 0;
585
+ }
586
+ runCli(main);