@descent-vtt/spec-guard 0.3.0 → 0.4.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/CHANGELOG.md +60 -0
- package/README.md +89 -24
- package/dist/cli.d.ts +2 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +6 -0
- package/dist/cli.js.map +1 -1
- package/dist/engine.d.ts +43 -49
- package/dist/engine.d.ts.map +1 -1
- package/dist/engine.js +162 -254
- package/dist/engine.js.map +1 -1
- package/dist/glob.d.ts +19 -6
- package/dist/glob.d.ts.map +1 -1
- package/dist/glob.js +14 -28
- package/dist/glob.js.map +1 -1
- package/dist/index.d.ts +5 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/reporter.d.ts.map +1 -1
- package/dist/reporter.js +33 -3
- package/dist/reporter.js.map +1 -1
- package/dist/runner.d.ts +12 -3
- package/dist/runner.d.ts.map +1 -1
- package/dist/runner.js +137 -92
- package/dist/runner.js.map +1 -1
- package/dist/scope.d.ts +108 -0
- package/dist/scope.d.ts.map +1 -0
- package/dist/scope.js +115 -0
- package/dist/scope.js.map +1 -0
- package/dist/types.d.ts +13 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +0 -6
- package/dist/types.js.map +1 -1
- package/package.json +1 -1
package/dist/engine.js
CHANGED
|
@@ -1,24 +1,29 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Search engines.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
4
|
+
* There is one set of semantics here, not two. The scanner reads files, counts
|
|
5
|
+
* matches, classifies comments, decides what is binary and keeps the ledger of
|
|
6
|
+
* what it could not inspect. ripgrep answers one question - which files under
|
|
7
|
+
* these targets contain this text at all - and everything downstream of that is
|
|
8
|
+
* the scanner's work, for both engines.
|
|
7
9
|
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
10
|
+
* It was not always so, and the reason for the rewrite is worth keeping: the
|
|
11
|
+
* two used to be independent implementations, and they drifted. On a tree with
|
|
12
|
+
* eight copies of one symbol the scanner found two and ripgrep found four,
|
|
13
|
+
* because one honoured .gitignore and the other did not, one skipped a
|
|
14
|
+
* hardcoded list of directory names and the other did not, and they disagreed
|
|
15
|
+
* about binary files. Nothing in the output said so. See ADR-0007.
|
|
11
16
|
*
|
|
12
17
|
* Both engines expose a batch API. Scanning a tree costs the same whether you
|
|
13
18
|
* look for one symbol or twenty, so assertions that share a target set and
|
|
14
|
-
* flags are answered by a single pass.
|
|
15
|
-
* eight assertions cost ~280ms as eight ripgrep passes and ~90ms as one.
|
|
19
|
+
* flags are answered by a single pass.
|
|
16
20
|
*/
|
|
17
21
|
import { spawn } from 'node:child_process';
|
|
18
22
|
import { promises as fs } from 'node:fs';
|
|
19
23
|
import path from 'node:path';
|
|
20
24
|
import { createCommentMask } from './comments.js';
|
|
21
25
|
import { createExcludeMatcher, createGlobMatcher, toPosix, walkFiles } from './glob.js';
|
|
26
|
+
import { isBinary, LedgerBuilder, MAX_LEDGER_ENTRIES, UNCERTAIN_REASONS, } from './scope.js';
|
|
22
27
|
/** Files larger than this are skipped by both engines, keeping them in sync. */
|
|
23
28
|
export const MAX_FILE_SIZE = 20 * 1024 * 1024;
|
|
24
29
|
/** Hard cap on collected locations; the reporter only ever shows a handful. */
|
|
@@ -32,22 +37,6 @@ function truncate(value) {
|
|
|
32
37
|
const trimmed = value.replace(/\r?\n$/, '');
|
|
33
38
|
return trimmed.length > MAX_SNIPPET_LENGTH ? `${trimmed.slice(0, MAX_SNIPPET_LENGTH)}…` : trimmed;
|
|
34
39
|
}
|
|
35
|
-
/**
|
|
36
|
-
* Converts ripgrep's byte column into a character column.
|
|
37
|
-
*
|
|
38
|
-
* ripgrep counts bytes; the scanner counts characters, and so does every editor
|
|
39
|
-
* that a reader will paste the location into. On an ASCII line the two agree,
|
|
40
|
-
* which is why the difference went unnoticed - it only appears once a line
|
|
41
|
-
* holds a non-ASCII character before the match, and then the two engines report
|
|
42
|
-
* different columns for the same match.
|
|
43
|
-
*/
|
|
44
|
-
export function byteColumnToCharacter(line, byteOffset) {
|
|
45
|
-
// One byte per character, so the offset is already a character count. This
|
|
46
|
-
// also covers the case where ripgrep gave us no line text to measure.
|
|
47
|
-
if (line.length === Buffer.byteLength(line))
|
|
48
|
-
return byteOffset + 1;
|
|
49
|
-
return Buffer.from(line, 'utf8').subarray(0, byteOffset).toString('utf8').length + 1;
|
|
50
|
-
}
|
|
51
40
|
/**
|
|
52
41
|
* Orders matches by path, then by line. ripgrep searches in parallel and emits
|
|
53
42
|
* files in no fixed order, so this is what makes snippet output stable.
|
|
@@ -58,30 +47,6 @@ export function sortLocations(locations) {
|
|
|
58
47
|
function emptyTally() {
|
|
59
48
|
return { count: 0, locations: [], commentCount: 0 };
|
|
60
49
|
}
|
|
61
|
-
/**
|
|
62
|
-
* True when no two of these literals can ever match overlapping text, which is
|
|
63
|
-
* exactly when merging them into one ripgrep alternation is safe.
|
|
64
|
-
*
|
|
65
|
-
* Two ways an alternation loses a match that separate passes would find:
|
|
66
|
-
* containment - ["Primary", "PrimaryButton"] on "PrimaryButton"; and
|
|
67
|
-
* dovetailing - ["abc", "cd"] on "abcd", where the scan resumes past "cd".
|
|
68
|
-
* Rejecting both leaves batching indistinguishable from separate passes.
|
|
69
|
-
*/
|
|
70
|
-
export function canBatchLiterals(patterns) {
|
|
71
|
-
for (const a of patterns) {
|
|
72
|
-
for (const b of patterns) {
|
|
73
|
-
if (a === b)
|
|
74
|
-
continue;
|
|
75
|
-
if (a.includes(b) || b.includes(a))
|
|
76
|
-
return false;
|
|
77
|
-
for (let offset = 1; offset < a.length; offset++) {
|
|
78
|
-
if (b.startsWith(a.slice(offset)))
|
|
79
|
-
return false;
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
}
|
|
83
|
-
return true;
|
|
84
|
-
}
|
|
85
50
|
/** Requests that may share one pass: same root, same targets, same options. */
|
|
86
51
|
function sharesOnePass(requests) {
|
|
87
52
|
const [first] = requests;
|
|
@@ -133,19 +98,43 @@ export function findRipgrep() {
|
|
|
133
98
|
});
|
|
134
99
|
return ripgrepProbe;
|
|
135
100
|
}
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
101
|
+
/**
|
|
102
|
+
* Builds the argv that makes ripgrep walk exactly what the scanner walks.
|
|
103
|
+
*
|
|
104
|
+
* Almost every flag here switches off an opinion. ripgrep's defaults are
|
|
105
|
+
* excellent for a developer grepping their own checkout and wrong for a rule
|
|
106
|
+
* about a repository:
|
|
107
|
+
*
|
|
108
|
+
* --hidden `.github`, `.husky` and `.claude-rules` hold real code, and
|
|
109
|
+
* leaving them out let an absence assertion pass while the
|
|
110
|
+
* forbidden thing sat in a workflow file.
|
|
111
|
+
* --no-ignore .gitignore says what git should carry, not what a rule
|
|
112
|
+
* covers - and it applies only inside a git repository, so the
|
|
113
|
+
* same tree answered differently depending on whether a .git
|
|
114
|
+
* directory happened to exist above it.
|
|
115
|
+
*
|
|
116
|
+
* What remains is spec-guard's own scope policy, passed as exclusions so that
|
|
117
|
+
* both engines skip the same four names for the same reasons. Those come last
|
|
118
|
+
* because ripgrep lets a later glob override an earlier one, and a policy skip
|
|
119
|
+
* must not be undone by a user's `glob="*.ts"`.
|
|
120
|
+
*/
|
|
146
121
|
export function buildRipgrepArgs(request, patterns = [request.symbol]) {
|
|
147
122
|
const { options } = request;
|
|
148
|
-
const args = [
|
|
123
|
+
const args = [
|
|
124
|
+
'--files-with-matches',
|
|
125
|
+
// The only separator a filename cannot contain.
|
|
126
|
+
'--null',
|
|
127
|
+
'--no-config',
|
|
128
|
+
'--hidden',
|
|
129
|
+
'--no-ignore',
|
|
130
|
+
// --text ripgrep treats a file named on the command line as text
|
|
131
|
+
// and a file it walked into as binary, so the same bytes
|
|
132
|
+
// were listed or not depending on how they were reached.
|
|
133
|
+
// The scanner decides what is binary, once, for both
|
|
134
|
+
// engines; ripgrep's job is only to say which files matched.
|
|
135
|
+
'--text',
|
|
136
|
+
`--max-filesize=${MAX_FILE_SIZE}`,
|
|
137
|
+
];
|
|
149
138
|
if (!options.regex)
|
|
150
139
|
args.push('--fixed-strings');
|
|
151
140
|
if (options.word)
|
|
@@ -158,15 +147,35 @@ export function buildRipgrepArgs(request, patterns = [request.symbol]) {
|
|
|
158
147
|
// createExcludeMatcher mirrors for the JavaScript engine.
|
|
159
148
|
for (const glob of options.excludeGlobs)
|
|
160
149
|
args.push('--glob', `!${glob}`);
|
|
150
|
+
for (const name of options.scope.skippedDirectories.keys())
|
|
151
|
+
args.push('--glob', `!${name}/`);
|
|
161
152
|
for (const pattern of patterns)
|
|
162
153
|
args.push('--regexp', pattern);
|
|
163
154
|
args.push('--');
|
|
164
155
|
args.push(...(request.targets.length > 0 ? request.targets : ['.']));
|
|
165
156
|
return args;
|
|
166
157
|
}
|
|
167
|
-
/**
|
|
168
|
-
|
|
169
|
-
|
|
158
|
+
/**
|
|
159
|
+
* ripgrep, used as a pre-filter rather than as a counter.
|
|
160
|
+
*
|
|
161
|
+
* The two engines used to be two implementations of the same semantics, and
|
|
162
|
+
* they drifted: ripgrep honoured .gitignore and the scanner did not, the
|
|
163
|
+
* scanner skipped a hardcoded list of directory names and ripgrep did not, and
|
|
164
|
+
* a binary file was searched by one and skipped by the other. Same tree, two
|
|
165
|
+
* answers, no warning.
|
|
166
|
+
*
|
|
167
|
+
* So ripgrep no longer decides anything. It answers one question - which files
|
|
168
|
+
* under these targets contain this text at all - and the scanner does the rest:
|
|
169
|
+
* counting, comment classification, binary handling, positions, the ledger.
|
|
170
|
+
* There is one implementation of the semantics, and ripgrep supplies the thing
|
|
171
|
+
* it is unmatched at, which is getting from thousands of files down to a
|
|
172
|
+
* handful very quickly.
|
|
173
|
+
*
|
|
174
|
+
* That also removes the batching problem. Attributing a match to the right
|
|
175
|
+
* pattern used to be delicate, because one ripgrep pass over several patterns
|
|
176
|
+
* cannot always say which one matched; as a pre-filter it does not need to,
|
|
177
|
+
* since including a file that turns out not to match is free.
|
|
178
|
+
*/
|
|
170
179
|
class RipgrepEngine {
|
|
171
180
|
binary;
|
|
172
181
|
name = 'ripgrep';
|
|
@@ -174,56 +183,25 @@ class RipgrepEngine {
|
|
|
174
183
|
this.binary = binary;
|
|
175
184
|
}
|
|
176
185
|
async search(request) {
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
return result;
|
|
180
|
-
}
|
|
181
|
-
const tallies = await this.run(request, [request.symbol]);
|
|
182
|
-
return this.toResult(tallies.get(request.symbol));
|
|
186
|
+
const [result] = await this.searchBatch([request]);
|
|
187
|
+
return result;
|
|
183
188
|
}
|
|
184
189
|
async searchBatch(requests) {
|
|
185
190
|
const [first] = requests;
|
|
191
|
+
/* c8 ignore next -- runSearches never passes an empty list */
|
|
186
192
|
if (!first)
|
|
187
193
|
return [];
|
|
188
194
|
const patterns = [...new Set(requests.map((request) => request.symbol))];
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
//
|
|
192
|
-
//
|
|
193
|
-
// then counted by the scanner, which already knows about comments. Both
|
|
194
|
-
// engines therefore produce comment-aware counts through one code path.
|
|
195
|
-
if (first.options.ignoreComments) {
|
|
196
|
-
return this.commentAware(first, patterns, requests);
|
|
197
|
-
}
|
|
198
|
-
if (!shouldBatchPatterns(patterns, first.options)) {
|
|
199
|
-
return Promise.all(requests.map((request) => this.search(request)));
|
|
200
|
-
}
|
|
201
|
-
try {
|
|
202
|
-
const tallies = await this.run(first, patterns);
|
|
203
|
-
return requests.map((request) => this.toResult(tallies.get(request.symbol)));
|
|
204
|
-
}
|
|
205
|
-
catch (error) {
|
|
206
|
-
if (!(error instanceof UnattributableBatch))
|
|
207
|
-
throw error;
|
|
208
|
-
return Promise.all(requests.map((request) => this.search(request)));
|
|
209
|
-
}
|
|
210
|
-
}
|
|
211
|
-
/**
|
|
212
|
-
* Two-phase search, used whenever comments must be classified.
|
|
213
|
-
*
|
|
214
|
-
* The result still names ripgrep: it did the searching, and classification is
|
|
215
|
-
* a post-step both engines share rather than a different engine.
|
|
216
|
-
*/
|
|
217
|
-
async commentAware(request, patterns, requests) {
|
|
218
|
-
const files = await this.filesWithMatches(request, patterns);
|
|
219
|
-
const results = await javascriptEngine.searchFiles(files, requests);
|
|
195
|
+
const { files, unreadable } = await this.filesWithMatches(first, patterns);
|
|
196
|
+
const results = await javascriptEngine.searchFiles(files, requests, unreadable);
|
|
197
|
+
// The result names ripgrep because ripgrep is what searched the tree; the
|
|
198
|
+
// scanner is a shared post-step, not a different engine.
|
|
220
199
|
return results.map((result) => ({ ...result, engine: this.name }));
|
|
221
200
|
}
|
|
222
|
-
/**
|
|
201
|
+
/** Which files contain any of these patterns, and which could not be read. */
|
|
223
202
|
filesWithMatches(request, patterns) {
|
|
224
203
|
return new Promise((resolve, reject) => {
|
|
225
|
-
const
|
|
226
|
-
const child = spawn(this.binary, args, {
|
|
204
|
+
const child = spawn(this.binary, buildRipgrepArgs(request, patterns), {
|
|
227
205
|
cwd: request.root,
|
|
228
206
|
windowsHide: true,
|
|
229
207
|
stdio: ['ignore', 'pipe', 'pipe'],
|
|
@@ -242,153 +220,46 @@ class RipgrepEngine {
|
|
|
242
220
|
return;
|
|
243
221
|
}
|
|
244
222
|
const files = [];
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
223
|
+
// --null separates paths with NUL, which is the only separator a file
|
|
224
|
+
// name cannot contain. Splitting on newlines loses files whose names
|
|
225
|
+
// contain one.
|
|
226
|
+
for (const entry of stdout.split('\0')) {
|
|
227
|
+
if (entry.length === 0)
|
|
248
228
|
continue;
|
|
249
|
-
const absolutePath = path.resolve(request.root,
|
|
229
|
+
const absolutePath = path.resolve(request.root, entry);
|
|
250
230
|
if (request.options.excludeFiles.has(absolutePath))
|
|
251
231
|
continue;
|
|
252
232
|
files.push({ absolutePath, relativePath: toPosix(path.relative(request.root, absolutePath)) });
|
|
253
233
|
}
|
|
254
234
|
files.sort((a, b) => (a.relativePath < b.relativePath ? -1 : 1));
|
|
255
|
-
resolve(files);
|
|
256
|
-
});
|
|
257
|
-
});
|
|
258
|
-
}
|
|
259
|
-
toResult(tally) {
|
|
260
|
-
const resolved = tally ?? emptyTally();
|
|
261
|
-
return {
|
|
262
|
-
count: resolved.count,
|
|
263
|
-
commentMatches: resolved.commentCount,
|
|
264
|
-
unclassifiedFiles: 0,
|
|
265
|
-
matches: sortLocations(resolved.locations),
|
|
266
|
-
engine: this.name,
|
|
267
|
-
};
|
|
268
|
-
}
|
|
269
|
-
/** One ripgrep pass; returns a tally per pattern. */
|
|
270
|
-
run(request, patterns) {
|
|
271
|
-
return new Promise((resolve, reject) => {
|
|
272
|
-
const child = spawn(this.binary, buildRipgrepArgs(request, patterns), {
|
|
273
|
-
cwd: request.root,
|
|
274
|
-
windowsHide: true,
|
|
275
|
-
stdio: ['ignore', 'pipe', 'pipe'],
|
|
276
|
-
});
|
|
277
|
-
const sink = createRipgrepSink(request, patterns);
|
|
278
|
-
let pending = '';
|
|
279
|
-
let stderr = '';
|
|
280
|
-
child.stdout.setEncoding('utf8');
|
|
281
|
-
child.stdout.on('data', (chunk) => {
|
|
282
|
-
pending += chunk;
|
|
283
|
-
let newline = pending.indexOf('\n');
|
|
284
|
-
while (newline !== -1) {
|
|
285
|
-
sink.line(pending.slice(0, newline));
|
|
286
|
-
pending = pending.slice(newline + 1);
|
|
287
|
-
newline = pending.indexOf('\n');
|
|
288
|
-
}
|
|
289
|
-
});
|
|
290
|
-
child.stderr.setEncoding('utf8');
|
|
291
|
-
child.stderr.on('data', (chunk) => {
|
|
292
|
-
stderr += chunk;
|
|
293
|
-
});
|
|
294
|
-
child.once('error', reject);
|
|
295
|
-
child.once('close', (code) => {
|
|
296
|
-
sink.line(pending);
|
|
297
|
-
if (sink.failure) {
|
|
298
|
-
reject(sink.failure);
|
|
299
|
-
return;
|
|
300
|
-
}
|
|
301
|
-
// 0 = matches, 1 = no matches, 2 = an actual failure.
|
|
302
|
-
if (code !== 0 && code !== 1) {
|
|
303
|
-
reject(new Error(`ripgrep exited with code ${code}${stderr ? `: ${stderr.trim()}` : ''}`));
|
|
304
|
-
return;
|
|
305
|
-
}
|
|
306
|
-
resolve(sink.tallies);
|
|
235
|
+
resolve({ files, unreadable: parseRipgrepErrors(stderr) });
|
|
307
236
|
});
|
|
308
237
|
});
|
|
309
238
|
}
|
|
310
239
|
}
|
|
311
240
|
/**
|
|
312
|
-
*
|
|
241
|
+
* Pulls the paths out of ripgrep's stderr.
|
|
313
242
|
*
|
|
314
|
-
*
|
|
315
|
-
*
|
|
316
|
-
*
|
|
317
|
-
*
|
|
318
|
-
*/
|
|
319
|
-
export function shouldBatchPatterns(patterns, options) {
|
|
320
|
-
if (patterns.length <= 1)
|
|
321
|
-
return false;
|
|
322
|
-
if (options.regex || options.ignoreCase)
|
|
323
|
-
return false;
|
|
324
|
-
return canBatchLiterals(patterns);
|
|
325
|
-
}
|
|
326
|
-
/**
|
|
327
|
-
* Parses ripgrep's newline-delimited JSON into per-pattern tallies.
|
|
243
|
+
* `--no-messages` used to be passed, which threw these away: a file ripgrep
|
|
244
|
+
* could not open produced no match, no error and no difference from a file that
|
|
245
|
+
* was searched and found clean. ripgrep writes one line per failure, as
|
|
246
|
+
* `path: reason`, and the path is what the report needs.
|
|
328
247
|
*
|
|
329
|
-
*
|
|
330
|
-
*
|
|
331
|
-
* unattributable match - is trivial to exercise as data and nearly impossible
|
|
332
|
-
* to provoke from a real ripgrep on demand.
|
|
248
|
+
* Anything that does not parse is returned as-is rather than dropped, on the
|
|
249
|
+
* principle that an unexplained line from a subprocess is still information.
|
|
333
250
|
*/
|
|
334
|
-
export function
|
|
335
|
-
const
|
|
336
|
-
const
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
}
|
|
347
|
-
catch {
|
|
348
|
-
return;
|
|
349
|
-
}
|
|
350
|
-
if (event.type !== 'match' || !event.data)
|
|
351
|
-
return;
|
|
352
|
-
const data = event.data;
|
|
353
|
-
const submatches = data.submatches ?? [];
|
|
354
|
-
if (submatches.length === 0)
|
|
355
|
-
return;
|
|
356
|
-
// ripgrep echoes the path as given ("./src/a.ts" when the target is
|
|
357
|
-
// "."); normalise so both engines report the same relative path.
|
|
358
|
-
const absolute = path.resolve(request.root, decodeText(data.path));
|
|
359
|
-
if (request.options.excludeFiles.has(absolute))
|
|
360
|
-
return;
|
|
361
|
-
const file = toPosix(path.relative(request.root, absolute));
|
|
362
|
-
const lineNumber = data.line_number ?? 0;
|
|
363
|
-
const lineText = decodeText(data.lines);
|
|
364
|
-
const text_ = truncate(lineText);
|
|
365
|
-
for (const submatch of submatches) {
|
|
366
|
-
// With --fixed-strings and no --ignore-case the matched text is the
|
|
367
|
-
// pattern verbatim, which is what makes attribution exact.
|
|
368
|
-
const pattern = single ?? decodeText(submatch.match);
|
|
369
|
-
const tally = tallies.get(pattern);
|
|
370
|
-
if (!tally) {
|
|
371
|
-
sink.failure = new UnattributableBatch(`ripgrep reported an unexpected match: ${pattern}`);
|
|
372
|
-
return;
|
|
373
|
-
}
|
|
374
|
-
tally.count += 1;
|
|
375
|
-
const last = tally.locations.at(-1);
|
|
376
|
-
if (last && last.file === file && last.line === lineNumber) {
|
|
377
|
-
last.count += 1;
|
|
378
|
-
}
|
|
379
|
-
else if (tally.locations.length < MAX_COLLECTED_MATCHES) {
|
|
380
|
-
tally.locations.push({
|
|
381
|
-
file,
|
|
382
|
-
line: lineNumber,
|
|
383
|
-
column: byteColumnToCharacter(lineText, submatch.start ?? 0),
|
|
384
|
-
text: text_,
|
|
385
|
-
count: 1,
|
|
386
|
-
});
|
|
387
|
-
}
|
|
388
|
-
}
|
|
389
|
-
},
|
|
390
|
-
};
|
|
391
|
-
return sink;
|
|
251
|
+
export function parseRipgrepErrors(stderr) {
|
|
252
|
+
const paths = [];
|
|
253
|
+
for (const raw of stderr.split(/\r?\n/)) {
|
|
254
|
+
const line = raw.trim();
|
|
255
|
+
if (line.length === 0)
|
|
256
|
+
continue;
|
|
257
|
+
// "rg: " prefixes ripgrep's own diagnostics rather than a file's.
|
|
258
|
+
const body = line.startsWith('rg: ') ? line.slice(4) : line;
|
|
259
|
+
const separator = body.indexOf(': ');
|
|
260
|
+
paths.push(separator === -1 ? body : body.slice(0, separator));
|
|
261
|
+
}
|
|
262
|
+
return paths;
|
|
392
263
|
}
|
|
393
264
|
/* --------------------------------------------------------------- javascript */
|
|
394
265
|
/** Builds the matching RegExp shared by the JS engine. */
|
|
@@ -402,14 +273,6 @@ export function buildJsRegExp(symbol, options) {
|
|
|
402
273
|
const source = options.word ? `(?<![\\p{L}\\p{N}_])(?:${escaped})(?![\\p{L}\\p{N}_])` : escaped;
|
|
403
274
|
return new RegExp(source, `${flags}u`);
|
|
404
275
|
}
|
|
405
|
-
function isProbablyBinary(buffer) {
|
|
406
|
-
const limit = Math.min(buffer.length, 8192);
|
|
407
|
-
for (let index = 0; index < limit; index++) {
|
|
408
|
-
if (buffer[index] === 0)
|
|
409
|
-
return true;
|
|
410
|
-
}
|
|
411
|
-
return false;
|
|
412
|
-
}
|
|
413
276
|
class JavaScriptEngine {
|
|
414
277
|
name = 'javascript';
|
|
415
278
|
async search(request) {
|
|
@@ -425,14 +288,25 @@ class JavaScriptEngine {
|
|
|
425
288
|
const [first] = requests;
|
|
426
289
|
if (!first)
|
|
427
290
|
return [];
|
|
428
|
-
const
|
|
429
|
-
return this.searchFiles(files, requests);
|
|
291
|
+
const enumeration = await enumerateCandidates(first);
|
|
292
|
+
return this.searchFiles(enumeration.files, requests, [], enumeration.skipped);
|
|
430
293
|
}
|
|
431
|
-
/**
|
|
432
|
-
|
|
294
|
+
/**
|
|
295
|
+
* Scans an already-enumerated file list.
|
|
296
|
+
*
|
|
297
|
+
* `unreadable` carries paths a caller already knows it could not open -
|
|
298
|
+
* ripgrep reports those on stderr, and they belong in the same ledger as the
|
|
299
|
+
* ones this scanner discovers for itself.
|
|
300
|
+
*/
|
|
301
|
+
async searchFiles(files, requests, unreadable = [], skipped = []) {
|
|
433
302
|
const [first] = requests;
|
|
434
303
|
if (!first)
|
|
435
304
|
return [];
|
|
305
|
+
const ledger = new LedgerBuilder();
|
|
306
|
+
for (const entry of skipped)
|
|
307
|
+
ledger.add(entry.path, entry.reason, entry.matches);
|
|
308
|
+
for (const entry of unreadable)
|
|
309
|
+
ledger.add(entry, 'unreadable');
|
|
436
310
|
const patterns = [...new Set(requests.map((request) => request.symbol))];
|
|
437
311
|
const regexps = new Map(patterns.map((pattern) => [pattern, buildJsRegExp(pattern, first.options)]));
|
|
438
312
|
const tallies = new Map(patterns.map((pattern) => [pattern, emptyTally()]));
|
|
@@ -447,8 +321,12 @@ class JavaScriptEngine {
|
|
|
447
321
|
if (!file)
|
|
448
322
|
return;
|
|
449
323
|
const buffer = await fs.readFile(file.absolutePath).catch(() => null);
|
|
450
|
-
if (!buffer
|
|
324
|
+
if (!buffer) {
|
|
325
|
+
// A file we cannot open might hold anything, so it is recorded rather
|
|
326
|
+
// than passed over as though it had been read and found clean.
|
|
327
|
+
ledger.add(file.relativePath, 'unreadable');
|
|
451
328
|
continue;
|
|
329
|
+
}
|
|
452
330
|
const content = buffer.toString('utf8');
|
|
453
331
|
let mask;
|
|
454
332
|
const getMask = first.options.ignoreComments
|
|
@@ -458,6 +336,21 @@ class JavaScriptEngine {
|
|
|
458
336
|
for (const [pattern, regexp] of regexps) {
|
|
459
337
|
scanned.set(pattern, scanContent(content, file.relativePath, regexp, getMask));
|
|
460
338
|
}
|
|
339
|
+
if (isBinary(buffer)) {
|
|
340
|
+
// Searched, but not counted. Skipping binary files silently was a way
|
|
341
|
+
// to pass an assertion by never looking; searching them and saying
|
|
342
|
+
// what was found leaves the decision with the reader.
|
|
343
|
+
//
|
|
344
|
+
// Only a binary file that *did* contain the symbol goes in the
|
|
345
|
+
// ledger. One that did not is not a gap - it was read, searched and
|
|
346
|
+
// found clean - and leaving it out is also what keeps the two engines
|
|
347
|
+
// reporting the same thing, since ripgrep only ever hands the scanner
|
|
348
|
+
// files that matched.
|
|
349
|
+
const found = [...scanned.values()].reduce((total, tally) => total + tally.count, 0);
|
|
350
|
+
if (found > 0)
|
|
351
|
+
ledger.add(file.relativePath, 'binary', found);
|
|
352
|
+
continue;
|
|
353
|
+
}
|
|
461
354
|
// A mask exists only if some pattern matched, since that is the only
|
|
462
355
|
// thing that calls getMask - so reaching here already means this file
|
|
463
356
|
// matched and its language was not understood.
|
|
@@ -482,6 +375,7 @@ class JavaScriptEngine {
|
|
|
482
375
|
}
|
|
483
376
|
}
|
|
484
377
|
}
|
|
378
|
+
const scope = ledger.build();
|
|
485
379
|
return requests.map((request) => {
|
|
486
380
|
const tally = tallies.get(request.symbol) ?? emptyTally();
|
|
487
381
|
return {
|
|
@@ -489,14 +383,11 @@ class JavaScriptEngine {
|
|
|
489
383
|
commentMatches: tally.commentCount,
|
|
490
384
|
unclassifiedFiles,
|
|
491
385
|
matches: tally.locations,
|
|
386
|
+
scope,
|
|
492
387
|
engine: this.name,
|
|
493
388
|
};
|
|
494
389
|
});
|
|
495
390
|
}
|
|
496
|
-
/** Every file a request should look at, sorted by relative path. */
|
|
497
|
-
async collectFiles(request) {
|
|
498
|
-
return (await enumerateCandidates(request)).files;
|
|
499
|
-
}
|
|
500
391
|
}
|
|
501
392
|
/**
|
|
502
393
|
* Lists the files a request would search, sorted by relative path.
|
|
@@ -511,6 +402,18 @@ export async function enumerateCandidates(request, budget) {
|
|
|
511
402
|
const excluded = createExcludeMatcher(request.options.excludeGlobs);
|
|
512
403
|
const admits = (relativePath) => matcher(relativePath) && !excluded(relativePath);
|
|
513
404
|
const found = new Map();
|
|
405
|
+
const skipped = [];
|
|
406
|
+
const note = (relativePath, reason) => {
|
|
407
|
+
// Only gaps go in the ledger. `.git` and `node_modules` are configuration,
|
|
408
|
+
// not news: they are the same on every run, they are documented, and
|
|
409
|
+
// reporting them each time would bury the entries that do mean something.
|
|
410
|
+
// It also keeps the two engines' ledgers identical, since ripgrep is only
|
|
411
|
+
// ever asked about files it did not skip.
|
|
412
|
+
if (!UNCERTAIN_REASONS.has(reason))
|
|
413
|
+
return;
|
|
414
|
+
if (skipped.length < MAX_LEDGER_ENTRIES)
|
|
415
|
+
skipped.push({ path: relativePath, reason });
|
|
416
|
+
};
|
|
514
417
|
let bytes = 0;
|
|
515
418
|
let exceeded = false;
|
|
516
419
|
const admit = (absolutePath, relativePath, size) => {
|
|
@@ -535,7 +438,12 @@ export async function enumerateCandidates(request, budget) {
|
|
|
535
438
|
}
|
|
536
439
|
continue;
|
|
537
440
|
}
|
|
538
|
-
|
|
441
|
+
const prefix = toPosix(path.relative(request.root, absoluteTarget));
|
|
442
|
+
const walkOptions = {
|
|
443
|
+
scope: request.options.scope,
|
|
444
|
+
onSkip: (relativePath, reason) => note(prefix ? `${prefix}/${relativePath}` : relativePath, reason),
|
|
445
|
+
};
|
|
446
|
+
for await (const file of walkFiles(absoluteTarget, walkOptions)) {
|
|
539
447
|
if (file.size > MAX_FILE_SIZE)
|
|
540
448
|
continue;
|
|
541
449
|
const relativePath = toPosix(path.relative(request.root, file.absolutePath));
|
|
@@ -548,7 +456,7 @@ export async function enumerateCandidates(request, budget) {
|
|
|
548
456
|
for (const excluded of request.options.excludeFiles)
|
|
549
457
|
found.delete(excluded);
|
|
550
458
|
const files = [...found.values()].sort((a, b) => (a.relativePath < b.relativePath ? -1 : 1));
|
|
551
|
-
return { files, exceeded, bytes };
|
|
459
|
+
return { files, exceeded, bytes, skipped };
|
|
552
460
|
}
|
|
553
461
|
/** Counts matches in one file and records per-line snippets. */
|
|
554
462
|
export function scanContent(content, relativePath, regexp,
|