@veda-hq/pariksha 0.5.17 → 0.5.18

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.
@@ -0,0 +1,762 @@
1
+ // masked-exit-codes: a gate must be able to fail.
2
+ //
3
+ // A check that keeps reporting success after it stopped checking is the most
4
+ // dangerous defect a repository's tooling can have: a hook that runs a commit
5
+ // message linter and then `exit 0`, a review step whose every failure reads
6
+ // as "no issues found", a baseline read with `2>/dev/null || true`. Each
7
+ // produces a green run, precisely where it matters.
8
+ //
9
+ // `|| true` is legitimate in plenty of places (probing for an optional tool,
10
+ // tolerating "no matches" from grep), so this does not ban it. It flags only
11
+ // the shapes that silence a real verdict:
12
+ //
13
+ // 1. `exit 0` at the end of a script that ran a gate, with no branch on
14
+ // that gate's status;
15
+ // 2. `|| true`, a handler that does not exit non-zero, or `2>/dev/null`
16
+ // with the status unchecked, applied to a gate command (the config's
17
+ // `gateCommands`: a linter, test runner, validator or reviewer);
18
+ // 3. in a file under `pipefailScope`, `echo`/`printf` of a variable piped
19
+ // into a reader that stops early (`grep -q`, `-m`, `-l`, `head`), which
20
+ // under pipefail reads a match as a miss and skips the check it gates.
21
+ import { execFileSync } from 'node:child_process';
22
+ import { readFileSync } from 'node:fs';
23
+ import { join } from 'node:path';
24
+ import { splitAndOrLists, splitSegmentsWithSeparators, substitutionBodies, tokenize } from "./shell-command.js";
25
+ export const DEFAULT_GATE_COMMANDS = ['eslint', 'tsc', 'vitest', 'prettier --check', 'commitlint', 'cubic review', 'gitleaks', 'actionlint', 'shellcheck', 'depcruise', 'stryker'];
26
+ export const DEFAULT_MASKED_CONFIG = {
27
+ id: 'masked-exit-codes',
28
+ gateCommands: DEFAULT_GATE_COMMANDS,
29
+ hookDirs: ['.husky/'],
30
+ pipefailScope: [/^\.husky\//],
31
+ };
32
+ const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
33
+ const KEYS = ['id', 'gateCommands', 'hookDirs', 'pipefailScope'];
34
+ /**
35
+ * `{ "id"?: "<label>", "gateCommands"?: ["<command>", …], "hookDirs"?:
36
+ * ["<path prefix>", …], "pipefailScope"?: ["<regex>", …] }`; absent keys
37
+ * take the defaults. Throws on anything else, so a mistyped key never passes
38
+ * as the default.
39
+ */
40
+ export const parseMaskedConfig = (text) => {
41
+ let raw;
42
+ try {
43
+ raw = JSON.parse(text);
44
+ }
45
+ catch (e) {
46
+ throw new Error(`not JSON: ${e.message}`);
47
+ }
48
+ if (!isRecord(raw))
49
+ throw new Error('the config must be a JSON object');
50
+ const unknown = Object.keys(raw).find((k) => !KEYS.includes(k));
51
+ if (unknown !== undefined)
52
+ throw new Error(`unknown key "${unknown}"`);
53
+ const id = raw['id'] ?? DEFAULT_MASKED_CONFIG.id;
54
+ if (typeof id !== 'string' || id.trim() === '')
55
+ throw new Error('"id" must be a non-empty string');
56
+ const list = (key, fallback, what) => {
57
+ const value = raw[key] ?? fallback;
58
+ if (!Array.isArray(value) || value.some((entry) => typeof entry !== 'string' || entry.trim() === ''))
59
+ throw new Error(`"${key}" must be a list of ${what}`);
60
+ return value;
61
+ };
62
+ const gateCommands = list('gateCommands', DEFAULT_MASKED_CONFIG.gateCommands, 'commands');
63
+ if (gateCommands.length === 0)
64
+ throw new Error('"gateCommands" names no command, so nothing would be checked');
65
+ const hookDirs = list('hookDirs', DEFAULT_MASKED_CONFIG.hookDirs, 'path prefixes');
66
+ const scope = list('pipefailScope', DEFAULT_MASKED_CONFIG.pipefailScope.map((r) => r.source), 'regexes').map((source) => {
67
+ try {
68
+ return new RegExp(source);
69
+ }
70
+ catch (e) {
71
+ throw new Error(`"pipefailScope" holds a bad regex: ${e.message}`);
72
+ }
73
+ });
74
+ return { id, gateCommands, hookDirs, pipefailScope: scope };
75
+ };
76
+ /** Files git tracks under `root` that are shell scripts (`*.sh`) or under a hook directory. */
77
+ export const shellFiles = (root, config = DEFAULT_MASKED_CONFIG) => execFileSync('git', ['ls-files', '-z'], { cwd: root, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 })
78
+ .split('\0')
79
+ .filter(Boolean)
80
+ .filter((path) => path.endsWith('.sh') || config.hookDirs.some((prefix) => path.startsWith(prefix)))
81
+ .filter((path) => !path.includes('/node_modules/'));
82
+ /** Whether the line is a comment, or an echo or printf. */
83
+ const isCommentary = (line) => {
84
+ const trimmed = line.trim();
85
+ return trimmed.startsWith('#') || trimmed.startsWith('echo ') || trimmed.startsWith('printf ');
86
+ };
87
+ /** An exit status word: digits, `$?` or a variable, quoted or not. */
88
+ const EXIT_STATUS = String.raw `\d+|'\d+'|"\d+"|"?\$\?"?|"?\$\{?[A-Za-z_]\w*\}?"?`;
89
+ /**
90
+ * Whether this list hands the gate's failure onward rather than swallow it.
91
+ * `|| exit 1`, `|| exit '1'` and a bare `|| exit` do; `|| exit 0` converts a
92
+ * failure into a success, so it is a mask. The exit must end its command:
93
+ * `|| exit 1 | cat` and `|| exit 1 &` run it in a subshell, while
94
+ * redirections after the status (`|| exit 1 2>&1`) still end the command.
95
+ * `|| false` leaves the list failed, so `set -e` still sees the failure.
96
+ */
97
+ const propagatesFailure = (line, { falseKeeps = true } = {}) => {
98
+ // Each redirection starts after whitespace and its target holds no `<`/`>`,
99
+ // so the repetition has one way to match (no exponential backtracking).
100
+ const handler = new RegExp(String.raw `^\|\|\s*(?:(?:exit|return)\b(?:\s+(${EXIT_STATUS}))?|false\b)(?:\s+\d*(?:>>?|<)&?\s*[^\s;&|)}#<>]+)*(?=\s*(?:$|;|&&|\|\||\)|\}|#))`);
101
+ // Only the first handler runs on a failure: in `eslint . || echo failed
102
+ // || exit 1` echo succeeds and the exit never runs. `false` fails, so the
103
+ // handler after it runs too: `|| false || echo ok` ends in echo's success,
104
+ // so a `false` keeps the list failed only as its last handler.
105
+ const starts = handlerStarts(line);
106
+ for (const at of starts) {
107
+ const match = handler.exec(line.slice(at));
108
+ if (match === null)
109
+ return false;
110
+ if (/^\|\|\s*false\b/.test(match[0])) {
111
+ if (falseKeeps && at === starts.at(-1))
112
+ return true;
113
+ continue;
114
+ }
115
+ // A bare `exit` and `exit $?` hand on the gate's own, non-zero, status.
116
+ const status = match[1];
117
+ return status === undefined || failingStatus(status, { lastIsGate: true });
118
+ }
119
+ return false;
120
+ };
121
+ /** The handler a failure reaches first (past any `|| false`), if any. */
122
+ const firstHandler = (list) => handlerStarts(list)
123
+ .map((at) => list.slice(at))
124
+ .find((rest) => !/^\|\|\s*false\b/.test(rest));
125
+ /**
126
+ * One piece of an and-or list as `handlerStarts` reads it: an escaped
127
+ * character, a quoted string (open to the end of the list when unclosed;
128
+ * `\` escapes only inside double quotes), an `||`, or any other character.
129
+ */
130
+ const LIST_PIECE = /\\[\s\S]?|'[^']*'?|"(?:\\[\s\S]?|[^"\\])*"?|\|\||[\s\S]/g;
131
+ /**
132
+ * Where each top-level `||` of an and-or list starts: outside quotes and
133
+ * outside `( … )`, `{ … }` and `$( … )`, whose own `||` handle their own
134
+ * commands, and outside `${ … }`, whose `||` is text. A `)` with nothing
135
+ * open (a `case` arm's) closes nothing.
136
+ */
137
+ export const handlerStarts = (list) => {
138
+ const starts = [];
139
+ let depth = 0;
140
+ for (const { 0: piece, index } of list.matchAll(LIST_PIECE)) {
141
+ if (piece === '(' || piece === '{')
142
+ depth += 1;
143
+ else if ((piece === ')' || piece === '}') && depth > 0)
144
+ depth -= 1;
145
+ else if (piece === '||' && depth === 0)
146
+ starts.push(index);
147
+ }
148
+ return starts;
149
+ };
150
+ /**
151
+ * Whether `exit STATUS` hands on a failure. A number must be non-zero, quoted
152
+ * or not; `$?` is the gate's status only when nothing ran in between; a
153
+ * variable counts when `before` (the handler up to the exit) sets it from
154
+ * `$?` as its first command (`{ status=$?; echo failed; exit "$status"; }`).
155
+ */
156
+ const failingStatus = (status, { before, lastIsGate }) => {
157
+ const bare = status.replace(/^(["'])(.*)\1$/, '$2');
158
+ if (/^\d+$/.test(bare))
159
+ return !/^0+$/.test(bare);
160
+ if (bare === '$?')
161
+ return lastIsGate;
162
+ const name = /^\$\{?(\w+)\}?$/.exec(bare)?.[1];
163
+ if (name === undefined || before === undefined)
164
+ return false;
165
+ // The only assignment must be the handler's first command: `$?` is the
166
+ // status of whatever ran last, so in `{ echo failed; status=$?; … }` it is
167
+ // echo's 0, and `status=$?; status=0` exits 0 too.
168
+ const assignments = [...before.matchAll(new RegExp(String.raw `(?:^|[\s;{])${name}=`, 'g'))];
169
+ return assignments.length === 1 && new RegExp(String.raw `^\s*${name}=(["']?)\$\?\1(?:\s*;|\s|$)`).test(before);
170
+ };
171
+ /** The and-or list from the command that runs `gate` on, cut from the list's own text so its redirections stay as written. */
172
+ const fromGate = (list, gate) => {
173
+ let cursor = 0;
174
+ for (const segment of splitSegmentsWithSeparators(list)) {
175
+ const at = list.indexOf(segment.text, cursor);
176
+ if (at < 0)
177
+ return list;
178
+ if (invokedAt(segment.text, gate))
179
+ return list.slice(at);
180
+ cursor = at + segment.text.length;
181
+ }
182
+ return list;
183
+ };
184
+ /**
185
+ * A `{ …; exit N; }` handler propagates when its exit hands on a failure and
186
+ * the group ends its command: piped or backgrounded, it runs in a subshell.
187
+ */
188
+ const braceHandlerPropagates = (list) => {
189
+ // A redirection may follow the status (`exit 1 >&2`), and a bare `exit`
190
+ // hands on `$?`: the gate's own status when nothing ran before it.
191
+ const group = new RegExp(String.raw `^\|\|\s*\{([^}]*)\b(?:exit|return)(?:\s+(${EXIT_STATUS}))?(?:\s+\d*[<>]{1,2}&?[^\s;}]+)*\s*;?\s*\}(?=\s*(?:$|;|&&|\|\||\)|\}|#))`);
192
+ // The first handler that runs: past any `|| false`, which fails on.
193
+ for (const at of handlerStarts(list)) {
194
+ const rest = list.slice(at);
195
+ if (/^\|\|\s*false\b/.test(rest))
196
+ continue;
197
+ const match = group.exec(rest);
198
+ if (match === null)
199
+ return false;
200
+ const before = match[1];
201
+ const status = match[2];
202
+ // The exit must be a command of its own, first in the group or after a
203
+ // `;` that ends a list. In `{ echo exit 1; }` it is echo's argument, in
204
+ // `{ false && exit 1; }` a condition can skip it, and `{ echo | exit 1; }`
205
+ // exits a pipeline subshell.
206
+ if (!/(?:^|;)\s*$/.test(before))
207
+ return false;
208
+ return failingStatus(status ?? '$?', { before, lastIsGate: before.trim() === '' });
209
+ }
210
+ return false;
211
+ };
212
+ /**
213
+ * Whether `command` is invoked here, at a command position (line start, or
214
+ * after `$(`, `(`, `{`, a pipe, `&&`, `;`, `then`, `do` or `if`, optionally
215
+ * negated with `!`), not merely named in an argument: `grep -n "eslint ."`
216
+ * searches for the string. Runners that forward to the
217
+ * real command count (`npx`, `pnpm exec`, `bash script.sh`), as do
218
+ * `NAME=value` prefixes and any relative directory before the command.
219
+ */
220
+ const invokedAt = (line, command) => {
221
+ // The whole command must appear (`prettier --check`, not any prettier).
222
+ if (!line.includes(command))
223
+ return false;
224
+ const head = command.split(' ')[0];
225
+ const escaped = head.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
226
+ const RUNNER = String.raw `(?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)*` + String.raw `(?:(?:npx|pnpm|npm|yarn|bunx|exec|run|--yes|-y|dlx|bash|sh|zsh)\s+)*` + String.raw `(?:[\w.-]+/)*`;
227
+ // `!` is a command position only directly after a real separator: alone it
228
+ // also matched a `!` used as an argument (`grep ! file eslint`).
229
+ const pattern = new RegExp(`(^|\\$\\(|\\(|\\{|\\||&&|;|\\bthen\\b|\\bdo\\b|\\bif\\b)\\s*!?\\s*${RUNNER}${escaped}(\\s|$)`);
230
+ // A quoted occurrence is an argument, not an invocation.
231
+ return pattern.test(withoutQuotedText(line));
232
+ };
233
+ const SHELL = /^(?:ba|z|da)?sh$/;
234
+ /** Words that precede a command without being it. `(` and `{` need no entry: `fromCommand` strips them from the word they open. */
235
+ const LEADING = new Set(['if', 'then', 'do', 'else', 'elif', 'while', 'until', '!', 'time', 'command', 'exec', 'builtin', 'nohup', 'env']);
236
+ /** A segment's words from its command word on, quotes removed. */
237
+ const fromCommand = (segment) => {
238
+ const tokens = tokenize(segment)
239
+ // `(eval …)`: the command starts inside the opener.
240
+ .map((token) => (token.quoted ? token : { ...token, value: token.value.replace(/^[({]+/, '') }))
241
+ .filter((token) => token.quoted || token.value !== '');
242
+ const start = tokens.findIndex((token) => token.quoted || !(LEADING.has(token.value) || /^[A-Za-z_]\w*=/.test(token.value)));
243
+ return start < 0 ? [] : tokens.slice(start);
244
+ };
245
+ /** A command word without its directory: `/bin/sh` is `sh`. */
246
+ const commandName = (word) => word.value.replace(/^.*\//, '');
247
+ /**
248
+ * The scripts this command runs as shell text, or 'stdin' for a shell that
249
+ * reads its program from a pipe. `eval` runs its arguments joined by spaces;
250
+ * `sh -c` runs its first operand only (later ones are `$0`, `$1`); a shell
251
+ * given a file runs committed code this check reads on its own.
252
+ */
253
+ const scriptsOf = (words) => {
254
+ const [head, ...rest] = words;
255
+ // A quoted command word still names the command: `'eval' …` runs eval.
256
+ if (head === undefined)
257
+ return [];
258
+ const name = commandName(head);
259
+ if (name === 'eval')
260
+ return [rest.map((word) => word.value).join(' ')];
261
+ if (!SHELL.test(name))
262
+ return [];
263
+ let command = false;
264
+ for (let index = 0; index < rest.length; index += 1) {
265
+ const word = rest[index];
266
+ if (!word.quoted && /^[-+]o$/.test(word.value)) {
267
+ index += 1; // `-o pipefail`: the option's value is no operand
268
+ continue;
269
+ }
270
+ if (!word.quoted && /^[-+][a-zA-Z]+$/.test(word.value)) {
271
+ if (word.value.startsWith('-') && word.value.includes('c'))
272
+ command = true;
273
+ continue;
274
+ }
275
+ // The first operand: the program under -c, otherwise a script file.
276
+ return command ? [word.value] : [];
277
+ }
278
+ return command ? [] : 'stdin';
279
+ };
280
+ /** The value of digits a pattern already matched in base `radix`. */
281
+ const digitsValue = (digits, radix) => {
282
+ let value = 0;
283
+ for (const digit of digits.toLowerCase())
284
+ value = value * radix + '0123456789abcdef'.indexOf(digit);
285
+ return value;
286
+ };
287
+ /** The named escapes printf decodes in its format and in a `%b` argument. */
288
+ const PRINTF_NAMED = {
289
+ a: '\u0007',
290
+ b: '\b',
291
+ e: '\u001b',
292
+ E: '\u001b',
293
+ f: '\f',
294
+ n: '\n',
295
+ r: '\r',
296
+ t: '\t',
297
+ v: '\v',
298
+ '\\': '\\',
299
+ };
300
+ /**
301
+ * printf's backslash escapes as bash decodes them. Both places decode the
302
+ * named escapes, `\xH`/`\xHH`, `\uHHHH` and `\UHHHHHHHH`, keeping the
303
+ * backslash of any other. In the format octal is one to three digits
304
+ * (`\0101` is `\010` then `1`) and `\"`, `\'`, `\?` drop theirs; in a `%b`
305
+ * argument octal is `\0` and up to three digits or `\NNN`, those three keep
306
+ * theirs, and `\c` ends all output.
307
+ */
308
+ const printfEscapes = (text, where) => {
309
+ const octal = where === 'format' ? '[0-7]{1,3}' : '0[0-7]{0,3}|[1-7][0-7]{0,2}';
310
+ const escape = new RegExp(String.raw `\\(?:x([\da-fA-F]{1,2})|u([\da-fA-F]{1,4})|U([\da-fA-F]{1,8})|(${octal})|([^]))`, 'g');
311
+ let out = '';
312
+ let last = 0;
313
+ for (const match of text.matchAll(escape)) {
314
+ out += text.slice(last, match.index);
315
+ last = match.index + match[0].length;
316
+ const hex = match[1] ?? match[2] ?? match[3];
317
+ const char = match[5];
318
+ if (where === 'argument' && char === 'c')
319
+ return { text: out, stop: true };
320
+ if (hex !== undefined) {
321
+ const code = digitsValue(hex, 16);
322
+ // Past Unicode bash writes no character; keep the escape as written.
323
+ out += code > 0x10ffff ? match[0] : String.fromCodePoint(code);
324
+ }
325
+ else if (char === undefined) {
326
+ // Bash keeps the low eight bits: `\455` is `-`.
327
+ out += String.fromCharCode(digitsValue(match[4], 8) & 0xff);
328
+ }
329
+ else {
330
+ out += PRINTF_NAMED[char] ?? (where === 'format' && `"'?`.includes(char) ? char : match[0]);
331
+ }
332
+ }
333
+ return { text: out + text.slice(last), stop: false };
334
+ };
335
+ /**
336
+ * What `printf FORMAT ARGS…` writes, for `%s`, `%b` and `%%` with every
337
+ * escape decoded; null for any other directive, which the caller reads word
338
+ * by word instead. The format is reused while arguments remain, as printf
339
+ * does, and a `\c` in a `%b` argument ends the output there.
340
+ */
341
+ export const renderPrintf = (words) => {
342
+ const [format, ...args] = words[0] === '--' ? words.slice(1) : words;
343
+ // No format: printf fails and writes nothing a shell could run.
344
+ if (format === undefined)
345
+ return null;
346
+ // Text and directives alternate; text with any other `%` is a directive
347
+ // this reader does not render. An escape writes `%` (`\045`) as text.
348
+ const pieces = format.split(/(%[sb%])/);
349
+ if (pieces.some((piece, index) => index % 2 === 0 && piece.includes('%')))
350
+ return null;
351
+ let rest = [...args];
352
+ let out = '';
353
+ for (;;) {
354
+ let used = 0;
355
+ for (const piece of pieces) {
356
+ if (piece === '%%')
357
+ out += '%';
358
+ else if (piece === '%s') {
359
+ out += rest[used] ?? '';
360
+ used += 1;
361
+ }
362
+ else if (piece === '%b') {
363
+ const value = printfEscapes(rest[used] ?? '', 'argument');
364
+ used += 1;
365
+ out += value.text;
366
+ if (value.stop)
367
+ return out;
368
+ }
369
+ else
370
+ out += printfEscapes(piece, 'format').text;
371
+ }
372
+ rest = rest.slice(used);
373
+ if (used === 0 || rest.length === 0)
374
+ break;
375
+ }
376
+ return out;
377
+ };
378
+ /**
379
+ * What `echo WORDS…` writes: its words after any `-n`/`-e`/`-E` options,
380
+ * joined, then the same text with `-e`'s escapes decoded. Both are read,
381
+ * since `sh`'s own echo (dash, or bash under xpg_echo) decodes them unasked.
382
+ */
383
+ const renderEcho = (words) => {
384
+ const text = words.join(' ').replace(/^(?:-[neE]+(?: |$))*/, '');
385
+ return `${text}\n${printfEscapes(text, 'argument').text}`;
386
+ };
387
+ /**
388
+ * The line, plus every script in it that a shell will run: the argument of
389
+ * `eval`, of `bash -c`, or what `echo`/`printf` pipes straight into a stdin
390
+ * shell. Only an `eval` or shell at a command position counts: `echo eval
391
+ * 'eslint . || true'` prints its text and runs nothing. Any other stage
392
+ * piped into a shell (`grep -v eslint`, `sed`, `cat file`) transforms or
393
+ * reads text this check cannot see, so nothing is read for it.
394
+ */
395
+ export const executedTexts = (line, depth = 0) => {
396
+ if (depth > 3)
397
+ return [line];
398
+ const segments = splitSegmentsWithSeparators(line);
399
+ const scripts = segments.flatMap((segment, index) => {
400
+ const run = scriptsOf(fromCommand(segment.text));
401
+ if (run !== 'stdin')
402
+ return run;
403
+ const source = index === 0 ? undefined : segments[index - 1];
404
+ if (source === undefined || source.next !== '|')
405
+ return [];
406
+ const [head, ...words] = fromCommand(source.text);
407
+ if (head === undefined)
408
+ return [];
409
+ const name = commandName(head);
410
+ if (!['echo', 'printf'].includes(name))
411
+ return [];
412
+ // What the stage writes is the program: printf fills its format (reused
413
+ // while arguments remain), echo joins its words. A printf format this
414
+ // reader cannot render falls back to each quoted word as a program.
415
+ // Each line written is a program; a blank one runs nothing.
416
+ const values = words.map((token) => token.value);
417
+ const written = name === 'printf' ? renderPrintf(values) : renderEcho(values);
418
+ if (written !== null)
419
+ return written.split('\n');
420
+ return words.filter((token) => token.quoted).map((token) => token.value);
421
+ });
422
+ // A substitution's body is judged as part of the line (so a capture the
423
+ // line then branches on stays exempt), but the scripts it hands a shell run
424
+ // too: `echo $(printf … | sh)` and `x=$(sh -c '…')`.
425
+ const nested = substitutionBodies(line)
426
+ .filter((body) => body !== line)
427
+ .flatMap((body) => executedTexts(body, depth + 1).slice(1));
428
+ return [line, ...scripts.flatMap((text) => executedTexts(text, depth + 1)), ...nested];
429
+ };
430
+ /**
431
+ * Backslash-continued lines joined into the single command they are. The
432
+ * marker is dropped and the pieces joined with a space, so `cmd \` +
433
+ * ` || true` becomes `cmd || true`; the line number is the first physical
434
+ * line's, where a reader looks for the command reported.
435
+ */
436
+ export const foldContinuations = (lines) => {
437
+ const folded = [];
438
+ let pending = null;
439
+ let start = 0;
440
+ lines.forEach((raw, index) => {
441
+ const continues = /\\\s*$/.test(raw);
442
+ const body = continues ? raw.replace(/\\\s*$/, '') : raw;
443
+ if (pending === null) {
444
+ pending = body;
445
+ start = index + 1;
446
+ }
447
+ else {
448
+ pending = `${pending} ${body.trim()}`;
449
+ }
450
+ if (!continues) {
451
+ folded.push({ text: pending, line: start });
452
+ pending = null;
453
+ }
454
+ });
455
+ // A file ending mid-continuation still has a command worth checking.
456
+ if (pending !== null)
457
+ folded.push({ text: pending, line: start });
458
+ return folded;
459
+ };
460
+ /**
461
+ * `VAR=$(gate ... || true)` moves the verdict into the variable, which the
462
+ * script then branches on: a wrapper that captures a linter's output and
463
+ * inspects it. Not a masked exit, but only if a later line reads the value to
464
+ * decide with; a capture nothing reads discards the verdict as `|| true` does.
465
+ */
466
+ const isCaptureThenBranch = (line, later) => {
467
+ const capture = /^\s*([A-Za-z_][A-Za-z0-9_]*)=\$\(/.exec(line);
468
+ if (capture === null)
469
+ return false;
470
+ const referenced = new RegExp(`\\$\\{?${capture[1]}\\b`);
471
+ const decides = /\bif\b|\bcase\b|\btest\b|\[|\]|&&|\|\||\bexit\b|\breturn\b/;
472
+ return later.some((next) => referenced.test(next) && decides.test(next));
473
+ };
474
+ /** Whether `path` runs under pipefail, so shape 3 holds it: the config's `pipefailScope`. */
475
+ export const isPipefailScoped = (path, config = DEFAULT_MASKED_CONFIG) => config.pipefailScope.some((scope) => scope.test(path));
476
+ /**
477
+ * Bash writes `echo`/`printf` output one line per write. A reader that stops
478
+ * at its first match exits while lines are still coming; the next write gets
479
+ * EPIPE, pipefail takes the writer's status, and `if` reads "no match". The
480
+ * pipe buffer is no protection: a list past 64 KB misses on every call.
481
+ */
482
+ const VARIABLE_FEED = /\b(?:echo|printf)\b[^|;&]*\$[^|;&]*\|(?!\|)\s*(grep|head)\b([^|;&)]*)/;
483
+ /** grep's long options that stop reading early, with or without `=value`. */
484
+ const EARLY_EXIT_LONG = /^--(?:quiet|silent|max-count|files-with(?:out)?-match(?:es)?)(?:=|$)/;
485
+ /** Options whose value is the next token when not attached (`-e PAT`). */
486
+ const VALUE_LONG = /^--(?:regexp|file|max-count|context|after-context|before-context)$/;
487
+ /**
488
+ * Whether this grep stops at its first match. Options are read the way GNU
489
+ * grep permutes them, so `grep a --quiet` counts, but an option's value is
490
+ * skipped: `grep -e -missing` has the pattern `-missing`, not `-m`.
491
+ */
492
+ const grepStopsEarly = (args) => {
493
+ const tokens = args.trim().split(/\s+/).filter(Boolean);
494
+ for (let index = 0; index < tokens.length; index += 1) {
495
+ const token = tokens[index];
496
+ if (token === '--')
497
+ return false;
498
+ if (token.startsWith('--')) {
499
+ if (EARLY_EXIT_LONG.test(token))
500
+ return true;
501
+ if (VALUE_LONG.test(token))
502
+ index += 1;
503
+ continue;
504
+ }
505
+ if (!token.startsWith('-'))
506
+ continue;
507
+ // A cluster's flags run up to its first value-taking flag; what follows
508
+ // is that flag's value (`-emissing`), or, when nothing does, the next
509
+ // token is (`-e -missing`). A lone `-` (stdin) has no flags at all.
510
+ const flags = token.slice(1);
511
+ const valueFlag = flags.search(/[efABC]/);
512
+ const own = valueFlag < 0 ? flags : flags.slice(0, valueFlag);
513
+ if (/[qmlL]/.test(own))
514
+ return true;
515
+ if (valueFlag >= 0 && valueFlag === flags.length - 1)
516
+ index += 1;
517
+ }
518
+ return false;
519
+ };
520
+ /**
521
+ * `gate || rc=$?` saves the gate's failing status for a later line to decide
522
+ * with: `if [ "$rc" -ne 0 ]; then exit "$rc"; fi`. Exempt only when a later
523
+ * line reads it and exits with the failure, and only on failure: under
524
+ * `[ "$rc" -ne 0 ]` (then, `&&`), or after `[ "$rc" -eq 0 ] ||` / in the
525
+ * `else` of an `-eq 0` test. `exit 0`, a bare `exit` and `echo "$rc"` carry
526
+ * on; any other condition (`(( rc ))`, a `case`) is not read, and reports;
527
+ * a reassignment of the variable ends the search.
528
+ */
529
+ const savesStatusThenBranches = (list, later) => {
530
+ const handler = firstHandler(list);
531
+ if (handler === undefined)
532
+ return false;
533
+ const saved = /^\|\|\s*([A-Za-z_]\w*)=(["']?)\$[?]\2\s*(?:;\s*)?$/.exec(handler);
534
+ if (saved === null)
535
+ return false;
536
+ const name = saved[1];
537
+ const referenced = new RegExp(`\\$\\{?${name}\\b`);
538
+ const reassigned = new RegExp(`(?:^|[\\s;&|])${name}=`);
539
+ const failing = new RegExp(`\\b(?:exit|return)\\s+(?:["']?\\$\\{?${name}\\b|["']?0*[1-9]\\d*["']?(?![\\w$]))`);
540
+ const operand = String.raw `["']?\$\{?${name}[^\s"'\]]*["']?\s*`;
541
+ const zero = String.raw `\s*["']?0["']?(?![\w$])`;
542
+ const failureTest = new RegExp(`${operand}(?:-ne|-gt|!=)${zero}`);
543
+ const successTest = new RegExp(`${operand}(?:-eq|==?)${zero}`);
544
+ const blockEnd = /(?:^|[\s;])(?:fi|esac)\b/;
545
+ /** Whether this one line exits with the failure, and only on failure. */
546
+ const exitsOnFailure = (text) => {
547
+ const at = failing.exec(text)?.index;
548
+ if (at === undefined)
549
+ return false;
550
+ const head = text.slice(0, at);
551
+ if (!failureTest.test(head) && !successTest.test(head)) {
552
+ // No test of the status: the exit is unconditional, or under a
553
+ // condition this reader does not judge.
554
+ return !/\bif\b|&&|\|\||\bcase\b/.test(head);
555
+ }
556
+ if (/\bif\b/.test(head))
557
+ return failureTest.test(head) ? /\bthen\b/.test(head) && !/\belse\b/.test(head) : /\belse\b/.test(head);
558
+ const operator = /(&&|\|\|)\s*$/.exec(head)?.[1];
559
+ return failureTest.test(head) ? operator === '&&' : operator === '||';
560
+ };
561
+ for (const [index, reader] of later.entries()) {
562
+ if (reassigned.test(reader))
563
+ return false;
564
+ if (!referenced.test(reader))
565
+ continue;
566
+ if (exitsOnFailure(reader))
567
+ return true;
568
+ if (!/\bif\b/.test(reader) || blockEnd.test(reader))
569
+ continue;
570
+ // A multi-line `if`: the failing branch is `then` under a failure test,
571
+ // `else` under a success test.
572
+ const onFailure = failureTest.test(reader) ? 'then' : successTest.test(reader) ? 'else' : null;
573
+ if (onFailure === null)
574
+ continue;
575
+ let branch = 'then';
576
+ for (const next of later.slice(index + 1)) {
577
+ if (/^\s*(?:else|elif)\b/.test(next))
578
+ branch = 'else';
579
+ else if (branch === onFailure && failing.test(next))
580
+ return true;
581
+ if (reassigned.test(next))
582
+ return false;
583
+ if (blockEnd.test(next))
584
+ break;
585
+ }
586
+ }
587
+ return false;
588
+ };
589
+ const isEarlyExitFeed = (line) => {
590
+ const feed = VARIABLE_FEED.exec(withoutQuotedText(line));
591
+ if (feed === null)
592
+ return false;
593
+ return feed[1] === 'head' || grepStopsEarly(feed[2]);
594
+ };
595
+ /**
596
+ * Quoted text collapsed so a `|` inside a pattern is not read as a pipe: a
597
+ * double-quoted string becomes `"$"` when it expands something and `""` when
598
+ * not, a single-quoted one `''`, and an escaped character (`\$`, `\|`,
599
+ * literal in shell) `_`.
600
+ */
601
+ export const withoutQuotedText = (line) => line.replace(/"((?:[^"\\]|\\.)*)"|'[^']*'|\\./g, (match, inner) => {
602
+ if (inner === undefined)
603
+ return match.startsWith('\\') ? '_' : "''";
604
+ const expands = inner.split(/\\./).some((part) => part.includes('$'));
605
+ return expands ? '"$"' : '""';
606
+ });
607
+ const findEarlyExitFeeds = (relative, logical, config) => {
608
+ if (!isPipefailScoped(relative, config))
609
+ return [];
610
+ return logical
611
+ .filter(({ text }) => !text.trim().startsWith('#'))
612
+ .filter(({ text }) => isEarlyExitFeed(text))
613
+ .map(({ text, line }) => ({
614
+ file: relative,
615
+ line,
616
+ snippet: text.trim(),
617
+ reason: 'a variable piped into a reader that stops early: under pipefail the writer can hit EPIPE after the match, and the check reads it as a miss. Feed it a here-string: `grep -q … <<<"$VAR"`',
618
+ }));
619
+ };
620
+ /** Absent only on ENOENT; ENOTDIR, EACCES, EISDIR and the rest throw. */
621
+ export const readWorkingTree = (root, relative) => {
622
+ try {
623
+ return readFileSync(join(root, relative), 'utf8');
624
+ }
625
+ catch (error) {
626
+ if (error.code === 'ENOENT')
627
+ return null;
628
+ throw error;
629
+ }
630
+ };
631
+ /**
632
+ * The blob the commit will record. Pre-commit must judge this, not the
633
+ * working tree: a clean unstaged edit would otherwise hide the staged one.
634
+ * Absent only when the index has no entry; a failing `git show` throws.
635
+ * `env` defaults to the process's own, which carries `GIT_INDEX_FILE` for a
636
+ * partial commit.
637
+ */
638
+ export const stagedReader = (env = process.env) => {
639
+ const git = (root, args) => execFileSync('git', args, { cwd: root, encoding: 'utf8', env, maxBuffer: 64 * 1024 * 1024 });
640
+ return (root, relative) => {
641
+ if (git(root, ['ls-files', '--cached', '-z', '--', relative]) === '')
642
+ return null;
643
+ return git(root, ['show', `:${relative}`]);
644
+ };
645
+ };
646
+ /** `--staged` judges the index; otherwise, the working tree. */
647
+ export const readerFor = (staged) => (staged ? stagedReader() : readWorkingTree);
648
+ /** Every masked exit in `files` (paths under `root`), each file read with `read`. */
649
+ export const findMaskedExits = (root, files, read = readWorkingTree, config = DEFAULT_MASKED_CONFIG) => {
650
+ const problems = [];
651
+ for (const relative of files) {
652
+ const source = read(root, relative);
653
+ if (source === null)
654
+ continue; // deleted between listing and reading
655
+ const lines = source.split('\n');
656
+ // Logical lines, not physical ones: a trailing `\` puts a mask on the
657
+ // next physical line while leaving it the same shell command.
658
+ const logical = foldContinuations(lines);
659
+ problems.push(...findEarlyExitFeeds(relative, logical, config));
660
+ const maskedGate = (line, lineNumber, gate, later) => {
661
+ // The and-or lists that run the gate, from the gate on: its handlers
662
+ // live there, and an unrelated list's `|| exit 1` or `|| true` says
663
+ // nothing about it. In `grep -q x f || eslint .` the `||` runs eslint
664
+ // as the fallback, and eslint's own failure is still the list's.
665
+ const own = splitAndOrLists(line)
666
+ .filter((list) => invokedAt(list, gate))
667
+ .map((list) => fromGate(list, gate))
668
+ .filter((list) => !savesStatusThenBranches(list, later));
669
+ // `|| true` on a gate discards its verdict outright, as the handler a
670
+ // failure reaches, not inside a handler's own group.
671
+ if (own.some((list) => {
672
+ const handler = firstHandler(list);
673
+ return handler !== undefined && /^\|\|\s*true\b/.test(handler);
674
+ })) {
675
+ problems.push({ file: relative, line: lineNumber, snippet: line.trim(), reason: `\`${gate}\` is a gate, but \`|| true\` discards its exit status — the check reports success whatever it found` });
676
+ return true;
677
+ }
678
+ // `gate || <handler>` where the handler neither exits nor returns
679
+ // non-zero carries on as if the gate passed: `|| echo failed`, `|| :`,
680
+ // and `|| exit 1 | cat`, whose exit runs in a pipeline subshell.
681
+ if (own.some((list) => /\|\|/.test(list) && !propagatesFailure(list) && !braceHandlerPropagates(list))) {
682
+ problems.push({ file: relative, line: lineNumber, snippet: line.trim(), reason: `\`${gate}\` fails into an \`||\` handler that does not exit non-zero — the script carries on as if it passed` });
683
+ return true;
684
+ }
685
+ // `cmd 2>/dev/null` with no status branch hides the failure reason and,
686
+ // with `set +e`, the failure itself. `|| exit 1` (or a bare `exit`)
687
+ // propagates the failure and is no mask; `|| exit 0` forces success and
688
+ // is; `|| false` checks nothing without `set -e`.
689
+ if (!/\$\?/.test(line) && !/if\s/.test(line) && own.some((list) => /2>\s*\/dev\/null/.test(list) && !propagatesFailure(list, { falseKeeps: false }))) {
690
+ problems.push({ file: relative, line: lineNumber, snippet: line.trim(), reason: `\`${gate}\` has its stderr discarded and its status unchecked — a crash is indistinguishable from a pass` });
691
+ return true;
692
+ }
693
+ return false;
694
+ };
695
+ const maskOn = (line, lineNumber, index) => {
696
+ // Every gate on the line is judged: `eslint . || exit 1; tsc || true`
697
+ // still masks tsc.
698
+ const gates = config.gateCommands.filter((command) => invokedAt(line, command));
699
+ if (gates.length === 0)
700
+ return false;
701
+ const later = logical.slice(index + 1).map((entry) => entry.text);
702
+ // The verdict survives in a variable the script goes on to test.
703
+ if (isCaptureThenBranch(line, later))
704
+ return false;
705
+ return gates.some((gate) => maskedGate(line, lineNumber, gate, later));
706
+ };
707
+ logical.forEach(({ text: whole, line: lineNumber }, index) => {
708
+ // Only a comment is skipped whole: `echo start; eslint . || true`
709
+ // masks its gate, and `invokedAt` already refuses a gate that is only
710
+ // echo's argument.
711
+ if (whole.trim().startsWith('#'))
712
+ return;
713
+ // The line as written, then any quoted script it runs; one report each.
714
+ for (const line of executedTexts(whole)) {
715
+ if (maskOn(line, lineNumber, index))
716
+ return;
717
+ }
718
+ });
719
+ // An `exit 0` on the line after a gate, with nothing branching on the
720
+ // result: the script always succeeds, whatever the gate decided.
721
+ lines.forEach((line, index) => {
722
+ if (!/^\s*exit\s+0\s*$/.test(line))
723
+ return;
724
+ for (let back = index - 1; back >= 0 && back >= index - 4; back--) {
725
+ const previous = lines[back];
726
+ if (previous.trim() === '' || isCommentary(previous))
727
+ continue;
728
+ // A bare `STATUS=$?` records the status without acting on it, so the
729
+ // gate above it is still the thing being masked.
730
+ if (/^\s*\w+=\$\?\s*$/.test(previous))
731
+ continue;
732
+ const gate = config.gateCommands.find((command) => invokedAt(previous, command));
733
+ if (gate !== undefined && !/\|\||&&|if\s|\$\?|exit\s+1/.test(previous)) {
734
+ problems.push({
735
+ file: relative,
736
+ line: index + 1,
737
+ snippet: `${previous.trim()} → ${line.trim()}`,
738
+ reason: `unconditional \`exit 0\` right after \`${gate}\` — the script always succeeds, whatever the gate decided`,
739
+ });
740
+ }
741
+ break;
742
+ }
743
+ });
744
+ }
745
+ return problems;
746
+ };
747
+ /** The report and exit code for `problems` among `scanned` files: 0 clean, 1 masked exits or no files. */
748
+ export const formatMasked = (problems, scanned, id) => {
749
+ if (scanned === 0) {
750
+ // Fail closed: finding no shell files at all means the lookup broke, not
751
+ // that the repository has none.
752
+ return { ok: false, out: [], err: [`❌ ${id}: no shell files found — the file lookup failed`] };
753
+ }
754
+ if (problems.length > 0) {
755
+ const err = [`\n❌ ${id}: ${String(problems.length)} masked exit code(s)\n`];
756
+ for (const p of problems)
757
+ err.push(` ${p.file}:${String(p.line)}`, ` ${p.snippet}`, ` ${p.reason}\n`);
758
+ err.push('A gate that cannot fail is not a gate. Branch on the status, or drop the check.\n');
759
+ return { ok: false, out: [], err };
760
+ }
761
+ return { ok: true, out: [`✅ ${id}: no masked exit codes (${String(scanned)} shell file(s) scanned)`], err: [] };
762
+ };