@kongyo2/ts-comment-scanner 1.5.0 → 1.7.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.en.md +5 -3
- package/README.md +5 -3
- package/dist/args.d.ts.map +1 -1
- package/dist/args.js +6 -2
- package/dist/args.js.map +1 -1
- package/dist/directives.d.ts.map +1 -1
- package/dist/directives.js +61 -20
- package/dist/directives.js.map +1 -1
- package/dist/files.d.ts +10 -2
- package/dist/files.d.ts.map +1 -1
- package/dist/files.js +91 -72
- package/dist/files.js.map +1 -1
- package/dist/git.d.ts.map +1 -1
- package/dist/git.js +7 -2
- package/dist/git.js.map +1 -1
- package/dist/lines.d.ts +18 -0
- package/dist/lines.d.ts.map +1 -0
- package/dist/lines.js +40 -0
- package/dist/lines.js.map +1 -0
- package/dist/remove.d.ts.map +1 -1
- package/dist/remove.js +60 -75
- package/dist/remove.js.map +1 -1
- package/dist/report.d.ts.map +1 -1
- package/dist/report.js +2 -2
- package/dist/report.js.map +1 -1
- package/dist/run.d.ts +1 -1
- package/dist/run.d.ts.map +1 -1
- package/dist/run.js +16 -16
- package/dist/run.js.map +1 -1
- package/package.json +1 -1
- package/src/args.ts +5 -2
- package/src/directives.ts +67 -23
- package/src/files.ts +110 -71
- package/src/git.ts +6 -2
- package/src/lines.ts +43 -0
- package/src/remove.ts +61 -79
- package/src/report.ts +2 -2
- package/src/run.ts +16 -16
package/src/directives.ts
CHANGED
|
@@ -1,9 +1,14 @@
|
|
|
1
|
+
import { lastLine, splitLines } from "./lines.js";
|
|
1
2
|
import type { CommentKind } from "./types.js";
|
|
2
3
|
|
|
3
4
|
interface DirectiveRule {
|
|
4
5
|
pattern: RegExp;
|
|
5
|
-
/**
|
|
6
|
-
|
|
6
|
+
/**
|
|
7
|
+
* Fixed name, or derive it from the match — returning undefined rejects the
|
|
8
|
+
* match, for checks a single regex cannot express. Defaults to the full
|
|
9
|
+
* matched text.
|
|
10
|
+
*/
|
|
11
|
+
name?: string | ((match: RegExpExecArray) => string | undefined);
|
|
7
12
|
blockOnly?: boolean;
|
|
8
13
|
/** Only match line comments (e.g. JetBrains suppressions in JS/TS). */
|
|
9
14
|
lineOnly?: boolean;
|
|
@@ -36,6 +41,25 @@ interface DirectiveRule {
|
|
|
36
41
|
keepStars?: boolean;
|
|
37
42
|
}
|
|
38
43
|
|
|
44
|
+
// stylelint's configuration commands, compared verbatim (as in its
|
|
45
|
+
// `configurationComment.mjs`) once the marker has been cut out of the
|
|
46
|
+
// comment's first token.
|
|
47
|
+
const STYLELINT_MARKER = "stylelint";
|
|
48
|
+
const STYLELINT_COMMANDS: ReadonlySet<string> = new Set(["-disable", "-disable-line", "-disable-next-line", "-enable"]);
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* The stylelint command the comment's first whitespace-delimited token
|
|
52
|
+
* carries, if any. Mirrors `isConfigurationComment`: `String#replace` with a
|
|
53
|
+
* string pattern drops only the FIRST `stylelint` in the token, wherever it
|
|
54
|
+
* sits, and the remainder must equal a command exactly (case-sensitively) —
|
|
55
|
+
* so `-disable` alone, or `-disablestylelint`, is a live command to stylelint
|
|
56
|
+
* while `stylelintstylelint-disable` is not.
|
|
57
|
+
*/
|
|
58
|
+
function stylelintDirective(token: string): string | undefined {
|
|
59
|
+
const command = token.replace(STYLELINT_MARKER, "");
|
|
60
|
+
return STYLELINT_COMMANDS.has(command) ? `${STYLELINT_MARKER}${command}` : undefined;
|
|
61
|
+
}
|
|
62
|
+
|
|
39
63
|
const RULES: DirectiveRule[] = [
|
|
40
64
|
// ESLint
|
|
41
65
|
{ pattern: /^eslint-(?:disable|enable)(?:-next-line|-line)?\b/ },
|
|
@@ -83,6 +107,16 @@ const RULES: DirectiveRule[] = [
|
|
|
83
107
|
{ pattern: /^@deno-types\s*=\s*(?:"[^"\n]+"|'[^'\n]+'|\S+)/i, name: "@deno-types" },
|
|
84
108
|
{ pattern: /^@ts-types\s*=\s*(?:"[^"\n]+"|'[^'\n]+')/i, name: "@ts-types" },
|
|
85
109
|
{ pattern: /^@ts-self-types\s*=\s*(?:"[^"\n]+"|'[^'\n]+')/i, name: "@ts-self-types" },
|
|
110
|
+
// stylelint. A configuration comment is recognised from the first
|
|
111
|
+
// whitespace-delimited token of the trimmed comment body alone (see
|
|
112
|
+
// stylelintDirective), so a glued rule list, a suffix, prose before the
|
|
113
|
+
// marker or a different case leave the comment inert — as does a JSDoc star
|
|
114
|
+
// after `/**`, which postcss keeps as comment text (hence keepStars). `//`
|
|
115
|
+
// comments count too: postcss-scss and postcss-less hand stylelint the same
|
|
116
|
+
// trimmed text. Verified against stylelint 17.15. A project-specific
|
|
117
|
+
// `configurationComment` prefix cannot be known here, so only the default
|
|
118
|
+
// marker is matched.
|
|
119
|
+
{ pattern: /^\S+/, keepStars: true, name: (match) => stylelintDirective(match[0]) },
|
|
86
120
|
// Formatter suppressions (prettier, and oxfmt which mirrors it). Both
|
|
87
121
|
// parsers compare the exact trimmed comment body, so the marker must be the
|
|
88
122
|
// whole comment (joinLines makes `$` span every line): hyphenated
|
|
@@ -307,7 +341,26 @@ const RULES: DirectiveRule[] = [
|
|
|
307
341
|
{ pattern: /^#(?:region|endregion)\b/ },
|
|
308
342
|
];
|
|
309
343
|
|
|
310
|
-
|
|
344
|
+
// Mirrors tsc's tripleSlashXMLCommentStartRegEx: the directive name (matched
|
|
345
|
+
// case-insensitively) must be followed by whitespace and the tag has to close
|
|
346
|
+
// with `/>` — `/// <reference>` and `/// <reference types="node">` are plain
|
|
347
|
+
// comments to the compiler. The AMD directives additionally need their
|
|
348
|
+
// mandatory quoted argument, or tsc drops the pragma altogether.
|
|
349
|
+
const TRIPLE_SLASH = /^\/\/\/\s*<(reference|amd-dependency|amd-module)\s.*?\/>/i;
|
|
350
|
+
const TRIPLE_SLASH_REQUIRED_ARGUMENT: Readonly<Record<string, RegExp>> = {
|
|
351
|
+
"amd-dependency": /\spath\s*=\s*(?:'[^']*'|"[^"]*")/i,
|
|
352
|
+
"amd-module": /\sname\s*=\s*(?:'[^']*'|"[^"]*")/i,
|
|
353
|
+
};
|
|
354
|
+
|
|
355
|
+
/** The canonical triple-slash directive name the line comment carries, if tsc would honour it. */
|
|
356
|
+
function tripleSlashDirective(text: string): string | undefined {
|
|
357
|
+
const match = TRIPLE_SLASH.exec(text);
|
|
358
|
+
if (!match) return undefined;
|
|
359
|
+
const name = (match[1] as string).toLowerCase();
|
|
360
|
+
const requiredArgument = TRIPLE_SLASH_REQUIRED_ARGUMENT[name];
|
|
361
|
+
if (requiredArgument !== undefined && !requiredArgument.test(text)) return undefined;
|
|
362
|
+
return `triple-slash-${name}`;
|
|
363
|
+
}
|
|
311
364
|
|
|
312
365
|
/**
|
|
313
366
|
* Where a comment sits in its file, for directives that are only honoured in
|
|
@@ -373,10 +426,12 @@ function isActiveAt(name: string, placement: DirectivePlacement): boolean {
|
|
|
373
426
|
|
|
374
427
|
// Mirrors the TypeScript compiler's own comment-directive matching, verified
|
|
375
428
|
// against tsc: the suppression directives are case-sensitive PREFIX matches
|
|
376
|
-
// (`@ts-ignoreTODO` is active), while the file-wide check pragmas
|
|
377
|
-
// case-insensitive
|
|
429
|
+
// (`@ts-ignoreTODO` is active), while the file-wide check pragmas go through
|
|
430
|
+
// the case-insensitive pragma parser, whose name runs up to the next
|
|
431
|
+
// whitespace or colon (`@ts-nocheck:reason` is active, `@ts-nocheckfoo` and
|
|
432
|
+
// `@ts-nocheck-foo` are not).
|
|
378
433
|
const TS_LINE_SUPPRESSION = /^\/\/\/?\s*@ts-(ignore|expect-error)/;
|
|
379
|
-
const TS_LINE_CHECK_PRAGMA = /^\/\/\/?\s*@ts-(nocheck|check)\
|
|
434
|
+
const TS_LINE_CHECK_PRAGMA = /^\/\/\/?\s*@ts-(nocheck|check)(?=[^\S\r\n]|:|$)/i;
|
|
380
435
|
// Block comments: only the suppression directives, and only on the comment's
|
|
381
436
|
// literal last line (`*/` included), even when that line is otherwise blank.
|
|
382
437
|
// tsc trims the line and then allows one run of `/`/`*` characters before the
|
|
@@ -396,11 +451,8 @@ const TS_BLOCK_SUPPRESSION = /^\s*[/*]*\s*@ts-(ignore|expect-error)/;
|
|
|
396
451
|
export function detectDirective(kind: CommentKind, text: string, placement?: DirectivePlacement): string | undefined {
|
|
397
452
|
const at = placement ?? ANY_PLACEMENT;
|
|
398
453
|
if (kind === "line") {
|
|
399
|
-
const tripleSlash =
|
|
400
|
-
if (tripleSlash)
|
|
401
|
-
const name = `triple-slash-${tripleSlash[1]}`;
|
|
402
|
-
if (isActiveAt(name, at)) return name;
|
|
403
|
-
}
|
|
454
|
+
const tripleSlash = tripleSlashDirective(text);
|
|
455
|
+
if (tripleSlash !== undefined && isActiveAt(tripleSlash, at)) return tripleSlash;
|
|
404
456
|
const suppression = TS_LINE_SUPPRESSION.exec(text);
|
|
405
457
|
if (suppression) {
|
|
406
458
|
return `@ts-${suppression[1]}`;
|
|
@@ -443,7 +495,9 @@ function* ruleMatches(kind: CommentKind, text: string): Generator<string> {
|
|
|
443
495
|
for (const line of candidates) {
|
|
444
496
|
const match = rule.pattern.exec(line);
|
|
445
497
|
if (!match) continue;
|
|
446
|
-
|
|
498
|
+
const name =
|
|
499
|
+
typeof rule.name === "string" ? rule.name : typeof rule.name === "function" ? rule.name(match) : match[0];
|
|
500
|
+
if (name !== undefined) yield name;
|
|
447
501
|
}
|
|
448
502
|
}
|
|
449
503
|
}
|
|
@@ -479,10 +533,6 @@ export function isLegalComment(text: string): boolean {
|
|
|
479
533
|
return /@(?:license|preserve|copyright)\b/i.test(text);
|
|
480
534
|
}
|
|
481
535
|
|
|
482
|
-
// Every ECMAScript line terminator, the way the scanner breaks lines: CRLF as
|
|
483
|
-
// one break, plus lone LF / CR and the U+2028/U+2029 separators.
|
|
484
|
-
const LINE_BREAK = /\r\n|[\n\r\u2028\u2029]/;
|
|
485
|
-
|
|
486
536
|
/**
|
|
487
537
|
* Non-empty content lines of the comment, with comment markers stripped.
|
|
488
538
|
* For line comments only the `//` marker itself is removed: extra slashes or
|
|
@@ -502,15 +552,9 @@ function contentLines(kind: CommentKind, text: string, keepStars: boolean): stri
|
|
|
502
552
|
? text.replace(/^\/\*/, "").replace(/\*\/\s*$/, "")
|
|
503
553
|
: text.replace(/^\/\*+/, "").replace(/\*+\/\s*$/, "");
|
|
504
554
|
const lines: string[] = [];
|
|
505
|
-
for (const line of inner
|
|
555
|
+
for (const line of splitLines(inner)) {
|
|
506
556
|
const stripped = (kind === "block" && !keepStars ? line.replace(/^\s*\*+\s*/, "") : line).trim();
|
|
507
557
|
if (stripped !== "") lines.push(stripped);
|
|
508
558
|
}
|
|
509
559
|
return lines;
|
|
510
560
|
}
|
|
511
|
-
|
|
512
|
-
/** Literal last line of the comment, closing marker included, exactly as tsc slices it. */
|
|
513
|
-
function lastLine(text: string): string {
|
|
514
|
-
const lines = text.split(LINE_BREAK);
|
|
515
|
-
return lines[lines.length - 1] as string;
|
|
516
|
-
}
|
package/src/files.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
|
-
import type { Stats } from "node:fs";
|
|
2
|
+
import type { Dirent, Stats } from "node:fs";
|
|
3
3
|
import { chmod, open, readFile, readdir, realpath, rename, rm, stat } from "node:fs/promises";
|
|
4
4
|
import { basename, dirname, isAbsolute, join, normalize, relative, resolve, sep } from "node:path";
|
|
5
5
|
import picomatch from "picomatch";
|
|
@@ -19,17 +19,19 @@ export interface CollectOptions {
|
|
|
19
19
|
ignoreDirs?: string[];
|
|
20
20
|
/**
|
|
21
21
|
* Glob patterns for files and directories to skip (picomatch syntax).
|
|
22
|
-
* Patterns without a slash match against base names, e.g. `*.test.ts
|
|
23
|
-
*
|
|
22
|
+
* Patterns without a slash match against base names, e.g. `*.test.ts`;
|
|
23
|
+
* a trailing slash restricts a pattern to directories, e.g. `dist/`, like
|
|
24
|
+
* in .gitignore. Explicitly listed input files bypass these patterns.
|
|
24
25
|
*/
|
|
25
26
|
ignore?: string[];
|
|
26
27
|
}
|
|
27
28
|
|
|
28
|
-
|
|
29
|
+
/** Whether the path (a directory when `isDirectory`) is excluded by the ignore patterns. */
|
|
30
|
+
type IgnoreMatcher = (path: string, root: string, isDirectory: boolean) => boolean;
|
|
29
31
|
|
|
30
32
|
export async function collectFiles(inputs: string[], options: CollectOptions = {}): Promise<string[]> {
|
|
31
33
|
const extensions = normalizeExtensions(options.extensions ?? DEFAULT_EXTENSIONS);
|
|
32
|
-
const ignoreDirs = new Set((options.ignoreDirs ?? DEFAULT_IGNORE_DIRS).map(
|
|
34
|
+
const ignoreDirs = new Set((options.ignoreDirs ?? DEFAULT_IGNORE_DIRS).map(foldPathCase));
|
|
33
35
|
const isIgnored = buildIgnoreMatcher(options.ignore ?? []);
|
|
34
36
|
// Keyed by the real path so different spellings of one file (relative vs
|
|
35
37
|
// absolute, `.` segments, case on Windows, symlink aliases) collapse into a
|
|
@@ -57,7 +59,7 @@ export async function collectFiles(inputs: string[], options: CollectOptions = {
|
|
|
57
59
|
// Directory inputs are themselves subject to the ignored directory
|
|
58
60
|
// names and the ignore patterns; only explicitly listed files bypass
|
|
59
61
|
// them.
|
|
60
|
-
if (!ignoreDirs.has(
|
|
62
|
+
if (!ignoreDirs.has(foldPathCase(basename(input))) && !isIgnored(input, input, true)) {
|
|
61
63
|
await walk(input, { extensions, ignoreDirs, isIgnored, root: input, visited: new Set() }, remember);
|
|
62
64
|
}
|
|
63
65
|
} else {
|
|
@@ -72,33 +74,33 @@ export async function collectFiles(inputs: string[], options: CollectOptions = {
|
|
|
72
74
|
return [...found.values()].sort();
|
|
73
75
|
}
|
|
74
76
|
|
|
77
|
+
/** Identity key of a file: its absolute path, case-folded where the platform compares paths that way. */
|
|
75
78
|
function canonicalKey(path: string): string {
|
|
76
|
-
|
|
77
|
-
// Windows paths are case-insensitive; a case-folded key keeps `Foo.ts` and
|
|
78
|
-
// `foo.ts` from being treated as two files.
|
|
79
|
-
return process.platform === "win32" ? resolved.toLowerCase() : resolved;
|
|
79
|
+
return foldPathCase(resolve(path));
|
|
80
80
|
}
|
|
81
81
|
|
|
82
|
-
/**
|
|
83
|
-
|
|
84
|
-
|
|
82
|
+
/**
|
|
83
|
+
* Folds a path or name the way the platform compares it: Windows paths are
|
|
84
|
+
* case-insensitive (`Foo.ts` and `foo.ts` are one file), everywhere else the
|
|
85
|
+
* spelling is exact.
|
|
86
|
+
*/
|
|
87
|
+
export function foldPathCase(path: string): string {
|
|
88
|
+
return process.platform === "win32" ? path.toLowerCase() : path;
|
|
85
89
|
}
|
|
86
90
|
|
|
87
91
|
async function statInput(input: string): Promise<Stats> {
|
|
88
|
-
|
|
89
|
-
return await stat(input);
|
|
90
|
-
} catch (error) {
|
|
91
|
-
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
|
|
92
|
-
throw new Error(`path not found: ${input}`, { cause: error });
|
|
93
|
-
}
|
|
94
|
-
throw error;
|
|
95
|
-
}
|
|
92
|
+
return withFriendlyNotFound(input, () => stat(input));
|
|
96
93
|
}
|
|
97
94
|
|
|
98
95
|
/** Real path of an explicit input, with the same friendly error statInput gives. */
|
|
99
96
|
async function realpathInput(input: string): Promise<string> {
|
|
97
|
+
return withFriendlyNotFound(input, () => realpath(input));
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Runs the lookup, reporting a missing path under the name the user spelled it with. */
|
|
101
|
+
async function withFriendlyNotFound<T>(input: string, lookup: () => Promise<T>): Promise<T> {
|
|
100
102
|
try {
|
|
101
|
-
return await
|
|
103
|
+
return await lookup();
|
|
102
104
|
} catch (error) {
|
|
103
105
|
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
|
|
104
106
|
throw new Error(`path not found: ${input}`, { cause: error });
|
|
@@ -143,7 +145,13 @@ async function walk(
|
|
|
143
145
|
if (context.visited.has(real)) return;
|
|
144
146
|
context.visited.add(real);
|
|
145
147
|
|
|
146
|
-
|
|
148
|
+
let entries: Dirent[];
|
|
149
|
+
try {
|
|
150
|
+
entries = await readdir(dir, { withFileTypes: true });
|
|
151
|
+
} catch (error) {
|
|
152
|
+
if (isSkippableWalkError(error)) return; // the directory vanished after it resolved
|
|
153
|
+
throw error;
|
|
154
|
+
}
|
|
147
155
|
|
|
148
156
|
await Promise.all(
|
|
149
157
|
entries.map(async (entry) => {
|
|
@@ -163,10 +171,14 @@ async function walk(
|
|
|
163
171
|
}
|
|
164
172
|
}
|
|
165
173
|
if (isDirectory) {
|
|
166
|
-
if (!context.ignoreDirs.has(
|
|
174
|
+
if (!context.ignoreDirs.has(foldPathCase(entry.name)) && !context.isIgnored(full, context.root, true)) {
|
|
167
175
|
await walk(full, context, remember);
|
|
168
176
|
}
|
|
169
|
-
} else if (
|
|
177
|
+
} else if (
|
|
178
|
+
isFile &&
|
|
179
|
+
hasExtension(entry.name, context.extensions) &&
|
|
180
|
+
!context.isIgnored(full, context.root, false)
|
|
181
|
+
) {
|
|
170
182
|
// Remembered under its real path, so several symlinks to one target
|
|
171
183
|
// (or a link plus the target itself) count — and get rewritten — once.
|
|
172
184
|
let realFile: string;
|
|
@@ -195,28 +207,57 @@ function hasExtension(name: string, extensions: string[]): boolean {
|
|
|
195
207
|
return extensions.some((extension) => lower.endsWith(extension));
|
|
196
208
|
}
|
|
197
209
|
|
|
210
|
+
interface IgnorePattern {
|
|
211
|
+
glob: string;
|
|
212
|
+
/** The pattern ended in a slash, so it only excludes directories (`dist/`). */
|
|
213
|
+
directoriesOnly: boolean;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function parseIgnorePattern(pattern: string): IgnorePattern {
|
|
217
|
+
const glob = pattern.replace(/\/+$/, "");
|
|
218
|
+
if (glob === "") {
|
|
219
|
+
// picomatch would reject it with an internal-sounding error; name the input instead.
|
|
220
|
+
throw new Error(`invalid ignore pattern: ${JSON.stringify(pattern)}`);
|
|
221
|
+
}
|
|
222
|
+
return { glob, directoriesOnly: glob !== pattern };
|
|
223
|
+
}
|
|
224
|
+
|
|
198
225
|
function buildIgnoreMatcher(patterns: string[]): IgnoreMatcher {
|
|
199
|
-
|
|
226
|
+
const parsed = patterns.map(parseIgnorePattern);
|
|
227
|
+
if (parsed.length === 0) return () => false;
|
|
200
228
|
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
const
|
|
206
|
-
|
|
207
|
-
if (byBasename.length > 0) matchers.push(picomatch(byBasename, { dot: true, basename: true }));
|
|
208
|
-
if (byPath.length > 0) matchers.push(picomatch(byPath, { dot: true }));
|
|
209
|
-
const match = (path: string): boolean => matchers.some((matcher) => matcher(path));
|
|
229
|
+
const matchesAny = compileGlobs(parsed.filter((pattern) => !pattern.directoriesOnly).map((pattern) => pattern.glob));
|
|
230
|
+
const matchesDirectory = compileGlobs(
|
|
231
|
+
parsed.filter((pattern) => pattern.directoriesOnly).map((pattern) => pattern.glob),
|
|
232
|
+
);
|
|
233
|
+
const match = (path: string, isDirectory: boolean): boolean =>
|
|
234
|
+
matchesAny(path) || (isDirectory && matchesDirectory(path));
|
|
210
235
|
|
|
211
236
|
// Anchored patterns like `src/legacy/**` are tried against the path as
|
|
212
237
|
// spelled, relative to the scanned root, and relative to the working
|
|
213
238
|
// directory, so they work regardless of where the scan was started from.
|
|
214
|
-
return (path, root) => {
|
|
215
|
-
|
|
216
|
-
|
|
239
|
+
return (path, root, isDirectory) => {
|
|
240
|
+
const matches = (candidate: string): boolean => match(candidate, isDirectory);
|
|
241
|
+
if (matches(toPosix(path))) return true;
|
|
242
|
+
return relativeMatches(root, path, matches) || relativeMatches(process.cwd(), path, matches);
|
|
217
243
|
};
|
|
218
244
|
}
|
|
219
245
|
|
|
246
|
+
/**
|
|
247
|
+
* One predicate over gitignore-like globs: patterns without a slash match
|
|
248
|
+
* base names, patterns with a slash match whole paths. (picomatch's
|
|
249
|
+
* `basename` option would apply to every pattern, breaking path globs, so
|
|
250
|
+
* the two groups get separate matchers.)
|
|
251
|
+
*/
|
|
252
|
+
function compileGlobs(globs: string[]): (path: string) => boolean {
|
|
253
|
+
const matchers: Array<(path: string) => boolean> = [];
|
|
254
|
+
const byBasename = globs.filter((glob) => !glob.includes("/"));
|
|
255
|
+
const byPath = globs.filter((glob) => glob.includes("/"));
|
|
256
|
+
if (byBasename.length > 0) matchers.push(picomatch(byBasename, { dot: true, basename: true }));
|
|
257
|
+
if (byPath.length > 0) matchers.push(picomatch(byPath, { dot: true }));
|
|
258
|
+
return (path) => matchers.some((matcher) => matcher(path));
|
|
259
|
+
}
|
|
260
|
+
|
|
220
261
|
function relativeMatches(base: string, path: string, match: (path: string) => boolean): boolean {
|
|
221
262
|
const relativePath = relative(base, path);
|
|
222
263
|
if (relativePath === "" || isAbsolute(relativePath)) return false;
|
|
@@ -231,9 +272,14 @@ function toPosix(path: string): string {
|
|
|
231
272
|
return sep === "/" ? path : path.split(sep).join("/");
|
|
232
273
|
}
|
|
233
274
|
|
|
275
|
+
// TypeScript parses plain JavaScript with the JSX language variant, so `.js`
|
|
276
|
+
// belongs here: read as TS instead, `<div>http://x</div>` in a React file
|
|
277
|
+
// becomes a type assertion followed by a phantom `//x` comment.
|
|
278
|
+
const JSX_EXTENSIONS = [".tsx", ".jsx", ".js", ".mjs", ".cjs"];
|
|
279
|
+
|
|
280
|
+
/** True for files whose syntax admits JSX (`.tsx`, `.jsx` and plain JavaScript), case-insensitively. */
|
|
234
281
|
export function isJsxFile(file: string): boolean {
|
|
235
|
-
|
|
236
|
-
return lower.endsWith(".tsx") || lower.endsWith(".jsx");
|
|
282
|
+
return hasExtension(file, JSX_EXTENSIONS);
|
|
237
283
|
}
|
|
238
284
|
|
|
239
285
|
export type FileEncoding = "utf8" | "utf16le" | "utf16be";
|
|
@@ -259,26 +305,29 @@ export interface FileText {
|
|
|
259
305
|
* editors, GitHub annotations and the removal report.
|
|
260
306
|
*/
|
|
261
307
|
export function decodeFileText(data: Buffer): FileText {
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
encoding = "utf16le";
|
|
267
|
-
bom = true;
|
|
268
|
-
body = data.subarray(2);
|
|
269
|
-
} else if (data.length >= 2 && data[0] === 0xfe && data[1] === 0xff) {
|
|
270
|
-
encoding = "utf16be";
|
|
271
|
-
bom = true;
|
|
272
|
-
body = data.subarray(2);
|
|
273
|
-
} else if (data.length >= 3 && data[0] === 0xef && data[1] === 0xbb && data[2] === 0xbf) {
|
|
274
|
-
bom = true;
|
|
275
|
-
body = data.subarray(3);
|
|
276
|
-
}
|
|
308
|
+
const marked = detectByteOrderMark(data);
|
|
309
|
+
const encoding = marked ?? "utf8";
|
|
310
|
+
const bom = marked !== undefined;
|
|
311
|
+
const body = bom ? data.subarray(BYTE_ORDER_MARKS[encoding].length) : data;
|
|
277
312
|
const text = encoding === "utf16be" ? decodeUtf16Be(body) : body.toString(encoding);
|
|
278
313
|
const lossless = encodeFileText(text, { encoding, bom }).equals(data);
|
|
279
314
|
return { text, encoding, bom, lossless };
|
|
280
315
|
}
|
|
281
316
|
|
|
317
|
+
const BYTE_ORDER_MARKS: Readonly<Record<FileEncoding, Buffer>> = {
|
|
318
|
+
utf8: Buffer.from([0xef, 0xbb, 0xbf]),
|
|
319
|
+
utf16le: Buffer.from([0xff, 0xfe]),
|
|
320
|
+
utf16be: Buffer.from([0xfe, 0xff]),
|
|
321
|
+
};
|
|
322
|
+
|
|
323
|
+
/** The encoding whose byte-order mark opens the data, if any. */
|
|
324
|
+
function detectByteOrderMark(data: Buffer): FileEncoding | undefined {
|
|
325
|
+
return (Object.keys(BYTE_ORDER_MARKS) as FileEncoding[]).find((encoding) => {
|
|
326
|
+
const mark = BYTE_ORDER_MARKS[encoding];
|
|
327
|
+
return data.subarray(0, mark.length).equals(mark);
|
|
328
|
+
});
|
|
329
|
+
}
|
|
330
|
+
|
|
282
331
|
function decodeUtf16Be(body: Buffer): string {
|
|
283
332
|
// swap16() refuses odd-length buffers; drop the dangling byte the same way
|
|
284
333
|
// the LE decoder does and let the lossless round-trip flag the truncation.
|
|
@@ -294,19 +343,8 @@ function decodeUtf16Be(body: Buffer): string {
|
|
|
294
343
|
*/
|
|
295
344
|
export function encodeFileText(text: string, target: { encoding: FileEncoding; bom: boolean }): Buffer {
|
|
296
345
|
const body =
|
|
297
|
-
target.encoding === "utf16le"
|
|
298
|
-
|
|
299
|
-
: target.encoding === "utf16be"
|
|
300
|
-
? Buffer.from(text, "utf16le").swap16()
|
|
301
|
-
: Buffer.from(text, "utf8");
|
|
302
|
-
if (!target.bom) return body;
|
|
303
|
-
const bom =
|
|
304
|
-
target.encoding === "utf16le"
|
|
305
|
-
? Buffer.from([0xff, 0xfe])
|
|
306
|
-
: target.encoding === "utf16be"
|
|
307
|
-
? Buffer.from([0xfe, 0xff])
|
|
308
|
-
: Buffer.from([0xef, 0xbb, 0xbf]);
|
|
309
|
-
return Buffer.concat([bom, body]);
|
|
346
|
+
target.encoding === "utf16be" ? Buffer.from(text, "utf16le").swap16() : Buffer.from(text, target.encoding);
|
|
347
|
+
return target.bom ? Buffer.concat([BYTE_ORDER_MARKS[target.encoding], body]) : body;
|
|
310
348
|
}
|
|
311
349
|
|
|
312
350
|
export async function readFileText(file: string): Promise<FileText> {
|
|
@@ -321,10 +359,11 @@ export async function readFileText(file: string): Promise<FileText> {
|
|
|
321
359
|
*/
|
|
322
360
|
export async function writeFileAtomic(file: string, data: Buffer): Promise<void> {
|
|
323
361
|
const target = await realpath(file);
|
|
324
|
-
|
|
362
|
+
// Permission bits only: stat()'s mode also carries the file-type bits.
|
|
363
|
+
const permissions = (await stat(target)).mode & 0o7777;
|
|
325
364
|
const temp = join(dirname(target), `.${basename(target)}.${randomUUID()}.tmp`);
|
|
326
365
|
try {
|
|
327
|
-
const handle = await open(temp, "wx",
|
|
366
|
+
const handle = await open(temp, "wx", permissions);
|
|
328
367
|
try {
|
|
329
368
|
await handle.writeFile(data);
|
|
330
369
|
await handle.sync();
|
|
@@ -332,7 +371,7 @@ export async function writeFileAtomic(file: string, data: Buffer): Promise<void>
|
|
|
332
371
|
await handle.close();
|
|
333
372
|
}
|
|
334
373
|
// open()'s mode is filtered through the umask; restore the original exactly.
|
|
335
|
-
await chmod(temp,
|
|
374
|
+
await chmod(temp, permissions);
|
|
336
375
|
await rename(temp, target);
|
|
337
376
|
} catch (error) {
|
|
338
377
|
await rm(temp, { force: true }).catch(() => undefined);
|
package/src/git.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { execFile } from "node:child_process";
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
2
3
|
import { realpath } from "node:fs/promises";
|
|
3
4
|
import { resolve } from "node:path";
|
|
4
5
|
import { promisify } from "node:util";
|
|
@@ -56,13 +57,16 @@ async function git(args: string[], cwd: string): Promise<string> {
|
|
|
56
57
|
const { stdout } = await execFileAsync("git", args, { cwd, maxBuffer: MAX_OUTPUT_BYTES });
|
|
57
58
|
return stdout;
|
|
58
59
|
} catch (error) {
|
|
59
|
-
throw new Error(describeFailure(args[0] as string, error), { cause: error });
|
|
60
|
+
throw new Error(describeFailure(args[0] as string, cwd, error), { cause: error });
|
|
60
61
|
}
|
|
61
62
|
}
|
|
62
63
|
|
|
63
|
-
function describeFailure(subcommand: string, error: unknown): string {
|
|
64
|
+
function describeFailure(subcommand: string, cwd: string, error: unknown): string {
|
|
64
65
|
const failure = error as { code?: unknown; stderr?: unknown; message?: unknown };
|
|
65
66
|
if (failure.code === "ENOENT") {
|
|
67
|
+
// spawn reports a missing working directory with the very same error as
|
|
68
|
+
// a missing executable; only the directory check tells them apart.
|
|
69
|
+
if (!existsSync(cwd)) return `directory not found: ${cwd}`;
|
|
66
70
|
return "git executable not found (is git installed and on PATH?)";
|
|
67
71
|
}
|
|
68
72
|
const stderr = typeof failure.stderr === "string" ? failure.stderr.trim() : "";
|
package/src/lines.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Line handling shared by the scanner's consumers. Everything here counts
|
|
3
|
+
* lines the way the TypeScript scanner does: LF, CR, U+2028 and U+2029 each
|
|
4
|
+
* end a line, and CRLF is a single break.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/** Matches one ECMAScript line terminator character. */
|
|
8
|
+
export const LINE_TERMINATOR = /[\n\r\u2028\u2029]/;
|
|
9
|
+
|
|
10
|
+
/** Matches one line break: CRLF as a unit, else any single terminator. */
|
|
11
|
+
export const LINE_BREAK = /\r\n|[\n\r\u2028\u2029]/;
|
|
12
|
+
|
|
13
|
+
/** True when the text holds nothing but whitespace (a byte-order mark included). */
|
|
14
|
+
export function isBlank(text: string): boolean {
|
|
15
|
+
return /^\s*$/.test(text);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Splits on every line break, so exotic terminators never leak into single-line output. */
|
|
19
|
+
export function splitLines(text: string): string[] {
|
|
20
|
+
return text.split(LINE_BREAK);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** The literal last line of the text, exactly as tsc slices a block comment's closing line. */
|
|
24
|
+
export function lastLine(text: string): string {
|
|
25
|
+
const lines = splitLines(text);
|
|
26
|
+
return lines[lines.length - 1] as string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Start offset of every line, numbered the way the scanner numbers them (line 1 starts at index 0). */
|
|
30
|
+
export function lineStartOffsets(source: string): number[] {
|
|
31
|
+
const starts = [0];
|
|
32
|
+
for (let index = 0; index < source.length; index += 1) {
|
|
33
|
+
const char = source[index] as string;
|
|
34
|
+
if (char === "\r") {
|
|
35
|
+
// A CRLF pair is one break: skip the LF so it does not open a second line.
|
|
36
|
+
if (source[index + 1] === "\n") index += 1;
|
|
37
|
+
starts.push(index + 1);
|
|
38
|
+
} else if (char === "\n" || char === "\u2028" || char === "\u2029") {
|
|
39
|
+
starts.push(index + 1);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return starts;
|
|
43
|
+
}
|