@kongyo2/ts-comment-scanner 1.10.0 → 1.11.1
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 +403 -137
- package/dist/args.d.ts +2 -0
- package/dist/args.d.ts.map +1 -1
- package/dist/args.js +25 -0
- package/dist/args.js.map +1 -1
- package/dist/directives.d.ts +41 -14
- package/dist/directives.d.ts.map +1 -1
- package/dist/directives.js +103 -32
- package/dist/directives.js.map +1 -1
- package/dist/remove.d.ts +10 -1
- package/dist/remove.d.ts.map +1 -1
- package/dist/remove.js +65 -10
- package/dist/remove.js.map +1 -1
- package/dist/run.d.ts.map +1 -1
- package/dist/run.js +5 -1
- package/dist/run.js.map +1 -1
- package/dist/scanner.d.ts +11 -0
- package/dist/scanner.d.ts.map +1 -1
- package/dist/scanner.js +100 -19
- package/dist/scanner.js.map +1 -1
- package/package.json +1 -1
- package/src/args.ts +28 -0
- package/src/directives.ts +148 -35
- package/src/remove.ts +72 -12
- package/src/run.ts +5 -1
- package/src/scanner.ts +107 -19
- package/README.en.md +0 -241
package/src/scanner.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import ts from "typescript";
|
|
2
2
|
import { bunMarkerOffset, detectDirective, type DirectivePlacement } from "./directives.js";
|
|
3
3
|
import { jsxLayout, type JsxLayout } from "./jsx.js";
|
|
4
|
+
import { isBlank } from "./lines.js";
|
|
5
|
+
import { firstIndexAtOrAfter } from "./ranges.js";
|
|
4
6
|
import type { Comment, CommentKind } from "./types.js";
|
|
5
7
|
|
|
6
8
|
export interface ScanOptions {
|
|
@@ -27,6 +29,8 @@ export function analyzeSource(source: string, options: ScanOptions = {}): Source
|
|
|
27
29
|
const jsxParents: Array<ts.JsxElement | ts.JsxFragment> = [];
|
|
28
30
|
const ranges: ts.CommentRange[] = [];
|
|
29
31
|
const seen = new Set<number>();
|
|
32
|
+
/** Every token, in document order. */
|
|
33
|
+
const tokens: ts.Node[] = [];
|
|
30
34
|
|
|
31
35
|
const collect = (found: readonly ts.CommentRange[] | undefined): void => {
|
|
32
36
|
if (!found) return;
|
|
@@ -49,6 +53,7 @@ export function analyzeSource(source: string, options: ScanOptions = {}): Source
|
|
|
49
53
|
// end-of-file token). Treat them as trivia like any other comment.
|
|
50
54
|
const children = node.getChildren(sourceFile).filter((child) => !ts.isJSDoc(child));
|
|
51
55
|
if (children.length === 0) {
|
|
56
|
+
tokens.push(node);
|
|
52
57
|
if (node.kind === ts.SyntaxKind.JsxText) {
|
|
53
58
|
jsxTextSpans.push([node.getFullStart(), node.getEnd()]);
|
|
54
59
|
}
|
|
@@ -91,30 +96,39 @@ export function analyzeSource(source: string, options: ScanOptions = {}): Source
|
|
|
91
96
|
const shebangEnd = ts.getShebang(source)?.length ?? 0;
|
|
92
97
|
const firstCommentPos = sorted.length > 0 ? (sorted[0] as ts.CommentRange).pos : -1;
|
|
93
98
|
const bunMarkerPos = bunMarkerOffset(source);
|
|
94
|
-
// The token after
|
|
95
|
-
//
|
|
96
|
-
//
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
99
|
+
// The token after a comment, past any further comments: no token overlaps
|
|
100
|
+
// a comment, so it is the first one ending at or past the comment's end
|
|
101
|
+
// (the end-of-file token ends at the text's end). Token ends never
|
|
102
|
+
// decrease in document order, so a binary search finds it — without
|
|
103
|
+
// skipping the leading trivia a token start would need.
|
|
104
|
+
const tokenAfter = (offset: number): ts.Node =>
|
|
105
|
+
tokens[firstIndexAtOrAfter(tokens, offset, (token) => token.end)] as ts.Node;
|
|
106
|
+
const placementOf = (range: ts.CommentRange): DirectivePlacement => {
|
|
107
|
+
// The switch slots walk the syntax tree, so they are worked out only for
|
|
108
|
+
// the comments a switch-clause rule matched, when it asks.
|
|
109
|
+
let slots: ReturnType<typeof switchSlots> | undefined;
|
|
110
|
+
const slotsOf = (): ReturnType<typeof switchSlots> => (slots ??= switchSlots(tokenAfter(range.end)));
|
|
111
|
+
const firstComment = range.pos === firstCommentPos;
|
|
112
|
+
return {
|
|
113
|
+
header: range.pos < firstTokenStart,
|
|
114
|
+
firstComment: firstComment && /^\s*$/.test(source.slice(shebangEnd, range.pos)),
|
|
115
|
+
fileStart: range.pos === bunMarkerPos,
|
|
116
|
+
fileWide: firstComment && isFileWidePosition(source, range.pos, range.end),
|
|
117
|
+
get fallthroughSlot() {
|
|
118
|
+
return slotsOf().fallthroughSlot;
|
|
119
|
+
},
|
|
120
|
+
get noDefaultSlot() {
|
|
121
|
+
return slotsOf().noDefaultSlot;
|
|
122
|
+
},
|
|
123
|
+
};
|
|
124
|
+
};
|
|
111
125
|
|
|
112
|
-
const comments = sorted.map((range
|
|
126
|
+
const comments = sorted.map((range): Comment => {
|
|
113
127
|
const kind: CommentKind = range.kind === ts.SyntaxKind.SingleLineCommentTrivia ? "line" : "block";
|
|
114
128
|
const text = source.slice(range.pos, range.end);
|
|
115
129
|
const startPosition = sourceFile.getLineAndCharacterOfPosition(range.pos);
|
|
116
130
|
const endPosition = sourceFile.getLineAndCharacterOfPosition(range.end);
|
|
117
|
-
const directive = detectDirective(kind, text, placementOf(range
|
|
131
|
+
const directive = detectDirective(kind, text, placementOf(range));
|
|
118
132
|
return {
|
|
119
133
|
kind,
|
|
120
134
|
text,
|
|
@@ -130,3 +144,77 @@ export function analyzeSource(source: string, options: ScanOptions = {}): Source
|
|
|
130
144
|
|
|
131
145
|
return { comments, jsx: jsxLayout(source, sourceFile, jsxParents, comments) };
|
|
132
146
|
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Whether a comment from `start` to `end` sits where ast-grep's suppression
|
|
150
|
+
* comment covers the whole file (`get_suppression_kind` in its `combined.rs`):
|
|
151
|
+
* on the first line with nothing but whitespace in front of it, and with the
|
|
152
|
+
* next node — code or another comment — starting two or more lines further
|
|
153
|
+
* down, or with nothing after it at all. Lines are counted the way tree-sitter
|
|
154
|
+
* counts its rows, by line feeds alone.
|
|
155
|
+
*/
|
|
156
|
+
export function isFileWidePosition(text: string, start: number, end: number): boolean {
|
|
157
|
+
if (!opensFirstRow(text, start)) return false;
|
|
158
|
+
const next = text.slice(end).search(/\S/);
|
|
159
|
+
return next === -1 || lineFeedCount(text.slice(0, end + next)) >= 2;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Whether nothing but whitespace, and no line feed, precedes the offset: the start of tree-sitter's first row. */
|
|
163
|
+
export function opensFirstRow(text: string, offset: number): boolean {
|
|
164
|
+
const before = text.slice(0, offset);
|
|
165
|
+
return isBlank(before) && !before.includes("\n");
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function lineFeedCount(text: string): number {
|
|
169
|
+
return text.split("\n").length - 1;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* The switch slots (see DirectivePlacement) a comment in front of the given
|
|
174
|
+
* token sits in. The token is what follows the comment past any further
|
|
175
|
+
* comments — the end-of-file token at the latest, whose parent is the file.
|
|
176
|
+
*/
|
|
177
|
+
function switchSlots(token: ts.Node): { fallthroughSlot: boolean; noDefaultSlot: boolean } {
|
|
178
|
+
let fallthroughSlot = false;
|
|
179
|
+
let noDefaultSlot = false;
|
|
180
|
+
const parent = token.parent;
|
|
181
|
+
if (
|
|
182
|
+
(token.kind === ts.SyntaxKind.CaseKeyword || token.kind === ts.SyntaxKind.DefaultKeyword) &&
|
|
183
|
+
ts.isCaseOrDefaultClause(parent)
|
|
184
|
+
) {
|
|
185
|
+
// In front of a clause: where ESLint, oxlint and deno_lint read the
|
|
186
|
+
// comment saying the clause before it falls through — so not the first.
|
|
187
|
+
fallthroughSlot = parent.parent.clauses[0] !== parent;
|
|
188
|
+
} else if (
|
|
189
|
+
token.kind === ts.SyntaxKind.CloseBraceToken &&
|
|
190
|
+
ts.isBlock(parent) &&
|
|
191
|
+
ts.isCaseOrDefaultClause(parent.parent)
|
|
192
|
+
) {
|
|
193
|
+
// Inside a block that is the last statement of a clause (its only one,
|
|
194
|
+
// for ESLint and oxlint), in front of its closing brace — read when
|
|
195
|
+
// another clause follows.
|
|
196
|
+
const clause = parent.parent;
|
|
197
|
+
const clauses = clause.parent.clauses;
|
|
198
|
+
fallthroughSlot = clause.statements.at(-1) === parent && clauses.at(-1) !== clause;
|
|
199
|
+
} else if (token.kind === ts.SyntaxKind.CloseBraceToken && ts.isCaseBlock(parent)) {
|
|
200
|
+
// After the last clause of a switch, in front of its closing brace:
|
|
201
|
+
// where ESLint's default-case reads its comment.
|
|
202
|
+
noDefaultSlot = lacksDefaultClause(parent);
|
|
203
|
+
}
|
|
204
|
+
// oxlint's default-case reads the last comment from the last clause's
|
|
205
|
+
// start to the switch's end, so the comments inside that clause count too
|
|
206
|
+
// — all but one in front of the clause's opening `case`.
|
|
207
|
+
for (let node = parent; !noDefaultSlot && !ts.isSourceFile(node); node = node.parent) {
|
|
208
|
+
noDefaultSlot =
|
|
209
|
+
ts.isCaseClause(node) &&
|
|
210
|
+
node.parent.clauses.at(-1) === node &&
|
|
211
|
+
lacksDefaultClause(node.parent) &&
|
|
212
|
+
(node !== parent || token.kind !== ts.SyntaxKind.CaseKeyword);
|
|
213
|
+
}
|
|
214
|
+
return { fallthroughSlot, noDefaultSlot };
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** Whether the switch has clauses but none of them is a default clause. */
|
|
218
|
+
function lacksDefaultClause(caseBlock: ts.CaseBlock): boolean {
|
|
219
|
+
return caseBlock.clauses.length > 0 && !caseBlock.clauses.some(ts.isDefaultClause);
|
|
220
|
+
}
|
package/README.en.md
DELETED
|
@@ -1,241 +0,0 @@
|
|
|
1
|
-
<p align="center">
|
|
2
|
-
<a href="https://kongyo2.github.io/ts-comment-scanner/"><img src="https://raw.githubusercontent.com/kongyo2/ts-comment-scanner/main/assets/logo.svg" width="96" height="96" alt="ts-comment-scanner logo"></a>
|
|
3
|
-
</p>
|
|
4
|
-
|
|
5
|
-
# ts-comment-scanner
|
|
6
|
-
|
|
7
|
-
[](https://www.npmjs.com/package/@kongyo2/ts-comment-scanner)
|
|
8
|
-
[](https://www.npmjs.com/package/@kongyo2/ts-comment-scanner)
|
|
9
|
-
[](https://github.com/kongyo2/ts-comment-scanner/actions/workflows/ci.yml)
|
|
10
|
-
[](https://kongyo2.github.io/ts-comment-scanner/)
|
|
11
|
-

|
|
12
|
-
[](https://nodejs.org)
|
|
13
|
-
[](./LICENSE)
|
|
14
|
-
[](https://deepwiki.com/kongyo2/ts-comment-scanner)
|
|
15
|
-
|
|
16
|
-
[日本語](./README.md) | **English** | 📘 [Project site](https://kongyo2.github.io/ts-comment-scanner/?lang=en)
|
|
17
|
-
|
|
18
|
-
A CLI / library that detects, lists, and summarizes comments in a TypeScript project — and can also remove them safely. It analyzes code through the TypeScript AST, so it never mistakes strings, template literals, regular expressions, or JSX text for comments.
|
|
19
|
-
|
|
20
|
-
## Features
|
|
21
|
-
|
|
22
|
-
- Recursively scans `.ts` `.tsx` `.mts` `.cts` (excluding `node_modules` and `.git`); symlinks are followed during the walk just like explicit inputs, with cycles detected automatically
|
|
23
|
-
- Reports line comments (`//`) and block comments (`/* */`) with position information
|
|
24
|
-
- Outputs in three formats: text / JSON / **GitHub Actions annotations**
|
|
25
|
-
- **Automatically identifies compiler and linter directives** such as `@ts-ignore` and `eslint-disable`, so you can filter them in or out
|
|
26
|
-
- **Safe comment removal** (code cleanup): directives and license headers are kept by default
|
|
27
|
-
- Handles UTF-8 (with or without BOM) and BOM-marked UTF-16 (LE/BE); removal preserves the encoding and BOM, and files with a broken encoding are reported as errors **without being modified**
|
|
28
|
-
- **Custom ignore patterns** via glob (`--ignore`, with a trailing slash such as `dist/` restricting a pattern to directories) and configurable target extensions (`--ext`, parsing JavaScript with JSX enabled)
|
|
29
|
-
- **git integration (`--diff`)**: narrow the scan to files touched between specific commits or in uncommitted work
|
|
30
|
-
- `--fail-on-comment` for CI (exit code 1 when comments are detected)
|
|
31
|
-
- Usable both as a CLI and as a library
|
|
32
|
-
|
|
33
|
-
## Installation
|
|
34
|
-
|
|
35
|
-
```bash
|
|
36
|
-
npm install @kongyo2/ts-comment-scanner
|
|
37
|
-
```
|
|
38
|
-
|
|
39
|
-
To run without installing:
|
|
40
|
-
|
|
41
|
-
```bash
|
|
42
|
-
npx @kongyo2/ts-comment-scanner src
|
|
43
|
-
```
|
|
44
|
-
|
|
45
|
-
## CLI usage
|
|
46
|
-
|
|
47
|
-
```
|
|
48
|
-
ts-comment-scanner [options] [paths...]
|
|
49
|
-
|
|
50
|
-
Output:
|
|
51
|
-
--format <fmt> Output format: text / json / github (default: text)
|
|
52
|
-
--json Shorthand for --format json
|
|
53
|
-
|
|
54
|
-
Filtering:
|
|
55
|
-
--ignore <glob> Exclude files/directories matching the glob (repeatable)
|
|
56
|
-
--ext <list> Extensions to scan (comma-separated, default: .ts,.tsx,.mts,.cts)
|
|
57
|
-
--diff <range> Only files git reports changed (e.g. HEAD, main..HEAD)
|
|
58
|
-
--skip-directives Exclude compiler/linter directives from the results
|
|
59
|
-
--only-directives Report only directives
|
|
60
|
-
|
|
61
|
-
CI:
|
|
62
|
-
--fail-on-comment Exit with code 1 if any comment is reported
|
|
63
|
-
|
|
64
|
-
Removal:
|
|
65
|
-
--remove Remove reported comments from files (in place)
|
|
66
|
-
--dry-run With --remove: show what would be removed without changing files
|
|
67
|
-
--remove-directives With --remove: also remove directive comments
|
|
68
|
-
--remove-legal With --remove: also remove license/legal comments
|
|
69
|
-
|
|
70
|
-
Other:
|
|
71
|
-
-h, --help Show help
|
|
72
|
-
-v, --version Show version
|
|
73
|
-
```
|
|
74
|
-
|
|
75
|
-
If no paths are given, the current directory is used. A glob without a slash (e.g. `*.test.ts`) matches against file names, while one that contains a slash (e.g. `src/legacy/**`) matches against paths. As in `.gitignore`, a pattern ending in a slash (e.g. `dist/`) matches directories only. Files passed explicitly are never subject to `--ignore`.
|
|
76
|
-
|
|
77
|
-
JavaScript files added through `--ext` (`.js`, `.jsx`, `.mjs`, `.cjs`) are parsed with JSX enabled, just as TypeScript itself parses them, so text such as `<div>http://…</div>` inside a React component is never mistaken for a comment.
|
|
78
|
-
|
|
79
|
-
**Exit codes**: `0` success / `1` comments detected when `--fail-on-comment` is set / `2` argument or runtime error
|
|
80
|
-
|
|
81
|
-
### Example output
|
|
82
|
-
|
|
83
|
-
```bash
|
|
84
|
-
$ ts-comment-scanner src
|
|
85
|
-
src/index.ts:1:1 [line] // entry point
|
|
86
|
-
src/scanner.ts:8:3 [block] /* walk the AST */
|
|
87
|
-
src/legacy.ts:3:1 [line] [@ts-ignore] // @ts-ignore fix later
|
|
88
|
-
|
|
89
|
-
3 comments across 3 files
|
|
90
|
-
```
|
|
91
|
-
|
|
92
|
-
JSON output:
|
|
93
|
-
|
|
94
|
-
```bash
|
|
95
|
-
$ ts-comment-scanner --json src
|
|
96
|
-
{
|
|
97
|
-
"summary": { "files": 1, "comments": 1, "directives": 0 },
|
|
98
|
-
"files": [
|
|
99
|
-
{
|
|
100
|
-
"file": "src/index.ts",
|
|
101
|
-
"comments": [
|
|
102
|
-
{
|
|
103
|
-
"kind": "line",
|
|
104
|
-
"text": "// entry point",
|
|
105
|
-
"start": 0,
|
|
106
|
-
"end": 14,
|
|
107
|
-
"line": 1,
|
|
108
|
-
"column": 1,
|
|
109
|
-
"endLine": 1,
|
|
110
|
-
"endColumn": 15
|
|
111
|
-
}
|
|
112
|
-
]
|
|
113
|
-
}
|
|
114
|
-
]
|
|
115
|
-
}
|
|
116
|
-
```
|
|
117
|
-
|
|
118
|
-
Comments identified as directives get a name attached, such as `"directive": "@ts-ignore"`.
|
|
119
|
-
|
|
120
|
-
### Using it in GitHub Actions
|
|
121
|
-
|
|
122
|
-
`--format github` emits each comment as a [workflow command](https://docs.github.com/actions/reference/workflow-commands-for-github-actions), so annotations appear on the relevant lines of a PR.
|
|
123
|
-
|
|
124
|
-
```yaml
|
|
125
|
-
- name: Check for stray comments
|
|
126
|
-
run: npx @kongyo2/ts-comment-scanner --format github --skip-directives --fail-on-comment src
|
|
127
|
-
```
|
|
128
|
-
|
|
129
|
-
```
|
|
130
|
-
::notice file=src/index.ts,line=1,endLine=1,col=1,endColumn=14,title=line comment::// entry point
|
|
131
|
-
```
|
|
132
|
-
|
|
133
|
-
While the JSON output's `endColumn` is exclusive (the column after the comment), GitHub annotation columns are inclusive, so the annotation reports the column of the last character (14 in this example). Comments larger than GitHub's 64 KiB annotation limit are truncated safely.
|
|
134
|
-
|
|
135
|
-
### Bulk comment removal (code cleanup)
|
|
136
|
-
|
|
137
|
-
```bash
|
|
138
|
-
# First, check what would be removed
|
|
139
|
-
ts-comment-scanner --remove --dry-run src
|
|
140
|
-
|
|
141
|
-
# Actually remove (directives and license headers are kept)
|
|
142
|
-
ts-comment-scanner --remove src
|
|
143
|
-
|
|
144
|
-
# Remove everything, including directives and legal comments
|
|
145
|
-
ts-comment-scanner --remove --remove-directives --remove-legal src
|
|
146
|
-
```
|
|
147
|
-
|
|
148
|
-
Removal is driven by the AST's comment ranges, so it never touches strings or code. In addition:
|
|
149
|
-
|
|
150
|
-
- Directives such as `@ts-expect-error` / `eslint-disable` are **kept by default**, because removing them would break the build or the linter
|
|
151
|
-
- Legal comments — `/*! ... */` or those containing `@license` / `@preserve` / `@copyright` or the `SPDX-License-Identifier:` / `SPDX-FileCopyrightText:` tags — are also **kept by default**
|
|
152
|
-
- **The line structure below next-line directives** (`@ts-expect-error`, `eslint-disable-next-line`, ...) **is preserved**: when removing comments would delete a line and shift the directive's target (e.g. a comment-only line), those comments are kept instead
|
|
153
|
-
- **Comments a directive looks past for its target are kept too**: below tsc's `@ts-ignore`/`@ts-expect-error`, which skip blank and `//` lines to find their target, the first line tsc 6 or tsc 7 stops at (a block-comment line, say) is kept; between a directive that only counts as the last comment before its target (`@deno-types`, `/* GraphQL */`, ESLint's `// falls through`, ...) and that target, every comment is kept
|
|
154
|
-
- **Position-dependent directives are never activated by a removal**: when deleting a leading comment would make prettier's `@format`/`@prettier` pragma or Deno's `deno-coverage-ignore-file` (honoured only in the file's first comment) or Bun's `// @bun` marker (honoured only at the very start of the file or on the line after a shebang) newly take effect in a kept comment, the leading comment is kept as well
|
|
155
|
-
- Whitespace is inserted where removing a block comment would otherwise join tokens together (`a/* x */b` → `a b`), and none is left where it only held the comment off a bracket or punctuation (`f(/* x */ a)` → `f(a)`, `{/* x */}` → `{}`)
|
|
156
|
-
- Comment-only lines are removed entirely, and trailing comments are removed together with the preceding whitespace
|
|
157
|
-
- **No blank-line pile-ups**: where comment-only lines vanish, the blank lines around them close ranks to the widest gap the source had there (removing a comment that sat between two blank lines leaves one, not two). At the start or end of the file or of a block (`{`, `(`, `[`, JSX tags), the blank lines that only separated the comment from the code go with it, while those already against the edge stay. Blank lines a next-line directive reaches stay put
|
|
158
|
-
- **JSX comments go with their braces**: `{/* ... */}` is removed as a whole — its line too, when it stands alone — instead of leaving `{ }` behind. Where the braces also keep rendered text apart, dropping them would change what the element renders (JSX merges and trims text across them), so `{" "}` takes their place when that renders the same (`<a /> {/* x */}` at the end of a line → `<a />{" "}`), and otherwise `{}` stays. The output is re-parsed and every element's rendered children compared under the whitespace rules of TypeScript, esbuild and Babel. A comment container right after a directive in braces that applies to the next sibling (`{/* prettier-ignore */}`, ...) is kept
|
|
159
|
-
- The result is re-scanned to verify that the surviving comments match the protected set, directive meaning included; if the outcome is unexpected the file is left unchanged and an error is reported
|
|
160
|
-
- Writes go through a temporary file and an atomic rename, so a failed write or a full disk can never truncate the original
|
|
161
|
-
|
|
162
|
-
With `--remove --json`, `summary.files` counts the entries of the `files` array (every file with removed, kept or skipped comments) and `summary.changedFiles` counts the files that actually had comments removed.
|
|
163
|
-
|
|
164
|
-
### Scanning only changed files (`--diff`)
|
|
165
|
-
|
|
166
|
-
With `--diff <range>`, scanning and removal are limited to the files git reports as changed. The range is exactly what `git diff` accepts as revisions: a single revision compares the working tree against it (untracked new files included, honouring `.gitignore`), while `a..b` / `a...b` compare two commits.
|
|
167
|
-
|
|
168
|
-
```bash
|
|
169
|
-
# Scan only files with uncommitted changes
|
|
170
|
-
ts-comment-scanner --diff HEAD
|
|
171
|
-
|
|
172
|
-
# Remove comments only from files changed on the branch
|
|
173
|
-
ts-comment-scanner --remove --diff main...HEAD
|
|
174
|
-
|
|
175
|
-
# Check only files changed between two commits in CI
|
|
176
|
-
ts-comment-scanner --fail-on-comment --diff a1b2c3..d4e5f6 src
|
|
177
|
-
```
|
|
178
|
-
|
|
179
|
-
This is designed for workflows like letting a coding agent do some work and then sweeping noise comments out of just the files it touched. Files deleted within the range are excluded, and renames are handled at their new path. git runs in the repository that contains the first input path, so pointing at another repository's checkout works too. Note that unlike `--ignore`, the narrowing also applies to explicitly listed files.
|
|
180
|
-
|
|
181
|
-
### Detectable directives (excerpt)
|
|
182
|
-
|
|
183
|
-
Each directive is matched the way the real tool's parser matches it (its regex or string comparison). Where tools or versions disagree, every form any of them honours counts as a directive, so removal errs on the side of keeping the comment.
|
|
184
|
-
|
|
185
|
-
- **Compiler / types**: `@ts-ignore` `@ts-expect-error` `@ts-nocheck` `@ts-check` (tsc 6, tsc 7, and Flow checking TypeScript files) / the `/// <reference>` family / `@ts-strict-ignore`, `@ts-strict` (typescript-strict-plugin's CLI and IDE plugin) / `@deno-types=`, `@ts-types=`, `@ts-self-types=` (Deno)
|
|
186
|
-
- **Linters**: the `eslint-disable` family, `eslint-env`, `/* global */`, `/* exported */`, `// falls through` (no-fallthrough), `// no default` (default-case; both only in front of the `case`, `default` or `}` ESLint reads them before) / the `eslint-disable … react-hooks/…` and `$FlowFixMe[react-rule…]` suppressions React Compiler reads / the `oxlint-disable` family / the `biome-ignore` family, `rome-ignore` / the `deno-lint-ignore` family / `stylelint-disable`, `stylelint-disable-line`, `stylelint-disable-next-line`, `stylelint-enable` (stylelint) / `@flow`, `@noflow`, the `$FlowFixMe` family, `flowlint` (Flow) / `tslint:`, `jshint`, `jscs:`, `jslint` (legacy)
|
|
187
|
-
- **Formatters**: `prettier-ignore`, the `@format`/`@prettier`/`@noformat`/`@noprettier` pragmas, `/** @type */` / `/** @satisfies */` type-cast comments (prettier) / `oxfmt-ignore` / `dprint-ignore`, `dprint-ignore-file`, `deno-fmt-ignore`, `deno-fmt-ignore-file` (dprint / deno fmt) / `organize-imports-ignore`, `sort-imports-ignore` / `beautify ignore/preserve` (legacy)
|
|
188
|
-
- **Coverage / testing**: `istanbul ignore`, `c8 ignore`, `v8 ignore`, `node:coverage`, the `deno-coverage-ignore` family / `@jest-environment(-options)`, `@vitest-environment(-options)`, `@module-tag` (Vitest 4+) / `Stryker disable/restore` / `type-coverage:ignore-line/-next-line` / `ts-prune-ignore-next`
|
|
189
|
-
- **Bundlers / runtimes**: webpack and turbopack magic comments such as `webpackChunkName:` / `@vite-ignore` / `#__PURE__`, `@__NO_SIDE_EFFECTS__`, `@__INLINE__`, `@__KEY__`, `@__MANGLE_PROP__` (terser/rollup annotations) / `// @bun` (Bun) / `@refresh reset/skip/reload/jsx-skip` (react-refresh / solid-refresh) / `million-ignore` / `nx-ignore-next-line` (Nx) / `@unocss-include/-ignore/-ide-include/-skip-start/-skip-end` / `@next-codemod-error/-ignore` (Next.js) / `/* GraphQL */`, `/* HTML */` tag comments / `//# sourceMappingURL=`, `//# sourceURL=` / `@jsx`-family pragmas (Deno's `@jsxImportSourceTypes` included)
|
|
190
|
-
- **Security / static analysis**: `NOSONAR` (SonarQube) / `nosemgrep` (Semgrep) / `lgtm[...]`, `codeql[...]` (CodeQL) / `skipcq` (DeepSource) / `deepcode ignore` (Snyk Code) / `no-dd-sa`, `datadog-disable` (Datadog) / `gitleaks:allow` / `trufflehog:ignore` / `pragma: allowlist secret` (detect-secrets)
|
|
191
|
-
- **Spell checkers**: the `cspell:` family (including the `cSpell:`, `spell-checker:`, `spellchecker:` aliases), `LocalWords` / `codespell:ignore`
|
|
192
|
-
- **Editors / IDEs**: `#region`, `#endregion`, `// region` (VS Code / JetBrains) / `noinspection`, `//file:noinspection`, `<editor-fold>`, `language=` (JetBrains) / `ReSharper disable/restore`
|
|
193
|
-
|
|
194
|
-
The prettier rules copy prettier's own implementation: `prettier-ignore` is an exact match on the trimmed comment body (JS/TS has no `prettier-ignore-start`/`-end`, so those stay ordinary comments), the `@format`-family pragmas go through the same docblock parsing as jest-docblock (the file's first block comment only, `@` at the start of a line, spaces only before it), `/** @type */` and `/** @satisfies */` are the type-cast comments whose following parentheses prettier keeps (and which tsc honours in JavaScript), and `@flow`/`@noflow` in the leading comments is what switches its babel parser to Flow syntax. The test suite cross-checks these rules against the real prettier.
|
|
195
|
-
|
|
196
|
-
The TypeScript rules follow both tsc 6 (the JavaScript compiler) and tsc 7 (the Go port). `//// @ts-ignore` and a `/// <reference types="node">` without its closing `/>` are live to tsc 7 alone, and an `@ts-ignore` behind a no-break space after `//` to tsc 6 alone; all of them count as directives. The test suite cross-checks these rules against the real tsc 6 as well.
|
|
197
|
-
|
|
198
|
-
## Using it as a library
|
|
199
|
-
|
|
200
|
-
```ts
|
|
201
|
-
import { scanPaths, scanComments, removeComments, changedFiles, formatText } from "@kongyo2/ts-comment-scanner";
|
|
202
|
-
|
|
203
|
-
// Scan files / directories together
|
|
204
|
-
const results = await scanPaths(["src"], { ignore: ["**/*.test.ts"] });
|
|
205
|
-
console.log(formatText(results));
|
|
206
|
-
|
|
207
|
-
// Scan a source string directly
|
|
208
|
-
const comments = scanComments("// hello\nconst x = 1;");
|
|
209
|
-
|
|
210
|
-
// Remove comments safely
|
|
211
|
-
const { code, removed, kept } = removeComments("// note\nconst x = 1;\n");
|
|
212
|
-
|
|
213
|
-
// Absolute paths of files changed in a git revision range
|
|
214
|
-
const changed = await changedFiles("main..HEAD");
|
|
215
|
-
```
|
|
216
|
-
|
|
217
|
-
### Main API
|
|
218
|
-
|
|
219
|
-
| Function | Summary |
|
|
220
|
-
| --- | --- |
|
|
221
|
-
| `scanComments(source, options?)` | Get an array of comments from a source string (parse TSX with `options.jsx`) |
|
|
222
|
-
| `scanFile(file)` | Scan a single file |
|
|
223
|
-
| `scanPaths(inputs, options?)` | Recursively scan files / directories (supports `ignore` / `extensions`) |
|
|
224
|
-
| `collectFiles(inputs, options?)` | Collect the list of target file paths |
|
|
225
|
-
| `changedFiles(range, cwd?)` | Absolute paths of working-tree files changed in a git revision range |
|
|
226
|
-
| `removeComments(source, options?)` | Remove comments safely (`removeDirectives` / `removeLegal` / `shouldRemove`) |
|
|
227
|
-
| `detectDirective(kind, text, placement?)` | Return a normalized name if the comment is a directive (`placement` enables position-sensitive rules) |
|
|
228
|
-
| `isLegalComment(text)` | Determine whether a comment is a license/legal comment |
|
|
229
|
-
| `formatText(results)` / `formatJson(results)` / `formatGitHub(results)` | Format scan results |
|
|
230
|
-
| `readFileText(file)` / `decodeFileText(data)` / `encodeFileText(text, target)` | Read/decode/encode helpers that preserve UTF-8 / UTF-16 and BOMs |
|
|
231
|
-
| `writeFileAtomic(file, data)` | Replace a file atomically through a temporary sibling |
|
|
232
|
-
|
|
233
|
-
Types: `Comment` / `CommentKind` / `FileScanResult` / `ScanOptions` / `CollectOptions` / `RemoveOptions` / `RemoveResult` / `FileText` / `FileEncoding` / `DirectivePlacement`
|
|
234
|
-
|
|
235
|
-
## Requirements
|
|
236
|
-
|
|
237
|
-
Node.js 20 or later
|
|
238
|
-
|
|
239
|
-
## License
|
|
240
|
-
|
|
241
|
-
MIT
|