@eslint-sh/eslint-plugin 0.13.0 → 0.14.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.
Files changed (33) hide show
  1. package/README.md +27 -10
  2. package/dist/api.d.ts +10 -0
  3. package/dist/api.js +8 -0
  4. package/dist/eslint-plugin-api.d.ts +40 -1
  5. package/dist/language/command-resolution.d.ts +8 -0
  6. package/dist/language/shell-language.js +2 -0
  7. package/dist/language/shell-source-code.d.ts +11 -1
  8. package/dist/language/shell-source-code.js +11 -1
  9. package/dist/processors/disable-justification.d.ts +20 -0
  10. package/dist/processors/disable-justification.js +124 -0
  11. package/dist/rules/compat/bash-builtin-destination.d.ts +18 -1
  12. package/dist/rules/compat/bash-builtin-destination.js +81 -2
  13. package/dist/rules/compat/no-mapfile.js +36 -1
  14. package/dist/rules/compat/no-printf-time-format.js +19 -2
  15. package/dist/rules/compat/no-test-v.js +14 -10
  16. package/dist/rules/no-unchecked-cd.js +11 -0
  17. package/dist/rules/require-tty-guard.js +17 -3
  18. package/docs/custom-rule-tutorial.md +140 -150
  19. package/docs/disable-justification.md +71 -0
  20. package/docs/examples/eslint.config.js +11 -0
  21. package/docs/examples/no-curl-in-functions-rule.mjs +15 -20
  22. package/docs/examples/no-listed-commands-rule.ts +19 -19
  23. package/docs/examples/no-rm-rf-rule.mjs +33 -62
  24. package/docs/examples/no-sample-command-rule.mjs +33 -0
  25. package/docs/reading-nodes.md +26 -1
  26. package/docs/rules/compat/no-mapfile.md +4 -1
  27. package/docs/rules/compat/no-printf-time-format.md +1 -1
  28. package/docs/rules/compat/no-test-v.md +1 -1
  29. package/docs/rules/no-unchecked-cd.md +2 -1
  30. package/docs/rules/require-tty-guard.md +1 -1
  31. package/docs/rules-about-commands.md +78 -0
  32. package/docs/selectors.md +8 -4
  33. package/package.json +1 -1
@@ -8,7 +8,10 @@
8
8
  * current time: `date '+fmt'`, which takes the same `strftime` format.
9
9
  *
10
10
  * The rule reads the first format field of a `printf` invocation, after
11
- * optional `-v name` and `--` operands. It scans exact text and known
11
+ * optional `-v name` and `--` operands. A destination Bash rejects (such as
12
+ * `a[1][2]`) stops `printf` before it reads the format, so nothing is
13
+ * reported. A destination that is not known, separate (`-v "$name"`) or
14
+ * attached to a literal `-v` (`"-v$name"`), is assumed to be valid. It scans exact text and known
12
15
  * literal edges for directives, honoring `%%`, flags, width and precision.
13
16
  * The report points to the format word.
14
17
  */
@@ -16,7 +19,7 @@ import { describeWordAtPosition, isSingleField } from '../../language/word-resol
16
19
  import { DEFAULT_TRANSPARENT_WRAPPERS } from 'sh-analysis';
17
20
  import { resolveTransparentWrappers } from '../resolve-transparent-wrappers.js';
18
21
  import { BUILTIN_WRAPPER } from '../transparent-wrappers.js';
19
- import { isBashBuiltinDestination } from './bash-builtin-destination.js';
22
+ import { canStartBashBuiltinDestination, isBashBuiltinDestination, } from './bash-builtin-destination.js';
20
23
  import { createCompatRule } from './create-compat-rule.js';
21
24
  /**
22
25
  * The wrappers followed to find the `printf` command: `sh-analysis`'s
@@ -99,6 +102,20 @@ export const noPrintfTimeFormat = createCompatRule({
99
102
  return;
100
103
  index = 1;
101
104
  }
105
+ else if (first !== undefined && !first.static) {
106
+ // An expanded word with a literal `-v` prefix is an attached
107
+ // destination: Bash takes the rest of the field as the variable
108
+ // name. Expect the format next only when the known edges can
109
+ // belong to a variable name or an array member.
110
+ const facts = words[0].facts;
111
+ const name = facts.knownPrefix.slice(2);
112
+ if (isSingleField(facts) &&
113
+ facts.knownPrefix.startsWith('-v') &&
114
+ ((/^(?:[A-Za-z_][A-Za-z0-9_]*)?$/u.test(name) &&
115
+ /^[A-Za-z0-9_]*$/u.test(facts.knownSuffix)) ||
116
+ (canStartBashBuiltinDestination(name) && facts.knownSuffix.endsWith(']'))))
117
+ index = 1;
118
+ }
102
119
  const option = words.at(index)?.facts.resolution;
103
120
  if (option?.static && option.text === '--')
104
121
  index++;
@@ -296,16 +296,17 @@ function variableTestIndices(argv) {
296
296
  if (argv[at] === '-v')
297
297
  found.push(at);
298
298
  }
299
- /** `test`'s three-argument rule, at offset `at`. */
299
+ /**
300
+ * `test`'s three-argument rule, at offset `at`. Only `! x y` can hold a
301
+ * `-v` operator; every other fitting form is a binary test or `( x )`, and
302
+ * arguments that fit no form are a syntax error.
303
+ */
300
304
  function threeArguments(at) {
301
305
  const middle = argv[at + 1];
302
306
  if (BINARY_OPERATORS.has(middle) || middle === '-a' || middle === '-o')
303
- return true;
304
- if (argv[at] === '!') {
307
+ return;
308
+ if (argv[at] === '!')
305
309
  twoArguments(at + 1);
306
- return true;
307
- }
308
- return argv[at] === '(' && argv[at + 2] === ')';
309
310
  }
310
311
  /** `test`'s precedence parser over every argument (`expr` in Bash's test.c). */
311
312
  function expression() {
@@ -362,6 +363,9 @@ function variableTestIndices(argv) {
362
363
  }
363
364
  return true;
364
365
  };
366
+ // Arguments left over after a complete expression are Bash's "too many
367
+ // arguments" error, raised only after the expression has been evaluated,
368
+ // so a `-v` in it has already run.
365
369
  or();
366
370
  }
367
371
  switch (argv.length) {
@@ -372,14 +376,14 @@ function variableTestIndices(argv) {
372
376
  if (argv[0] !== '!')
373
377
  twoArguments(0);
374
378
  break;
379
+ // Three arguments that fit no three-argument form are Bash's "binary
380
+ // operator expected" error; Bash does not fall back to the expression parser.
375
381
  case 3:
376
- if (!threeArguments(0))
377
- expression();
382
+ threeArguments(0);
378
383
  break;
379
384
  case 4:
380
385
  if (argv[0] === '!') {
381
- if (!threeArguments(1))
382
- expression();
386
+ threeArguments(1);
383
387
  }
384
388
  else if (argv[0] === '(' && argv[3] === ')') {
385
389
  if (argv[1] !== '!')
@@ -46,9 +46,13 @@
46
46
  * `&&`/`||`/pipeline (appending would change what the rest of the list does),
47
47
  * negated, in the background, or carrying a here-document (the text after the
48
48
  * statement is the document body, not shell code).
49
+ * It is also withheld when the file may install an error trap (`trap … ERR`,
50
+ * Zsh's `trap … ZERR` or a `TRAPZERR` function): the trap does not run for
51
+ * the left side of `||`, so the edit would silence it.
49
52
  */
50
53
  import { DEFAULT_TRANSPARENT_WRAPPERS } from 'sh-analysis';
51
54
  import { resolveTransparentWrappers } from './resolve-transparent-wrappers.js';
55
+ import { someShellNode } from '../language/syntax-view.js';
52
56
  import { createRule } from './create-rule.js';
53
57
  import { prologueOptionState, resolveStrictModePrologue, setStatementArguments, } from './strict-mode-prologue.js';
54
58
  import { BUILTIN_WRAPPER } from './transparent-wrappers.js';
@@ -235,6 +239,13 @@ export const noUncheckedCd = createRule({
235
239
  .some((word) => !word.static || /^(?:SIG)?(?:ERR|ZERR)$/iu.test(word.text)));
236
240
  });
237
241
  }
242
+ // Zsh also runs a function named TRAPZERR on failure; defining it,
243
+ // directly or through the `functions` parameter, installs the trap.
244
+ if (sourceCode.dialect === 'zsh' && !hasErrorTrap) {
245
+ hasErrorTrap = someShellNode(node, (part) => part.type === 'FuncDecl'
246
+ ? [part.name, ...part.names].some((name) => name?.value === 'TRAPZERR')
247
+ : part.type === 'Assign' && part.name?.value === 'functions');
248
+ }
238
249
  if (options.ignoreWhenErrexit === false)
239
250
  return;
240
251
  const { enabled, hasUnknownOptions } = prologueOptionState(node, sourceCode, prologue);
@@ -161,8 +161,12 @@ function readInput(call, sourceCode) {
161
161
  .filter((facts) => facts.fields.max !== 0);
162
162
  let input = 'stdin';
163
163
  let checkedAlternateDescriptor = false;
164
+ // Zsh's -p flag reads the coprocess wherever it appears; `-u p` selects it
165
+ // only until a later -u selects another descriptor.
164
166
  let usesCoprocess = false;
167
+ let coprocessDescriptor = false;
165
168
  let readsKeys = false;
169
+ let readsAnswer = false;
166
170
  let selectedDescriptor = false;
167
171
  let uncertainArguments = false;
168
172
  for (let i = 0; i < words.length; i += 1) {
@@ -184,6 +188,13 @@ function readInput(call, sourceCode) {
184
188
  const rest = text.slice(j + 1);
185
189
  if (switches.includes(flag))
186
190
  continue;
191
+ // Zsh's -q, like -k, reads one character from the terminal unless -u
192
+ // or -p selects another descriptor, even when stdin is redirected.
193
+ if (dialect === 'zsh' && flag === 'q') {
194
+ readsKeys = true;
195
+ readsAnswer = true;
196
+ continue;
197
+ }
187
198
  if (dialect === 'zsh' && flag === 'k') {
188
199
  readsKeys = true;
189
200
  if (rest !== '') {
@@ -227,8 +238,7 @@ function readInput(call, sourceCode) {
227
238
  }
228
239
  if (flag === 'u') {
229
240
  selectedDescriptor = true;
230
- if (dialect === 'zsh' && operand === 'p')
231
- usesCoprocess = true;
241
+ coprocessDescriptor = dialect === 'zsh' && operand === 'p';
232
242
  input = descriptorInput(operand, dialect, false);
233
243
  if (input === 'unknown')
234
244
  return input;
@@ -249,10 +259,14 @@ function readInput(call, sourceCode) {
249
259
  break;
250
260
  }
251
261
  }
252
- if (usesCoprocess)
262
+ if (usesCoprocess || coprocessDescriptor)
253
263
  return 'explicit';
254
264
  if (readsKeys && !selectedDescriptor)
255
265
  return 'terminal';
266
+ // `read -q` from a selected stdin can still fail on its operands (such as
267
+ // `-A` with two names); a guard would turn that failure into success.
268
+ if (readsAnswer && input === 'stdin')
269
+ return 'unknown';
256
270
  return input === 'stdin' && (checkedAlternateDescriptor || uncertainArguments)
257
271
  ? 'unknown'
258
272
  : input;
@@ -1,9 +1,9 @@
1
- # Custom-rule tutorial: from a cookbook selector to a firing rule
1
+ # Custom-rule tutorial
2
2
 
3
- The [selector cookbook](./selectors.md) is a reference for selector strings; this page bridges
4
- one of those selectors to a complete, runnable ESLint rule: a `{ meta, create(context) }` module,
5
- a `context.report` call with a message and location, and the exact flat-config (`eslint.config.mjs`)
6
- wiring — `plugins`, `rules`, `language` — needed to run it.
3
+ This walkthrough shows how to write, configure, and test an ESLint rule for shell scripts.
4
+ The [selector cookbook](./selectors.md) lists selectors for rules about syntax.
5
+
6
+ For rules about which program a script invokes, start with [Rules about commands](./rules-about-commands.md).
7
7
 
8
8
  Every rule on this page is built with `defineShellRule`, the plugin's rule-authoring helper (step
9
9
  2 explains what it does). Every code block that names a file is the literal, shipped file it
@@ -14,66 +14,46 @@ declarations. A rule fires on a fixture script and does not fire on a clean one,
14
14
  cannot silently drift from working code. To write the same kind of test for your own rule, see
15
15
  [step 11](#11-test-your-rule), whose example [`no-backticks-rule-tester.mjs`](./examples/no-backticks-rule-tester.mjs)
16
16
  you can run yourself. All example files ship with this package
17
- (`docs/examples/`), so you can copy them into your own project as-is. The JavaScript examples use
17
+ (`docs/examples/`), so you can copy them into your own project as-is. The separate rule modules use
18
18
  the `.mjs` extension deliberately: they are ES modules (`import`/`export`), and a default
19
19
  `npm init -y` project is CommonJS, so a plain `.js` extension would make Node — and ESLint's own
20
20
  config loader — try to parse them as CommonJS and fail with `SyntaxError: Cannot use import
21
21
  statement outside a module`. `.mjs` marks each file as an ES module regardless of the surrounding
22
22
  project's `"type"` field.
23
23
 
24
- ## 1. Pick a selector from the cookbook
24
+ ## 1. Run one local rule
25
+
26
+ Copy [`no-sample-command-rule.mjs`](./examples/no-sample-command-rule.mjs) from
27
+ [Rules about commands](./rules-about-commands.md). In a project with `"type": "module"` in
28
+ `package.json`, save this [`eslint.config.js`](./examples/eslint.config.js) beside the rule. In a CommonJS project, use
29
+ `eslint.config.mjs` for the same contents.
30
+
31
+ ```js
32
+ import sh from '@eslint-sh/eslint-plugin';
33
+ import noSampleCommand from './no-sample-command-rule.mjs';
34
+
35
+ export default [
36
+ {
37
+ files: ['**/*.sh'],
38
+ plugins: { sh, local: { rules: { 'no-sample-command': noSampleCommand } } },
39
+ language: 'sh/sh',
40
+ rules: { 'local/no-sample-command': 'warn' },
41
+ },
42
+ ];
43
+ ```
44
+
45
+ With `eslint` and `@eslint-sh/eslint-plugin` installed, run `npx eslint script.sh` on a script
46
+ containing `env sample-tool`. ESLint reports
47
+ `local/no-sample-command` at `sample-tool`. The config registers the shell language under
48
+ `sh` and enables the single project rule under `local`.
25
49
 
26
- The cookbook's `:command` [launch class](./selectors.md#the-six-launch-classes) matches
27
- `CallExpr` nodes with a command word, exactly the calls in `sourceCode.getCommandInventory().commands`.
28
- An assignment-only statement such as `FOO=1` does not match; `FOO=1 jq .`, `true`, `:`, and
29
- dynamic invocations such as `"$tool" file` do. Select `CallExpr` directly to include
30
- assignment-only calls. This tutorial's rule listens on `:command`; `create()` then narrows further
31
- (is the command `rm`? does it pass recursive and force short
32
- flags, such as `-rf`, `-fr`, or `-r -f`?) the same way a hand-written rule narrows any other
33
- selector-first ESLint rule.
50
+ The rest of the walkthrough builds a rule about short options passed to `rm`.
34
51
 
35
52
  ## 2. Write the rule module
36
53
 
37
54
  `docs/examples/no-rm-rf-rule.mjs`:
38
55
 
39
56
  ```mjs
40
- /**
41
- * The complete "flag `rm -rf`" custom rule from the custom-rule tutorial
42
- * (`../custom-rule-tutorial.md`). Plain, directly-runnable JavaScript (no
43
- * compile step) — this file *is* the tutorial's rule-module code fence,
44
- * copy-paste-verbatim; this package's test suite imports this
45
- * exact file (not a reconstruction) and asserts the markdown fence matches
46
- * it byte-for-byte, so the two can't silently drift.
47
- *
48
- * Built with `defineShellRule`, which declares `meta.languages: ['sh/sh']`
49
- * for it, so ESLint refuses to run the rule on a file of any other language.
50
- *
51
- * Built on the `:command` launch class from the selector cookbook
52
- * (`../selectors.md`) — `:command` matches calls with a command word, so `create()`
53
- * narrows further by inspecting the command word and its flag arguments,
54
- * exactly the pattern the cookbook's intro describes ("writing a rule as a
55
- * selector string rather than a `create()` full of manual type checks" —
56
- * here the selector does the node-type narrowing, `create()` only does the
57
- * domain-specific check).
58
- *
59
- * Flag words are resolved with `context.sourceCode.resolveWord`
60
- * (backed by `sh-analysis`) rather than a
61
- * hand-rolled scan: a word is only treated as a short-option cluster
62
- * when it is *statically* that string (bare or
63
- * quoted literal concatenations). Recursive (`r`/`R`) and force (`f`)
64
- * flags accumulate across words before `--`; uppercase `F` is not force.
65
- * Options are matched anywhere before `--`, GNU-style, even after operands.
66
- * This teaching example does not model long options or option precedence.
67
- * A word containing a `ParamExp`/`CmdSubst`/`ArithmExp`/
68
- * `ProcSubst` resolves to `{ static: false, reason }` (`'expansion'`,
69
- * `'tilde'`, `'glob'`, …) rather than being silently erased into a static
70
- * match — see `ShellSourceCode.resolveWord`'s API docs. The source instance
71
- * comes from ESLint, so the rule needs no separate `sh-ast` install or
72
- * dependency-hoisting reliance.
73
- *
74
- * @see ../custom-rule-tutorial.md — the tutorial this rule backs
75
- * @see ../selectors.md — the `:command` launch class
76
- */
77
57
  import { defineShellRule } from '@eslint-sh/eslint-plugin';
78
58
 
79
59
  const noRmRf = defineShellRule({
@@ -89,35 +69,43 @@ const noRmRf = defineShellRule({
89
69
  },
90
70
  create(context) {
91
71
  return {
92
- ':command'(node) {
93
- const args = node.args ?? [];
94
- const words = args.map((arg) => {
95
- const resolved = context.sourceCode.resolveWord(arg);
96
- return resolved.static ? resolved.text : null;
97
- });
98
-
99
- if (words[0] !== 'rm') {
100
- return;
101
- }
102
-
103
- // `rm -- -rf` and `rm build -- -rf` are not `rm -rf` — everything
104
- // after a `--` end-of-options marker is an operand (a filename),
105
- // never a flag (POSIX Utility Syntax Guidelines, guideline 10).
106
- const endOfOptions = words.indexOf('--');
107
- const flagCandidates = words.slice(1, endOfOptions === -1 ? undefined : endOfOptions);
108
-
109
- // Only static short-option clusters contribute flags; operands,
110
- // long options, and unresolved words supply no evidence. Recursive
111
- // and force may occur in the same word or in separate words.
112
- const shortOptions = flagCandidates.filter(
113
- (word) => word !== null && /^-[a-zA-Z]+$/.test(word),
114
- );
115
- const hasRecursive = shortOptions.some((word) => /[rR]/.test(word));
116
- const hasForce = shortOptions.some((word) => word.includes('f'));
117
- const isRecursiveForce = hasRecursive && hasForce;
118
-
119
- if (isRecursiveForce) {
120
- context.report({ node, loc: node.loc, messageId: 'rmRf' });
72
+ File() {
73
+ for (const site of context.sourceCode.getCommandInventory().commands) {
74
+ const { effective, chainIndices } = site.resolveInvokedCommand();
75
+ const index = chainIndices.at(-1);
76
+ if (index === undefined || (!effective.static && chainIndices.length > 1)) continue;
77
+
78
+ const facts = site.argvFacts.at(index);
79
+ if (facts?.resolution !== effective) continue;
80
+
81
+ const text = effective.static ? effective.text : undefined;
82
+ const name = facts.basename.known
83
+ ? facts.basename.text
84
+ : text?.slice(text.lastIndexOf('/') + 1);
85
+ const command = site.node.args.at(index);
86
+ if (name !== 'rm' || !command) continue;
87
+
88
+ const words = site.argv.slice(index + 1).map((word) => (word.static ? word.text : null));
89
+
90
+ // `rm -- -rf` and `rm build -- -rf` are not `rm -rf` — everything
91
+ // after a `--` end-of-options marker is an operand (a filename),
92
+ // never a flag (POSIX Utility Syntax Guidelines, guideline 10).
93
+ const endOfOptions = words.indexOf('--');
94
+ const flagCandidates = words.slice(0, endOfOptions === -1 ? undefined : endOfOptions);
95
+
96
+ // Only static short-option clusters contribute flags; operands,
97
+ // long options, and unresolved words supply no evidence. Recursive
98
+ // and force may occur in the same word or in separate words.
99
+ const shortOptions = flagCandidates.filter(
100
+ (word) => word !== null && /^-[a-zA-Z]+$/.test(word),
101
+ );
102
+ const hasRecursive = shortOptions.some((word) => /[rR]/.test(word));
103
+ const hasForce = shortOptions.some((word) => word.includes('f'));
104
+ const isRecursiveForce = hasRecursive && hasForce;
105
+
106
+ if (isRecursiveForce) {
107
+ context.report({ node: command, messageId: 'rmRf' });
108
+ }
121
109
  }
122
110
  },
123
111
  };
@@ -142,26 +130,21 @@ A few things worth calling out:
142
130
  - `defineShellRule` comes from `@eslint-sh/eslint-plugin` (or the umbrella `eslint-sh`).
143
131
  ESLint supplies `context.sourceCode`, including its word-resolution method. A rule needs no
144
132
  separate `sh-ast` or `@eslint/core` dependency.
145
- - The listener key, `':command'`, is a selector string — one of the [six launch
146
- classes](./selectors.md#the-six-launch-classes) — not a bare node-type name. ESLint's
147
- `esquery`-based rule-listener matching (via `ShellLanguage.matchesSelectorClass`) treats it
148
- exactly like any other selector key such as `CallExpr` or `CallExpr[args.0.parts.0.value='jq']`.
149
- - `context.sourceCode.resolveWord(arg)` uses the raw Word associated with the lint view and
150
- defaults to command-argument context for `CallExpr.args`. It is the way to ask "is this word statically the string X":
151
- it returns `{ static: true, text }` for a bare or
152
- quoted literal (`rm`, `'r'm`, `"-rf"` all resolve), and `{ static: false, reason }` the moment any
153
- part of the word depends on a `ParamExp`/`CmdSubst`/`ArithmExp`/`ProcSubst` — never inventing a
154
- value for a dynamic word.
133
+ - The `File` listener finds the effective command word and its basename as in
134
+ [Rules about commands](./rules-about-commands.md). `site.argv.slice(index + 1)` then starts
135
+ at that command's first argument. For `timeout 5 /bin/rm -rf build`, the arguments to
136
+ check for short options are `-rf` and `build`.
137
+ - Each argument in `site.argv` has a resolution. A static word has `{ static: true, text }`,
138
+ including quoted literals such as `"-rf"`. A dynamic word has `{ static: false, reason }`.
139
+ Only static words contribute short options.
155
140
  - Short flags accumulate across static words before the first `--`: `rm -rf build`,
156
141
  `rm -r -f build`, and `rm -R -f build` all report, while `rm -r build`, `rm -f build`,
157
142
  and `rm -r -- -f` do not. Recursive accepts `r` or `R`; force is lowercase `f`, so `-rF`
158
143
  does not supply both flags. Options are matched anywhere before `--`, GNU-style, even after
159
144
  operands (for example, `rm build -rf` reports). This example focuses on short options; it does not
160
145
  model long options or option precedence (such as a later `-i` overriding `-f`).
161
- - `context.report({ node, loc: node.loc, messageId: 'rmRf' })` reports with both a message (via
162
- `meta.messages.rmRf`) and an explicit location (`node.loc`, `ShellSourceCode`'s
163
- `{ start: { line, column }, end: { line, column } }` shape) — the two pieces every ESLint lint
164
- message needs.
146
+ - `context.report({ node: command, messageId: 'rmRf' })` highlights the original command word
147
+ and uses the message text from `meta.messages.rmRf`.
165
148
 
166
149
  ## 3. Wire it into a flat config
167
150
 
@@ -206,13 +189,15 @@ export default [
206
189
 
207
190
  ## 4. What "firing" looks like
208
191
 
209
- Given
192
+ Save the following in `script.sh`.
210
193
 
211
194
  ```sh
212
195
  rm -rf "$BUILD_DIR"
213
196
  ```
214
197
 
215
- the rule reports once, at the `CallExpr`'s location, with the message text from
198
+ Run `npx eslint --config eslint.config.mjs script.sh`.
199
+ The `--config` flag selects the step 3 config even if the step 1 `eslint.config.js` is still present.
200
+ The rule reports once, at the `rm` word's location, with the message text from
216
201
  `meta.messages.rmRf`. Given a clean script with no `rm` invocation combining recursive and force
217
202
  short flags, the rule produces no messages at all — both cases are asserted in
218
203
  this package's test suite against a real `eslint` `Linter.verify()` run (not a hand-built approximation of one), using the real
@@ -220,9 +205,8 @@ this package's test suite against a real `eslint` `Linter.verify()` run (not a h
220
205
 
221
206
  ## 5. Every command in the file
222
207
 
223
- The `:command` listener above sees one `CallExpr` at a time. Some rules need every command in the
224
- file together with how each one is reached: inside which function, inside `$(…)`, in which
225
- pipeline stage. `context.sourceCode.getCommandInventory().commands` returns that list, one entry per command in
208
+ The command inventory also describes how each command is reached, including its enclosing
209
+ function, command substitution, or pipeline stage. `context.sourceCode.getCommandInventory().commands` returns that list, one entry per command in
226
210
  source order, from `enumerateCommands` (in `sh-analysis`). This is the represented-command collection,
227
211
  not a completeness claim; inspect `getCommandInventory().uncertainties` for opaque boundaries. Each
228
212
  entry has:
@@ -233,31 +217,16 @@ entry has:
233
217
  `f() { echo "$(date)"; }` has `[{ kind: 'function', names: ['f'] }, { kind: 'cmdSubst' }]`.
234
218
  Function frames list names in declaration order. Anonymous functions have an empty list.
235
219
  - `argv0` and `argv`: the command's words, resolved like `resolveWord` resolves them.
236
- - `resolveInvokedCommand()`: the command that actually runs after transparent wrappers such as
237
- `sudo` or `env`. Its `chainIndices` say where each word of that chain sits in the site's `argv`,
238
- so the command's own arguments are `site.argv.slice(chainIndices.at(-1) + 1)`. `site.argv` is
239
- the whole command line, wrappers included, so slicing from `0` or `1` would hand you
240
- `sudo`'s arguments for `sudo chmod 777 x`.
220
+ - `resolveInvokedCommand()`: follows transparent wrappers such as `sudo` or `env`. The final
221
+ `chainIndices` entry points into `argv`, `argvFacts`, and `node.args`. See
222
+ [Rules about commands](./rules-about-commands.md) for checking whether it identifies a command
223
+ word and matching its basename.
241
224
 
242
225
  An assignment-only statement such as `FOO=1` runs no command and has no entry.
243
226
 
244
227
  `docs/examples/no-curl-in-functions-rule.mjs` reports `curl` anywhere inside a shell function:
245
228
 
246
229
  ```mjs
247
- /**
248
- * The "every command in the file" custom rule from the custom-rule tutorial
249
- * (`../custom-rule-tutorial.md`, step 5). Plain, directly-runnable
250
- * JavaScript; this package's test suite imports this exact file and
251
- * asserts the tutorial's code fence matches it byte-for-byte.
252
- *
253
- * It reports `curl` run anywhere inside a shell function, including through a
254
- * wrapper (`sudo curl …`) or inside a command substitution in that function.
255
- * Instead of tracking "am I inside a function?" while visiting nodes, it reads
256
- * every command once from `context.sourceCode.getCommandInventory().commands`, whose
257
- * `context` frames (outermost first) already say how each command is reached.
258
- *
259
- * @see ../custom-rule-tutorial.md — the tutorial this rule backs
260
- */
261
230
  import { defineShellRule } from '@eslint-sh/eslint-plugin';
262
231
 
263
232
  const noCurlInFunctions = defineShellRule({
@@ -276,10 +245,19 @@ const noCurlInFunctions = defineShellRule({
276
245
  return {
277
246
  File() {
278
247
  for (const site of context.sourceCode.getCommandInventory().commands) {
279
- const { effective } = site.resolveInvokedCommand();
280
- if (!effective.static || effective.text !== 'curl') {
281
- continue;
282
- }
248
+ const { effective, chainIndices } = site.resolveInvokedCommand();
249
+ const index = chainIndices.at(-1);
250
+ if (index === undefined || (!effective.static && chainIndices.length > 1)) continue;
251
+
252
+ const facts = site.argvFacts.at(index);
253
+ if (facts?.resolution !== effective) continue;
254
+
255
+ const text = effective.static ? effective.text : undefined;
256
+ const name = facts.basename.known
257
+ ? facts.basename.text
258
+ : text?.slice(text.lastIndexOf('/') + 1);
259
+ const command = site.node.args.at(index);
260
+ if (name !== 'curl' || !command) continue;
283
261
 
284
262
  // Frames run outermost first, so the last `function` frame is the
285
263
  // function that directly contains this command.
@@ -287,9 +265,9 @@ const noCurlInFunctions = defineShellRule({
287
265
  if (fn) {
288
266
  const [name] = fn.names;
289
267
  if (typeof name === 'string') {
290
- context.report({ node: site.node, messageId: 'curlInFunction', data: { name } });
268
+ context.report({ node: command, messageId: 'curlInFunction', data: { name } });
291
269
  } else {
292
- context.report({ node: site.node, messageId: 'curlInUnnamedFunction' });
270
+ context.report({ node: command, messageId: 'curlInUnnamedFunction' });
293
271
  }
294
272
  }
295
273
  }
@@ -305,13 +283,12 @@ Register it the same way as the rule in step 3. For
305
283
 
306
284
  ```sh
307
285
  fetch() {
308
- sudo curl -fsSL "$1"
286
+ sudo /usr/bin/curl -fsSL "$1"
309
287
  }
310
288
  curl -fsSL https://example.com
311
289
  ```
312
290
 
313
- it reports once, on line 2: the `curl` in `fetch` runs through `sudo`, and the top-level `curl` is
314
- outside any function. This package's test suite runs this case through a real `eslint`
291
+ it reports once, on `/usr/bin/curl` inside `fetch`. The top-level `curl` is outside any function. This package's test suite runs this case through a real `eslint`
315
292
  `Linter`.
316
293
 
317
294
  ## 6. Report on an operator
@@ -710,36 +687,36 @@ TypeScript rule needs no `@eslint/core` import and no rule types of its own:
710
687
  `docs/examples/no-listed-commands-rule.ts`:
711
688
 
712
689
  ```ts
713
- /**
714
- * The TypeScript custom rule from the custom-rule tutorial
715
- * (`../custom-rule-tutorial.md`, step 10). This package's test suite
716
- * asserts the tutorial's code fence matches this file byte-for-byte,
717
- * type-checks it against the package's published declarations, and runs it
718
- * through a real `eslint` `Linter`.
719
- *
720
- * It reports any command named in its `commands` option, including through a
721
- * wrapper such as `sudo`. Every type comes from `@eslint-sh/eslint-plugin`:
722
- * the options and message ids passed to `defineShellRule` flow into
723
- * `context.options` and `context.report`, and `ShellRuleContext` types the
724
- * helper that reports outside `create()`.
725
- *
726
- * @see ../custom-rule-tutorial.md — the tutorial this rule backs
727
- */
728
690
  import { defineShellRule } from '@eslint-sh/eslint-plugin';
729
691
  import type { ShellCommandSite, ShellRuleContext } from '@eslint-sh/eslint-plugin';
730
692
 
731
693
  /** The rule's one options object; `commands` defaults to `[]`. */
732
694
  type Options = [{ commands?: string[] }?];
733
695
 
734
- /** Reports the program named by `site`, after wrappers, including interpreters running strings. */
696
+ /** Reports the effective command when its basename or full static path is listed. */
735
697
  function reportIfListed(
736
698
  context: ShellRuleContext<Options, 'listed'>,
737
699
  site: ShellCommandSite,
738
700
  listed: ReadonlySet<string>,
739
701
  ): void {
740
- const { effective } = site.resolveInvokedCommand({ embeddedCommandInterpreters: [] });
741
- if (effective.static && listed.has(effective.text)) {
742
- context.report({ node: site.node, messageId: 'listed', data: { name: effective.text } });
702
+ // The policy also matches the interpreter itself when it runs a command string.
703
+ const { effective, chainIndices } = site.resolveInvokedCommand({
704
+ embeddedCommandInterpreters: [],
705
+ });
706
+ const index = chainIndices.at(-1);
707
+ if (index === undefined || (!effective.static && chainIndices.length > 1)) return;
708
+
709
+ const facts = site.argvFacts.at(index);
710
+ if (facts?.resolution !== effective) return;
711
+
712
+ const text = effective.static ? effective.text : undefined;
713
+ const basename = facts.basename.known
714
+ ? facts.basename.text
715
+ : text?.slice(text.lastIndexOf('/') + 1);
716
+ const name = [text, basename].find((entry) => entry !== undefined && listed.has(entry));
717
+ const command = site.node.args.at(index);
718
+ if (name !== undefined && command) {
719
+ context.report({ node: command, messageId: 'listed', data: { name } });
743
720
  }
744
721
  }
745
722
 
@@ -776,9 +753,11 @@ export default noListedCommands;
776
753
  ```
777
754
 
778
755
  Enable it with its options, the same way as the rule in step 3:
779
- `'my-rules/no-listed-commands': ['error', { commands: ['telnet'] }]`. For `sudo telnet example.com`
780
- it reports `` `telnet` is not allowed in this project. ``, because `resolveInvokedCommand()` sees
781
- through `sudo`.
756
+ `'my-rules/no-listed-commands': ['error', { commands: ['telnet'] }]`. For
757
+ `sudo /usr/bin/telnet example.com` it reports `` `telnet` is not allowed in this project. ``
758
+ at `/usr/bin/telnet`. A bare name matches the basename. A configured path matches the full
759
+ static command text, so listing `/usr/bin/telnet` limits the match to that spelling after
760
+ word resolution.
782
761
 
783
762
  ## 11. Test your rule
784
763
 
@@ -943,3 +922,14 @@ Both appear when the test file runs, before any case is checked. A rule built wi
943
922
  declares `meta.languages: ['sh/sh']`, so ESLint refuses to run it under any other language.
944
923
 
945
924
  See [error codes](error-codes.md) for stable failure identities, source-helper argument boundaries, and dependency pass-through behavior.
925
+
926
+
927
+ ## Policy exceptions
928
+
929
+ Use your custom rule to report the prohibited operation. Select
930
+ `processor: 'sh/require-disable-justification'` on the same flat-config entry to require a
931
+ reason after `--` on each disable comment, including comments that disable all rules.
932
+ Use `createDisableJustificationProcessor({ rules: ['policy/*'] })` to scope the requirement
933
+ to your policy plugin. ESLint applies the directive to your rule before the processor
934
+ checks the comment. See [disable justification](./disable-justification.md) for the
935
+ configuration and options.