@veda-hq/pariksha 0.5.14 → 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.
- package/NOTICE +6 -0
- package/README.md +290 -5
- package/dist/absolute-paths.js +59 -0
- package/dist/aggregate-gate-needs.js +153 -0
- package/dist/cli.js +152 -1
- package/dist/doc-files.js +74 -0
- package/dist/hook-preamble.js +343 -0
- package/dist/masked-exit-codes.js +762 -0
- package/dist/non-synced-resources.js +164 -0
- package/dist/pnpm-settings.js +350 -0
- package/dist/semver-range.js +320 -0
- package/dist/shell-command.js +425 -0
- package/dist/shell-gates.js +283 -0
- package/dist/shell-pitfalls.js +408 -0
- package/dist/shell-sources.js +165 -0
- package/dist/shell-text.js +417 -22
- package/package.json +4 -3
package/dist/cli.js
CHANGED
|
@@ -4,9 +4,16 @@ import { execFileSync } from 'node:child_process';
|
|
|
4
4
|
import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs';
|
|
5
5
|
import { join, relative, resolve } from 'node:path';
|
|
6
6
|
import { fileURLToPath } from 'node:url';
|
|
7
|
+
import { checkAbsolutePaths, DEFAULT_GUIDANCE as ABSOLUTE_PATHS_GUIDANCE } from "./absolute-paths.js";
|
|
8
|
+
import { checkGates, DEFAULT_GATE_CONFIG, parseGateConfig as parseAggregateConfig } from "./aggregate-gate-needs.js";
|
|
9
|
+
import { parseDocConfig, readDoc, selectDocs } from "./doc-files.js";
|
|
10
|
+
import { DEFAULT_MASKED_CONFIG, findMaskedExits, formatMasked, parseMaskedConfig, readerFor as maskedReaderFor, shellFiles } from "./masked-exit-codes.js";
|
|
11
|
+
import { checkNonSyncedResources, DEFAULT_GUIDANCE as NON_SYNCED_GUIDANCE } from "./non-synced-resources.js";
|
|
12
|
+
import { ALL_CHECKS as SHELL_CHECKS, parseGatesConfig, runShellGates, shellcheckRunner } from "./shell-gates.js";
|
|
13
|
+
import { checkPnpmSettings, DEFAULT_PNPM_CONFIG, formatParity, parsePnpmConfig } from "./pnpm-settings.js";
|
|
7
14
|
import { adrDirOf, DEFAULTS, findUncited, formatClaims, listAdrs, readOrUndefined, stagedSource, treeSource } from "./authority-citations.js";
|
|
8
15
|
import { findDenied, hash, isText, parseDenyList } from "./boundary.js";
|
|
9
|
-
import { DEFAULT_CONFIG, findGaps, formatGaps, listedPaths, parseConfig, treePaths } from "./coverage-by-type.js";
|
|
16
|
+
import { DEFAULT_CONFIG, entries, findGaps, formatGaps, listedPaths, parseConfig, treePaths } from "./coverage-by-type.js";
|
|
10
17
|
import { checkBuild, checkPackage, checkVitest, formatViolations, loaderFailure, loadVitestExclude, missingConfigs, ownedBy, parseConfig as parseExemptions } from "./coverage-exemptions.js";
|
|
11
18
|
import { checkBudgets } from "./doc-budgets.js";
|
|
12
19
|
import { lycheeRunner } from "./doc-links.js";
|
|
@@ -25,6 +32,8 @@ import { checkClaims, formatOutcome, loadEslint, parseConfig as parseClaimsConfi
|
|
|
25
32
|
export const DENY_FILE = '.veda/deny.sha256';
|
|
26
33
|
const USAGE = [
|
|
27
34
|
'usage: pariksha authority-citations [--mode staged|tree] [--authority <a,b>] [--issue-prefix <A,B>] [--adr-dir <dir>] [--root <dir>]',
|
|
35
|
+
' pariksha absolute-paths [--config <file>] [--files-from <file>|-] [--root <dir>]',
|
|
36
|
+
' pariksha aggregate-gate-needs [--config <file>] [--root <dir>]',
|
|
28
37
|
' pariksha boundary [--root <dir>] [--deny <file>]',
|
|
29
38
|
' pariksha codec-registry --config <file> [--base <ref> | --no-base] [--root <dir>]',
|
|
30
39
|
' pariksha coverage-by-type [--config <file>] [--files-from <file>|-] [--root <dir>]',
|
|
@@ -35,7 +44,11 @@ const USAGE = [
|
|
|
35
44
|
' pariksha env-gate-switches --config <file> [--mode staged|tree] [--root <dir>]',
|
|
36
45
|
' pariksha export-deletions [--base <ref>] [--root <dir>]',
|
|
37
46
|
' pariksha fault-injection-registry --config <file> [--base <ref> | --no-base] [--root <dir>]',
|
|
47
|
+
' pariksha masked-exit-codes [--config <file>] [--staged] [--root <dir>]',
|
|
48
|
+
' pariksha non-synced-resources [--config <file>] [--files-from <file>|-] [--root <dir>]',
|
|
49
|
+
' pariksha pnpm-settings [--config <file>] [--root <dir>]',
|
|
38
50
|
' pariksha required-settings --require <file> [--settings <file>] [--root <dir>]',
|
|
51
|
+
' pariksha shell-gates [--config <file>] [--staged | --all | --base <ref> | --files-from <file>|-] [--only <checks>] [--root <dir>]',
|
|
39
52
|
' pariksha hash <word>',
|
|
40
53
|
' pariksha --version',
|
|
41
54
|
].join('\n');
|
|
@@ -81,6 +94,138 @@ export const flags = (rest, allowed, switches = []) => {
|
|
|
81
94
|
}
|
|
82
95
|
return out;
|
|
83
96
|
};
|
|
97
|
+
/**
|
|
98
|
+
* absolute-paths and non-synced-resources: the documents `--files-from`
|
|
99
|
+
* lists (a file, or `-` for stdin), or every tracked one, each path read
|
|
100
|
+
* from `--root`; the report goes to stdout, as the shell checks printed it.
|
|
101
|
+
*/
|
|
102
|
+
const docCheck = (name, defaultGuidance, check) => (f, io) => {
|
|
103
|
+
const P = `pariksha ${name}:`;
|
|
104
|
+
const base = resolve(f.get('--root') ?? '.');
|
|
105
|
+
try {
|
|
106
|
+
const configPath = f.get('--config');
|
|
107
|
+
const config = parseDocConfig(configPath === undefined ? undefined : readFileSync(resolve(base, configPath), 'utf8'), defaultGuidance);
|
|
108
|
+
const from = f.get('--files-from');
|
|
109
|
+
const listed = from === undefined ? undefined : from === '-' ? (io.stdin ?? (() => readFileSync(0, 'utf8')))() : readFileSync(resolve(from), 'utf8');
|
|
110
|
+
const docs = selectDocs(base, listed, config.include).map((file) => ({ file, text: () => readDoc(base, file) }));
|
|
111
|
+
const result = check(docs, base, config);
|
|
112
|
+
result.out.forEach(io.out);
|
|
113
|
+
return result.ok ? 0 : 1;
|
|
114
|
+
}
|
|
115
|
+
catch (e) {
|
|
116
|
+
io.err(`${P} ${e.message}; nothing was checked, so this is not a pass`);
|
|
117
|
+
return 2;
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
const absolutePaths = docCheck('absolute-paths', ABSOLUTE_PATHS_GUIDANCE, (docs, _base, config) => checkAbsolutePaths(docs, config));
|
|
121
|
+
const nonSyncedResources = docCheck('non-synced-resources', NON_SYNCED_GUIDANCE, (docs, base, config) => checkNonSyncedResources(docs, () => {
|
|
122
|
+
const top = topOf(base);
|
|
123
|
+
if (top === undefined)
|
|
124
|
+
throw new Error(`${base} is not in a git repository`);
|
|
125
|
+
return top;
|
|
126
|
+
}, config));
|
|
127
|
+
/** Standard input, or the file `from` names, read whole. */
|
|
128
|
+
const listFrom = (from, io) => (from === '-' ? (io.stdin ?? (() => readFileSync(0, 'utf8')))() : readFileSync(resolve(from), 'utf8'));
|
|
129
|
+
/**
|
|
130
|
+
* masked-exit-codes: the shell files git tracks under `--root`, read from
|
|
131
|
+
* the working tree, or the index with `--staged`. The report goes to stdout
|
|
132
|
+
* when clean and stderr when not, as the original printed it.
|
|
133
|
+
*/
|
|
134
|
+
const maskedExitCodes = (f, io) => {
|
|
135
|
+
const root = resolve(f.get('--root') ?? '.');
|
|
136
|
+
try {
|
|
137
|
+
const configPath = f.get('--config');
|
|
138
|
+
const config = configPath === undefined ? DEFAULT_MASKED_CONFIG : parseMaskedConfig(readFileSync(resolve(root, configPath), 'utf8'));
|
|
139
|
+
const files = shellFiles(root, config);
|
|
140
|
+
const problems = files.length === 0 ? [] : findMaskedExits(root, files, maskedReaderFor(f.has('--staged')), config);
|
|
141
|
+
const result = formatMasked(problems, files.length, config.id);
|
|
142
|
+
result.out.forEach(io.out);
|
|
143
|
+
result.err.forEach(io.err);
|
|
144
|
+
return result.ok ? 0 : 1;
|
|
145
|
+
}
|
|
146
|
+
catch (e) {
|
|
147
|
+
io.err(`pariksha masked-exit-codes: ${e.message}; nothing was checked, so this is not a pass`);
|
|
148
|
+
return 2;
|
|
149
|
+
}
|
|
150
|
+
};
|
|
151
|
+
/**
|
|
152
|
+
* shell-gates: one of `--staged` (the default), `--all`, `--base <ref>` or
|
|
153
|
+
* `--files-from <file>|-`; `--only` names the checks to run, and then
|
|
154
|
+
* ShellCheck sits the run out, as the original did.
|
|
155
|
+
*/
|
|
156
|
+
const shellGates = (f, io) => {
|
|
157
|
+
const P = '❌ Shell gates could not run:';
|
|
158
|
+
const root = resolve(f.get('--root') ?? '.');
|
|
159
|
+
const modes = ['--staged', '--all', '--base', '--files-from'].filter((name) => f.has(name));
|
|
160
|
+
if (modes.length > 1) {
|
|
161
|
+
io.err(`${P} choose one of --staged, --all, --base, --files-from (got ${modes.join(', ')})`);
|
|
162
|
+
return 2;
|
|
163
|
+
}
|
|
164
|
+
let config;
|
|
165
|
+
let mode;
|
|
166
|
+
try {
|
|
167
|
+
const configPath = f.get('--config');
|
|
168
|
+
config = parseGatesConfig(configPath === undefined ? '{}' : readFileSync(resolve(root, configPath), 'utf8'));
|
|
169
|
+
const base = f.get('--base');
|
|
170
|
+
const from = f.get('--files-from');
|
|
171
|
+
if (from !== undefined) {
|
|
172
|
+
const files = entries(listFrom(from, io));
|
|
173
|
+
if (files.length === 0)
|
|
174
|
+
throw new Error('the --files-from list names no file, and a check of nothing is no pass');
|
|
175
|
+
mode = { kind: 'files', files };
|
|
176
|
+
}
|
|
177
|
+
else
|
|
178
|
+
mode = base !== undefined ? { kind: 'base', base } : f.has('--all') ? { kind: 'all' } : { kind: 'staged' };
|
|
179
|
+
}
|
|
180
|
+
catch (e) {
|
|
181
|
+
io.err(`${P} ${e.message}`);
|
|
182
|
+
return 2;
|
|
183
|
+
}
|
|
184
|
+
const only = f.get('--only');
|
|
185
|
+
let checks = SHELL_CHECKS.filter((name) => name !== 'preamble' || config.preamble !== undefined);
|
|
186
|
+
if (only !== undefined) {
|
|
187
|
+
const names = only.split(',').filter(Boolean);
|
|
188
|
+
const unknown = names.filter((name) => !SHELL_CHECKS.some((check) => check === name));
|
|
189
|
+
if (names.length === 0 || unknown.length > 0) {
|
|
190
|
+
io.err(`${P} --only takes ${SHELL_CHECKS.join(',')}; got ${names.join(',') || 'nothing'}`);
|
|
191
|
+
return 2;
|
|
192
|
+
}
|
|
193
|
+
checks = SHELL_CHECKS.filter((name) => names.includes(name));
|
|
194
|
+
}
|
|
195
|
+
return runShellGates({ root, mode, checks, only: only !== undefined }, config, { out: io.out, err: io.err, shellcheck: io.shellcheck ?? shellcheckRunner() });
|
|
196
|
+
};
|
|
197
|
+
const aggregateGateNeeds = (f, io) => {
|
|
198
|
+
const root = resolve(f.get('--root') ?? '.');
|
|
199
|
+
const configPath = f.get('--config');
|
|
200
|
+
let config = DEFAULT_GATE_CONFIG;
|
|
201
|
+
try {
|
|
202
|
+
if (configPath !== undefined)
|
|
203
|
+
config = parseAggregateConfig(readFileSync(resolve(root, configPath), 'utf8'));
|
|
204
|
+
}
|
|
205
|
+
catch (e) {
|
|
206
|
+
io.err(`pariksha aggregate-gate-needs: ${e.message}; nothing was checked, so this is not a pass`);
|
|
207
|
+
return 2;
|
|
208
|
+
}
|
|
209
|
+
const result = checkGates(root, config);
|
|
210
|
+
result.out.forEach(io.out);
|
|
211
|
+
result.err.forEach(io.err);
|
|
212
|
+
return result.ok ? 0 : 1;
|
|
213
|
+
};
|
|
214
|
+
const pnpmSettings = (f, io) => {
|
|
215
|
+
const root = resolve(f.get('--root') ?? '.');
|
|
216
|
+
const configPath = f.get('--config');
|
|
217
|
+
try {
|
|
218
|
+
const config = configPath === undefined ? DEFAULT_PNPM_CONFIG : parsePnpmConfig(readFileSync(resolve(root, configPath), 'utf8'));
|
|
219
|
+
const result = formatParity(checkPnpmSettings(root, config, (io.now ?? Date.now)()), config.id);
|
|
220
|
+
result.err.forEach(io.err);
|
|
221
|
+
result.out.forEach(io.out);
|
|
222
|
+
return result.ok ? 0 : 1;
|
|
223
|
+
}
|
|
224
|
+
catch (e) {
|
|
225
|
+
io.err(`pariksha pnpm-settings: ${e.message}; nothing was checked, so this is not a pass`);
|
|
226
|
+
return 2;
|
|
227
|
+
}
|
|
228
|
+
};
|
|
84
229
|
const boundary = (f, io) => {
|
|
85
230
|
const root = resolve(f.get('--root') ?? '.');
|
|
86
231
|
const denyPath = resolve(root, f.get('--deny') ?? DENY_FILE);
|
|
@@ -553,6 +698,10 @@ const COMMANDS = {
|
|
|
553
698
|
'codec-registry': { allowed: ['--config', '--base', '--root'], switches: ['--no-base'], run: codecRegistry },
|
|
554
699
|
'coverage-exemptions': { allowed: ['--config', '--package', '--root'], run: coverageExemptions },
|
|
555
700
|
'fault-injection-registry': { allowed: ['--config', '--base', '--root'], switches: ['--no-base'], run: faultInjectionRegistry },
|
|
701
|
+
'absolute-paths': { allowed: ['--config', '--files-from', '--root'], run: absolutePaths },
|
|
702
|
+
'aggregate-gate-needs': { allowed: ['--config', '--root'], run: aggregateGateNeeds },
|
|
703
|
+
'non-synced-resources': { allowed: ['--config', '--files-from', '--root'], run: nonSyncedResources },
|
|
704
|
+
'pnpm-settings': { allowed: ['--config', '--root'], run: pnpmSettings },
|
|
556
705
|
'authority-citations': { allowed: ['--mode', '--authority', '--issue-prefix', '--adr-dir', '--root'], run: authorityCitations },
|
|
557
706
|
boundary: { allowed: ['--root', '--deny'], run: boundary },
|
|
558
707
|
'coverage-by-type': { allowed: ['--config', '--files-from', '--root'], run: coverageByType },
|
|
@@ -561,7 +710,9 @@ const COMMANDS = {
|
|
|
561
710
|
'enforcement-claims': { allowed: ['--config', '--root'], run: enforcementClaims },
|
|
562
711
|
'env-gate-switches': { allowed: ['--config', '--mode', '--root'], run: envGateSwitches },
|
|
563
712
|
'export-deletions': { allowed: ['--base', '--root'], run: exportDeletions },
|
|
713
|
+
'masked-exit-codes': { allowed: ['--config', '--root'], switches: ['--staged'], run: maskedExitCodes },
|
|
564
714
|
'required-settings': { allowed: ['--require', '--settings', '--root'], run: requiredSettings },
|
|
715
|
+
'shell-gates': { allowed: ['--config', '--base', '--files-from', '--only', '--root'], switches: ['--staged', '--all'], run: shellGates },
|
|
565
716
|
};
|
|
566
717
|
/** The exit code; a Promise of it for the one check that is asynchronous (enforcement-claims, which loads ESLint). */
|
|
567
718
|
export const run = (args, io, version = ownVersion(), env = process.env) => {
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// The documents absolute-paths and non-synced-resources read, and the config
|
|
2
|
+
// both take. A product's hook hands them its own list (`--files-from`); with
|
|
3
|
+
// none, they read every file git tracks.
|
|
4
|
+
import { readFileSync, statSync } from 'node:fs';
|
|
5
|
+
import { resolve } from 'node:path';
|
|
6
|
+
import { entries } from "./coverage-by-type.js";
|
|
7
|
+
import { gitAt, must } from "./git.js";
|
|
8
|
+
/** Markdown and MDX. */
|
|
9
|
+
export const DEFAULT_INCLUDE = '\\.(md|mdx)$';
|
|
10
|
+
const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
11
|
+
/**
|
|
12
|
+
* `{ "include"?: "<regex>", "guidance"?: ["<line>", …] }`; absent keys take
|
|
13
|
+
* the defaults. Throws on anything else, so a mistyped key never passes as
|
|
14
|
+
* the default.
|
|
15
|
+
*/
|
|
16
|
+
export const parseDocConfig = (text, defaultGuidance) => {
|
|
17
|
+
if (text === undefined)
|
|
18
|
+
return { include: new RegExp(DEFAULT_INCLUDE), guidance: defaultGuidance };
|
|
19
|
+
let raw;
|
|
20
|
+
try {
|
|
21
|
+
raw = JSON.parse(text);
|
|
22
|
+
}
|
|
23
|
+
catch (e) {
|
|
24
|
+
throw new Error(`not JSON: ${e.message}`);
|
|
25
|
+
}
|
|
26
|
+
if (!isRecord(raw))
|
|
27
|
+
throw new Error('the config must be a JSON object');
|
|
28
|
+
const unknown = Object.keys(raw).find((k) => k !== 'include' && k !== 'guidance');
|
|
29
|
+
if (unknown !== undefined)
|
|
30
|
+
throw new Error(`unknown key "${unknown}"`);
|
|
31
|
+
// Absent takes the default; a present `null` is refused like any other wrong value.
|
|
32
|
+
const include = 'include' in raw ? raw['include'] : DEFAULT_INCLUDE;
|
|
33
|
+
if (typeof include !== 'string' || include === '')
|
|
34
|
+
throw new Error('"include" must be a non-empty regex string');
|
|
35
|
+
let pattern;
|
|
36
|
+
try {
|
|
37
|
+
pattern = new RegExp(include);
|
|
38
|
+
}
|
|
39
|
+
catch (e) {
|
|
40
|
+
throw new Error(`"include" is not a regex: ${e.message}`);
|
|
41
|
+
}
|
|
42
|
+
const guidance = 'guidance' in raw ? raw['guidance'] : defaultGuidance;
|
|
43
|
+
if (!Array.isArray(guidance) || guidance.some((line) => typeof line !== 'string'))
|
|
44
|
+
throw new Error('"guidance" must be a list of lines');
|
|
45
|
+
return { include: pattern, guidance: guidance };
|
|
46
|
+
};
|
|
47
|
+
/** Whether `path` (under `base` when relative) names a regular file, a symlink to one included. */
|
|
48
|
+
export const isFileAt = (base, path) => {
|
|
49
|
+
try {
|
|
50
|
+
return statSync(resolve(base, path)).isFile();
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
return false;
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
/**
|
|
57
|
+
* The documents to check, as listed: each entry of `listed` that names a
|
|
58
|
+
* regular file under `base` and matches `include`, in order; a named path
|
|
59
|
+
* that is not a file is dropped. With no list, every file git tracks under
|
|
60
|
+
* `base`, as git names it.
|
|
61
|
+
*/
|
|
62
|
+
export const selectDocs = (base, listed, include) => {
|
|
63
|
+
const paths = listed === undefined ? must(gitAt(base), ['ls-files', '-z']).split('\0').filter(Boolean) : entries(listed);
|
|
64
|
+
return paths.filter((path) => isFileAt(base, path) && include.test(path));
|
|
65
|
+
};
|
|
66
|
+
/** A document's lines as a shell `read` loop sees them: split on newlines, a last line without one included. */
|
|
67
|
+
export const linesOf = (text) => {
|
|
68
|
+
const lines = text.split('\n');
|
|
69
|
+
if (lines.at(-1) === '')
|
|
70
|
+
lines.pop();
|
|
71
|
+
return lines;
|
|
72
|
+
};
|
|
73
|
+
/** A listed document's text. */
|
|
74
|
+
export const readDoc = (base, path) => readFileSync(resolve(base, path), 'utf8');
|
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
// The git hook preamble contract: every hook follows one preamble, so the
|
|
2
|
+
// runtime a hook uses is decided in one place (the config's `selectScript`,
|
|
3
|
+
// which defines `selectFunction`) and a cancelled hook stays cancelled.
|
|
4
|
+
//
|
|
5
|
+
// runtime-before-select-node node/npx/pnpm/npm/tsx/corepack/yarn runs before
|
|
6
|
+
// the hook sources the select script and calls
|
|
7
|
+
// its function
|
|
8
|
+
// opt-out-after-select-node an opt-out (`[ "$VAR" = 0 ] && exit 0`) comes
|
|
9
|
+
// after runtime selection, so opting out still
|
|
10
|
+
// pays for (and can fail on) selection
|
|
11
|
+
// own-runtime-path the hook edits PATH or touches nvm/fnm/mise
|
|
12
|
+
// itself; the select script owns that
|
|
13
|
+
// exec-sh-trampoline `exec sh <hook>` ignores the target's bash
|
|
14
|
+
// shebang
|
|
15
|
+
// signal-trap-continues an INT/TERM/HUP/QUIT trap whose handler does
|
|
16
|
+
// not end in `exit`: bash resumes after the
|
|
17
|
+
// handler, so a cancelled gate carries on
|
|
18
|
+
import { isHook } from "./shell-sources.js";
|
|
19
|
+
import { codeLines, commandAt, commandPositions, maskQuoted, messageView, words } from "./shell-text.js";
|
|
20
|
+
export const DEFAULT_RUNTIMES = ['node', 'npx', 'pnpm', 'npm', 'tsx', 'corepack', 'yarn'];
|
|
21
|
+
const STOP_SIGNALS = new Set(['INT', 'TERM', 'HUP', 'QUIT', '1', '2', '3', '15']);
|
|
22
|
+
const escapeRegex = (text) => text.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&');
|
|
23
|
+
const finding = (config, source, rule, line, message) => ({ check: config.id, rule, file: source.path, line, message });
|
|
24
|
+
/** Whether the first word of `rest` (a command's operands) matches `pattern`; no word, no match. */
|
|
25
|
+
const firstWordMatches = (rest, pattern) => words(rest)
|
|
26
|
+
.slice(0, 1)
|
|
27
|
+
.some((word) => pattern.test(word));
|
|
28
|
+
/**
|
|
29
|
+
* Quote-masked text after a command at this level only: each `( … )` or
|
|
30
|
+
* `$( … )` group becomes one space, so `&(:)&` stays two separate `&`, and
|
|
31
|
+
* the text is cut at a `)` that closes an enclosing group. Only this level's
|
|
32
|
+
* separators remain; offsets are not kept.
|
|
33
|
+
*/
|
|
34
|
+
const outerLevel = (masked) => {
|
|
35
|
+
let depth = 0;
|
|
36
|
+
const kept = [];
|
|
37
|
+
for (const char of masked) {
|
|
38
|
+
if (char === ')') {
|
|
39
|
+
if (depth === 0)
|
|
40
|
+
break;
|
|
41
|
+
depth -= 1;
|
|
42
|
+
}
|
|
43
|
+
else if (char === '(') {
|
|
44
|
+
if (depth === 0)
|
|
45
|
+
kept.push(' ');
|
|
46
|
+
depth += 1;
|
|
47
|
+
}
|
|
48
|
+
else if (depth === 0)
|
|
49
|
+
kept.push(char);
|
|
50
|
+
}
|
|
51
|
+
return kept.join('');
|
|
52
|
+
};
|
|
53
|
+
/**
|
|
54
|
+
* Whether the command at `start..end` runs in a child shell, so whatever it
|
|
55
|
+
* defines or selects is gone afterwards: a pipeline stage (`x | cmd`,
|
|
56
|
+
* `cmd | cat`, `|&` too) or a list sent to the background (`cmd &`).
|
|
57
|
+
*/
|
|
58
|
+
const runsInChildShell = (code, start, end) => {
|
|
59
|
+
if (/(?:^|[^|])\|&?\s*$/.test(code.slice(0, start)))
|
|
60
|
+
return true;
|
|
61
|
+
// The rest of its list (to `;` or a newline) and of its pipeline (to `&&`
|
|
62
|
+
// or `||` too, which bind looser than `|`), read at this level only: a `;`
|
|
63
|
+
// inside `"$(a; b)"` ends nothing.
|
|
64
|
+
const list = outerLevel(maskQuoted(code).slice(end)).split(/[;\n]/)[0];
|
|
65
|
+
if (/(?:^|[^&>])&(?![&>])/.test(list))
|
|
66
|
+
return true;
|
|
67
|
+
const pipeline = list.split(/&&|\|\|/)[0];
|
|
68
|
+
return /\|/.test(pipeline);
|
|
69
|
+
};
|
|
70
|
+
/**
|
|
71
|
+
* Offsets of each `.`/`source` command, where it runs (never in a message or
|
|
72
|
+
* quoted text), whose file operand is the select script.
|
|
73
|
+
*/
|
|
74
|
+
const selectSources = (code, script) => ['.', 'source'].flatMap((name) => commandPositions(code, name).filter((end) => firstWordMatches(code.slice(end), script) && !runsInChildShell(code, end - name.length, end)));
|
|
75
|
+
/**
|
|
76
|
+
* `[ "$VAR" ... ] && exit 0` or `if [ ... ]; then exit 0`, on one line or
|
|
77
|
+
* several (`then` and `exit 0` on lines of their own), read over the logical
|
|
78
|
+
* lines joined with newlines.
|
|
79
|
+
*/
|
|
80
|
+
const OPT_OUT = /\$\{?[A-Z][A-Z0-9_]*\b[^\]\n]*\]\]?\s*(?:&&|(?:;|\n)\s*then)\s*exit\s+0\b/g;
|
|
81
|
+
const PATH_EDIT = /(?:^|[\s;&|(])(?:export\s+)?PATH\+?=/;
|
|
82
|
+
const NVM = /\bNVM_DIR\b|\bnvm\.sh\b/;
|
|
83
|
+
const FNM_USE = /(?:^|[\s;&|("])fnm\s+(?:use|env)\b/;
|
|
84
|
+
/** `mise activate`, `mise env`, `mise exec`/`x` or `mise shell`: each edits the runtime PATH. */
|
|
85
|
+
const MISE_USE = /(?:^|[\s;&|("])mise\s+(?:activate|env|exec|x|shell)\b/;
|
|
86
|
+
/** `. "$NVM_DIR/nvm.sh"`, `\. ~/.nvm/nvm.sh` or `source …nvm.sh`: the path is often quoted. */
|
|
87
|
+
const sourcesNvm = (code) => ['.', '\\.', 'source'].some((name) => commandPositions(code, name).some((end) => firstWordMatches(code.slice(end), /nvm\.sh\b/)));
|
|
88
|
+
/** The first position, in line then offset order, that `find` yields and `keep` accepts. */
|
|
89
|
+
const firstAt = (lines, find, keep) => {
|
|
90
|
+
for (const [index, line] of lines.entries()) {
|
|
91
|
+
const kept = find(line.code).filter((offset) => keep({ index, offset }));
|
|
92
|
+
if (kept.length > 0)
|
|
93
|
+
return { index, offset: Math.min(...kept) };
|
|
94
|
+
}
|
|
95
|
+
return undefined;
|
|
96
|
+
};
|
|
97
|
+
const NAME = String.raw `[A-Za-z_][\w-]*`;
|
|
98
|
+
/** `f() {`, `function f {` or `function f() {`, capturing the name and the rest. */
|
|
99
|
+
const FUNCTION_HEADER = new RegExp(String.raw `^\s*(?:function\s+(${NAME})\s*(?:\(\s*\))?|(${NAME})\s*\(\s*\))\s*\{(.*)$`);
|
|
100
|
+
/** `f()`, `function f` or `function f()` alone: the `{` opens the next line. */
|
|
101
|
+
const BARE_HEADER = new RegExp(String.raw `^\s*(?:function\s+(${NAME})\s*(?:\(\s*\))?|(${NAME})\s*\(\s*\))\s*$`);
|
|
102
|
+
/**
|
|
103
|
+
* Statements split at unquoted `;` and newlines only: `echo "a; exit 1"` is
|
|
104
|
+
* one statement, and `cleanup && exit 130` is one whose exit may not run.
|
|
105
|
+
*/
|
|
106
|
+
const splitStatements = (code) => {
|
|
107
|
+
const masked = maskQuoted(code);
|
|
108
|
+
const parts = [];
|
|
109
|
+
let from = 0;
|
|
110
|
+
for (let at = 0; at <= code.length; at += 1) {
|
|
111
|
+
if (at === code.length || masked[at] === ';' || masked[at] === '\n') {
|
|
112
|
+
parts.push(code.slice(from, at).trim());
|
|
113
|
+
from = at + 1;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return parts.filter(Boolean);
|
|
117
|
+
};
|
|
118
|
+
/** Unquoted code with `${…}` blanked, offsets preserved, for brace counting. */
|
|
119
|
+
const braceView = (code) => maskQuoted(code).replace(/\$\{[^}]*\}/g, (match) => ' '.repeat(match.length));
|
|
120
|
+
/** A function header at `index`: its name, the line holding its `{`, and the code after that `{`. */
|
|
121
|
+
const headerAt = (lines, index) => {
|
|
122
|
+
const code = lines[index].code;
|
|
123
|
+
const match = FUNCTION_HEADER.exec(code);
|
|
124
|
+
if (match !== null)
|
|
125
|
+
return { name: (match[1] ?? match[2]), braceLine: index, rest: match[3] };
|
|
126
|
+
// `f()` alone, its `{` opening the next line, is a definition too.
|
|
127
|
+
const bare = BARE_HEADER.exec(code);
|
|
128
|
+
const next = lines.at(index + 1);
|
|
129
|
+
if (bare === null || next === undefined)
|
|
130
|
+
return undefined;
|
|
131
|
+
const brace = /^\s*\{(.*)$/.exec(next.code);
|
|
132
|
+
if (brace === null)
|
|
133
|
+
return undefined;
|
|
134
|
+
return { name: (bare[1] ?? bare[2]), braceLine: index + 1, rest: brace[1] };
|
|
135
|
+
};
|
|
136
|
+
/**
|
|
137
|
+
* Every function definition, from its header to the `}` that brings the
|
|
138
|
+
* brace depth back to zero, so a nested `{ …; }` group does not end it and
|
|
139
|
+
* code after the closing brace on that line stays top level.
|
|
140
|
+
*/
|
|
141
|
+
const functionDefinitions = (lines) => {
|
|
142
|
+
const out = [];
|
|
143
|
+
for (let index = 0; index < lines.length; index += 1) {
|
|
144
|
+
const start = index;
|
|
145
|
+
const header = headerAt(lines, index);
|
|
146
|
+
if (header === undefined)
|
|
147
|
+
continue;
|
|
148
|
+
const { name, braceLine, rest } = header;
|
|
149
|
+
index = braceLine;
|
|
150
|
+
// Where the body starts: just past the `{`, on the line holding it.
|
|
151
|
+
const bodyStart = lines[braceLine].code.length - rest.length;
|
|
152
|
+
let depth = 0;
|
|
153
|
+
let end;
|
|
154
|
+
for (; index < lines.length && end === undefined; index += 1) {
|
|
155
|
+
for (const [offset, char] of braceView(lines[index].code)
|
|
156
|
+
.split('')
|
|
157
|
+
.entries()) {
|
|
158
|
+
if (char === '{')
|
|
159
|
+
depth += 1;
|
|
160
|
+
else if (char === '}' && --depth === 0) {
|
|
161
|
+
end = { index, offset };
|
|
162
|
+
break;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
index -= 1; // back to the closing line; the outer loop steps past it
|
|
167
|
+
const close = end ?? { index, offset: lines[index].code.length };
|
|
168
|
+
const parts = [];
|
|
169
|
+
for (let line = braceLine; line <= close.index; line += 1)
|
|
170
|
+
parts.push(lines[line].code.slice(line === braceLine ? bodyStart : 0, line === close.index ? close.offset : undefined));
|
|
171
|
+
const body = parts.join(';');
|
|
172
|
+
out.push({ name, start, end: close, body, statements: splitStatements(body).filter((statement) => statement !== '}' && statement !== '{') });
|
|
173
|
+
}
|
|
174
|
+
return out;
|
|
175
|
+
};
|
|
176
|
+
/** Strictly earlier: by logical line, then by offset within it. */
|
|
177
|
+
export const isBefore = (a, b) => a.index < b.index || (a.index === b.index && a.offset < b.offset);
|
|
178
|
+
// A command ends before the `}` that closes its function: `node}` is one word.
|
|
179
|
+
const insideFunction = (functions, at) => functions.some((fn) => at.index >= fn.start && isBefore(at, fn.end));
|
|
180
|
+
/**
|
|
181
|
+
* Whether `at` runs in the hook's own shell: no unquoted `(` left open before
|
|
182
|
+
* it, across lines, and no open backtick substitution. Selection inside
|
|
183
|
+
* `( … )`, `$( … )` or `` `…` `` is lost when the subshell exits.
|
|
184
|
+
*/
|
|
185
|
+
const inHookShell = (lines, at) => {
|
|
186
|
+
let depth = 0;
|
|
187
|
+
let inBacktick = false;
|
|
188
|
+
const before = lines
|
|
189
|
+
.slice(0, at.index)
|
|
190
|
+
.map((line) => maskQuoted(line.code))
|
|
191
|
+
.concat(maskQuoted(lines[at.index].code).slice(0, at.offset));
|
|
192
|
+
for (const text of before) {
|
|
193
|
+
for (const char of text) {
|
|
194
|
+
if (char === '(')
|
|
195
|
+
depth += 1;
|
|
196
|
+
else if (char === ')')
|
|
197
|
+
depth = Math.max(0, depth - 1);
|
|
198
|
+
else if (char === '`')
|
|
199
|
+
inBacktick = !inBacktick;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
return depth === 0 && !inBacktick;
|
|
203
|
+
};
|
|
204
|
+
/** `'x'` or `"x"` without its quotes; anything else as it is. */
|
|
205
|
+
const unquote = (word) => /^(['"])([\s\S]*)\1$/.exec(word)?.[2] ?? word;
|
|
206
|
+
/** Leading redirections (`2>&1`, `>/dev/null`) of a command's remainder. */
|
|
207
|
+
const REDIRECTIONS = /^(?:\s*[0-9]*[<>]{1,2}&?\s*[^\s;&|]+)+/;
|
|
208
|
+
/**
|
|
209
|
+
* `exit` or `exit N`, plus any redirections (`exit 130 >&2` still exits the
|
|
210
|
+
* hook); `exit 130 &` or `exit 130 | cat` exits a child shell instead.
|
|
211
|
+
*/
|
|
212
|
+
const EXIT = String.raw `exit(?:\s+[^\s&|;<>]+)?(?:\s*[0-9]*[<>]{1,2}&?\s*[^\s;&|<>]+)*`;
|
|
213
|
+
const EXIT_STATEMENT = new RegExp(String.raw `^${EXIT}\s*$`);
|
|
214
|
+
/** Whether the last statement of a handler string, or of a named function's body, exits. */
|
|
215
|
+
const handlerEndsInExit = (handler, functions) => {
|
|
216
|
+
// `trap - SIG` restores the default (the hook dies); `trap '' SIG` ignores
|
|
217
|
+
// the signal, so a cancelled hook runs on.
|
|
218
|
+
if (handler === '-')
|
|
219
|
+
return true;
|
|
220
|
+
const body = unquote(handler).trim();
|
|
221
|
+
// A function name ends in exit when its body's last statement does.
|
|
222
|
+
// Otherwise split on `;` and newlines only: `cleanup && exit 130` is one
|
|
223
|
+
// statement whose exit is skipped when cleanup fails. An empty handler
|
|
224
|
+
// (`trap '' SIG`) has no last statement.
|
|
225
|
+
const last = /^[A-Za-z_][A-Za-z0-9_]*$/.test(body) ? functions.find((entry) => entry.name === body)?.statements.at(-1) : splitStatements(body).at(-1);
|
|
226
|
+
return last !== undefined && EXIT_STATEMENT.test(last);
|
|
227
|
+
};
|
|
228
|
+
const trapFindings = (config, source, lines, functions) => {
|
|
229
|
+
const out = [];
|
|
230
|
+
for (const entry of lines) {
|
|
231
|
+
// Every trap on the line: `trap 'exit 130' INT; trap '' TERM` has two.
|
|
232
|
+
for (const at of commandPositions(entry.code, 'trap')) {
|
|
233
|
+
let args = words(entry.code.slice(at));
|
|
234
|
+
// `trap -- handler SIG` ends options; `-p` and `-l` only list.
|
|
235
|
+
// `trap - SIG` restores the default, so it needs no check either.
|
|
236
|
+
if (args[0] === '--')
|
|
237
|
+
args = args.slice(1);
|
|
238
|
+
else if (args[0]?.startsWith('-'))
|
|
239
|
+
continue;
|
|
240
|
+
if (args.length < 2)
|
|
241
|
+
continue;
|
|
242
|
+
const [handler, ...signals] = args;
|
|
243
|
+
const stops = signals.some((signal) => STOP_SIGNALS.has(unquote(signal).toUpperCase().replace(/^SIG/, '')));
|
|
244
|
+
if (stops && !handlerEndsInExit(handler, functions)) {
|
|
245
|
+
out.push(finding(config, source, 'signal-trap-continues', entry.line, `trap ${handler} on ${signals.join(' ')} does not end in exit: bash resumes after the handler, so a cancelled hook keeps running`));
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
return out;
|
|
250
|
+
};
|
|
251
|
+
export const checkHookPreamble = (source, config) => {
|
|
252
|
+
if (!isHook(source.path, config.hooksDir))
|
|
253
|
+
return [];
|
|
254
|
+
const lines = codeLines(source.text);
|
|
255
|
+
const out = [];
|
|
256
|
+
const select = config.selectFunction;
|
|
257
|
+
// Absolute or repository-relative: hooks run from the repository root.
|
|
258
|
+
const script = new RegExp(String.raw `(?:^["']?|\/)${escapeRegex(config.selectScript)}\b`);
|
|
259
|
+
// A function body runs where the function is called, not where it is
|
|
260
|
+
// defined: selection inside one does not count as the preamble selecting,
|
|
261
|
+
// and a runtime inside one counts at each call of that function.
|
|
262
|
+
const functions = functionDefinitions(lines);
|
|
263
|
+
const outsideFunctions = (at) => !insideFunction(functions, at);
|
|
264
|
+
const runtimeOffsets = (code, names) => names.flatMap((name) => commandPositions(code, name));
|
|
265
|
+
// A function that runs a runtime, or calls a function that does, is a
|
|
266
|
+
// runner. A Set's iteration also visits what is added during it, so each
|
|
267
|
+
// new runner is in turn checked for callers, and each name once.
|
|
268
|
+
const runners = new Set(functions.filter((definition) => runtimeOffsets(definition.body, config.runtimes).length > 0).map((definition) => definition.name));
|
|
269
|
+
for (const runner of runners) {
|
|
270
|
+
for (const definition of functions)
|
|
271
|
+
if (runtimeOffsets(definition.body, [runner]).length > 0)
|
|
272
|
+
runners.add(definition.name);
|
|
273
|
+
}
|
|
274
|
+
// Selection must also run in the hook's own shell: inside `( … )` or
|
|
275
|
+
// `$( … )` its PATH change is gone once the subshell exits.
|
|
276
|
+
const topLevel = (at) => outsideFunctions(at) && inHookShell(lines, at);
|
|
277
|
+
const sourcedAt = firstAt(lines, (code) => selectSources(code, script), topLevel);
|
|
278
|
+
// And its failure must stop the hook: `<select> || exit 1`, or the
|
|
279
|
+
// condition of an `if`. A bare call, `|| true`, or a top-level `|| return`
|
|
280
|
+
// (which fails and carries on) runs on unselected.
|
|
281
|
+
const calledAt = firstAt(lines, (code) => commandPositions(code, select).filter((end) => {
|
|
282
|
+
const start = end - select.length;
|
|
283
|
+
// A pipeline stage runs in a subshell: `x | select`; so does a list
|
|
284
|
+
// sent to the background: `select || exit 1 &`.
|
|
285
|
+
if (runsInChildShell(code, start, end))
|
|
286
|
+
return false;
|
|
287
|
+
// Redirections may sit between the call and `||`: `2>&1 || exit 1`.
|
|
288
|
+
const rest = code.slice(end).replace(REDIRECTIONS, '');
|
|
289
|
+
return (
|
|
290
|
+
// `|| exit`, or a `|| { …; }` block whose last statement exits. The
|
|
291
|
+
// exit must end the list: `|| exit 1 | cat` exits a pipeline child.
|
|
292
|
+
new RegExp(String.raw `^\s*\|\|\s*${EXIT}\s*(?:$|;|&&)`).test(rest) ||
|
|
293
|
+
new RegExp(String.raw `^\s*\|\|\s*\{(?:[^}]*;)?\s*${EXIT}\s*;\s*\}\s*(?:$|;|&&)`).test(rest) ||
|
|
294
|
+
/(?:^|[\s;&])if\s+(?:!\s*)?$/.test(code.slice(0, start)));
|
|
295
|
+
}), topLevel);
|
|
296
|
+
const runtimeAt = firstAt(lines, (code) => runtimeOffsets(code, [...config.runtimes, ...runners]), outsideFunctions);
|
|
297
|
+
if (runtimeAt !== undefined) {
|
|
298
|
+
// Ordered by logical line, then by offset within it, so
|
|
299
|
+
// `. select.sh; select; node x` on one line is in order.
|
|
300
|
+
const selectedBefore = sourcedAt !== undefined && calledAt !== undefined && isBefore(sourcedAt, calledAt) && isBefore(calledAt, runtimeAt);
|
|
301
|
+
if (!selectedBefore) {
|
|
302
|
+
out.push(finding(config, source, 'runtime-before-select-node', lines[runtimeAt.index].line, `runs a Node tool before sourcing ${config.selectScript} and calling ${select}, so it uses whatever node PATH happens to hold`));
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
if (sourcedAt !== undefined) {
|
|
306
|
+
// Everything after the source, its own line's rest included:
|
|
307
|
+
// `. select.sh; [ "$X" ] && exit 0` opts out after selecting.
|
|
308
|
+
const sourceLine = lines[sourcedAt.index];
|
|
309
|
+
const after = [{ line: sourceLine.line, code: sourceLine.code.slice(sourcedAt.offset) }, ...lines.slice(sourcedAt.index + 1)];
|
|
310
|
+
// Messages blanked: `echo '[ "$X" ] && exit 0'` shows an opt-out.
|
|
311
|
+
const texts = after.map((entry) => `${messageView(entry.code)}\n`);
|
|
312
|
+
const joined = texts.join('');
|
|
313
|
+
const starts = texts.map((_, index) => texts.slice(0, index).join('').length);
|
|
314
|
+
const masked = maskQuoted(joined);
|
|
315
|
+
for (const match of joined.matchAll(OPT_OUT)) {
|
|
316
|
+
// The exit must run: in `HELP='[ "$X" ] && exit 0'` it is quoted text.
|
|
317
|
+
const exitAt = match.index + match[0].lastIndexOf('exit');
|
|
318
|
+
if (!masked.startsWith('exit', exitAt))
|
|
319
|
+
continue;
|
|
320
|
+
// Reported on the condition's line: the last starting at or before it.
|
|
321
|
+
const owner = starts.findLastIndex((start) => start <= match.index);
|
|
322
|
+
out.push(finding(config, source, 'opt-out-after-select-node', after[owner].line, 'opt-out comes after runtime selection; check it first so an opted-out hook does no work and cannot fail'));
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
for (const entry of lines) {
|
|
326
|
+
// Code text, not command positions, with quoted literals blanked: a
|
|
327
|
+
// message (echo/printf) is judged with its words blanked too, so
|
|
328
|
+
// `echo export PATH=...` and `HELP="export PATH=..."` name an edit
|
|
329
|
+
// without making one, while `eval "$(fnm env)"` keeps its substitution.
|
|
330
|
+
const view = messageView(entry.code);
|
|
331
|
+
const code = maskQuoted(view);
|
|
332
|
+
if (PATH_EDIT.test(code) || NVM.test(code) || sourcesNvm(view) || commandAt(entry.code, 'nvm') !== -1 || FNM_USE.test(code) || MISE_USE.test(code)) {
|
|
333
|
+
out.push(finding(config, source, 'own-runtime-path', entry.line, `hook edits PATH or drives nvm/fnm/mise itself; ${config.selectScript} owns runtime and tool PATH`));
|
|
334
|
+
}
|
|
335
|
+
// `exec` at a command position, never in a message; sh and dash only:
|
|
336
|
+
// `exec bash <hook>` names the dialect the hook needs.
|
|
337
|
+
const masked = maskQuoted(entry.code);
|
|
338
|
+
if (commandPositions(entry.code, 'exec').some((end) => /^\s+(?:\/usr\/bin\/env\s+)?(?:\/bin\/)?(?:da)?sh(?=\s|$)/.test(masked.slice(end)))) {
|
|
339
|
+
out.push(finding(config, source, 'exec-sh-trampoline', entry.line, '`exec sh <hook>` runs the target under sh whatever its shebang says; exec the hook itself'));
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
return [...out, ...trapFindings(config, source, lines, functions)].sort((a, b) => a.line - b.line);
|
|
343
|
+
};
|