@eslint-sh/eslint-plugin 0.12.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 (83) hide show
  1. package/README.md +32 -12
  2. package/dist/api.d.ts +11 -1
  3. package/dist/api.js +8 -0
  4. package/dist/command-harvest/harvest-commands.d.ts +5 -3
  5. package/dist/command-harvest/harvest-commands.js +34 -12
  6. package/dist/eslint-plugin-api.d.ts +65 -12
  7. package/dist/language/command-resolution.d.ts +24 -6
  8. package/dist/language/command-resolution.js +44 -17
  9. package/dist/language/shell-language.js +2 -0
  10. package/dist/language/shell-source-code.d.ts +29 -11
  11. package/dist/language/shell-source-code.js +35 -26
  12. package/dist/language/word-resolution.d.ts +18 -12
  13. package/dist/language/word-resolution.js +133 -3
  14. package/dist/processors/disable-justification.d.ts +20 -0
  15. package/dist/processors/disable-justification.js +124 -0
  16. package/dist/rules/compat/bash-builtin-destination.d.ts +19 -0
  17. package/dist/rules/compat/bash-builtin-destination.js +83 -0
  18. package/dist/rules/compat/declaration-options.d.ts +2 -2
  19. package/dist/rules/compat/declaration-options.js +23 -17
  20. package/dist/rules/compat/no-case-attributes.js +2 -4
  21. package/dist/rules/compat/no-mapfile.js +52 -20
  22. package/dist/rules/compat/no-negative-array-index.d.ts +3 -8
  23. package/dist/rules/compat/no-negative-array-index.js +7 -30
  24. package/dist/rules/compat/no-nounset-empty-array.js +10 -7
  25. package/dist/rules/compat/no-parameter-transformation.js +2 -1
  26. package/dist/rules/compat/no-printf-time-format.js +55 -16
  27. package/dist/rules/compat/no-source.d.ts +3 -8
  28. package/dist/rules/compat/no-source.js +3 -40
  29. package/dist/rules/compat/no-test-v.js +257 -71
  30. package/dist/rules/compat/no-wait-n.js +43 -12
  31. package/dist/rules/compat/nounset-array-proof.d.ts +3 -1
  32. package/dist/rules/compat/nounset-array-proof.js +84 -63
  33. package/dist/rules/compat/posix-absent-command.js +3 -2
  34. package/dist/rules/compat/shopt-options.js +3 -2
  35. package/dist/rules/create-wrapper-rule.js +16 -9
  36. package/dist/rules/no-dynamic-invocation.js +8 -9
  37. package/dist/rules/no-eval.js +19 -8
  38. package/dist/rules/no-masked-exit-status.js +29 -17
  39. package/dist/rules/no-secret-flags.js +4 -3
  40. package/dist/rules/no-unchecked-cd.d.ts +8 -3
  41. package/dist/rules/no-unchecked-cd.js +65 -25
  42. package/dist/rules/no-unused-declarations.js +51 -19
  43. package/dist/rules/prefer-local.js +136 -16
  44. package/dist/rules/require-strict-mode.d.ts +2 -2
  45. package/dist/rules/require-strict-mode.js +27 -18
  46. package/dist/rules/require-tty-guard.d.ts +2 -0
  47. package/dist/rules/require-tty-guard.js +211 -45
  48. package/dist/rules/set-options.d.ts +3 -1
  49. package/dist/rules/set-options.js +5 -1
  50. package/dist/rules/strict-mode-prologue.d.ts +9 -2
  51. package/dist/rules/strict-mode-prologue.js +45 -8
  52. package/docs/custom-rule-tutorial.md +148 -155
  53. package/docs/disable-justification.md +71 -0
  54. package/docs/error-codes.md +4 -0
  55. package/docs/examples/eslint.config.js +11 -0
  56. package/docs/examples/no-curl-in-functions-rule.mjs +20 -23
  57. package/docs/examples/no-listed-commands-rule.ts +19 -19
  58. package/docs/examples/no-rm-rf-rule.mjs +33 -62
  59. package/docs/examples/no-sample-command-rule.mjs +33 -0
  60. package/docs/reading-nodes.md +26 -1
  61. package/docs/rules/README.md +4 -4
  62. package/docs/rules/compat/no-mapfile.md +14 -20
  63. package/docs/rules/compat/no-negative-array-index.md +9 -22
  64. package/docs/rules/compat/no-nounset-empty-array.md +5 -5
  65. package/docs/rules/compat/no-printf-time-format.md +2 -1
  66. package/docs/rules/compat/no-source.md +8 -17
  67. package/docs/rules/compat/no-test-v.md +8 -2
  68. package/docs/rules/compat/no-wait-n.md +3 -1
  69. package/docs/rules/no-dynamic-invocation.md +3 -0
  70. package/docs/rules/no-eval.md +22 -1
  71. package/docs/rules/no-masked-exit-status.md +2 -1
  72. package/docs/rules/no-secret-flags.md +22 -2
  73. package/docs/rules/no-unchecked-cd.md +3 -1
  74. package/docs/rules/no-undeclared-commands.md +1 -1
  75. package/docs/rules/no-unused-declarations.md +10 -6
  76. package/docs/rules/prefer-local.md +4 -0
  77. package/docs/rules/require-network-wrapper.md +1 -1
  78. package/docs/rules/require-strict-mode.md +19 -11
  79. package/docs/rules/require-tty-guard.md +26 -4
  80. package/docs/rules-about-commands.md +78 -0
  81. package/docs/selectors.md +8 -4
  82. package/docs/wrapper-rules.md +1 -1
  83. package/package.json +4 -4
@@ -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:
@@ -230,33 +214,19 @@ entry has:
230
214
  - `node`: the `CallExpr` node, the same object a `CallExpr` listener receives, so you can report
231
215
  on it.
232
216
  - `context`: the frames that lead to the command, outermost first. `date` in
233
- `f() { echo "$(date)"; }` has `[{ kind: 'function', name: 'f' }, { kind: 'cmdSubst' }]`.
217
+ `f() { echo "$(date)"; }` has `[{ kind: 'function', names: ['f'] }, { kind: 'cmdSubst' }]`.
218
+ Function frames list names in declaration order. Anonymous functions have an empty list.
234
219
  - `argv0` and `argv`: the command's words, resolved like `resolveWord` resolves them.
235
- - `resolveInvokedCommand()`: the command that actually runs after transparent wrappers such as
236
- `sudo` or `env`. Its `chainIndices` say where each word of that chain sits in the site's `argv`,
237
- so the command's own arguments are `site.argv.slice(chainIndices.at(-1) + 1)`. `site.argv` is
238
- the whole command line, wrappers included, so slicing from `0` or `1` would hand you
239
- `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.
240
224
 
241
225
  An assignment-only statement such as `FOO=1` runs no command and has no entry.
242
226
 
243
227
  `docs/examples/no-curl-in-functions-rule.mjs` reports `curl` anywhere inside a shell function:
244
228
 
245
229
  ```mjs
246
- /**
247
- * The "every command in the file" custom rule from the custom-rule tutorial
248
- * (`../custom-rule-tutorial.md`, step 5). Plain, directly-runnable
249
- * JavaScript; this package's test suite imports this exact file and
250
- * asserts the tutorial's code fence matches it byte-for-byte.
251
- *
252
- * It reports `curl` run anywhere inside a shell function, including through a
253
- * wrapper (`sudo curl …`) or inside a command substitution in that function.
254
- * Instead of tracking "am I inside a function?" while visiting nodes, it reads
255
- * every command once from `context.sourceCode.getCommandInventory().commands`, whose
256
- * `context` frames (outermost first) already say how each command is reached.
257
- *
258
- * @see ../custom-rule-tutorial.md — the tutorial this rule backs
259
- */
260
230
  import { defineShellRule } from '@eslint-sh/eslint-plugin';
261
231
 
262
232
  const noCurlInFunctions = defineShellRule({
@@ -268,26 +238,37 @@ const noCurlInFunctions = defineShellRule({
268
238
  schema: [],
269
239
  messages: {
270
240
  curlInFunction: 'Function `{{name}}` runs `curl`; fetch data before calling it.',
241
+ curlInUnnamedFunction: 'This function runs `curl`; fetch data before calling it.',
271
242
  },
272
243
  },
273
244
  create(context) {
274
245
  return {
275
246
  File() {
276
247
  for (const site of context.sourceCode.getCommandInventory().commands) {
277
- const { effective } = site.resolveInvokedCommand();
278
- if (!effective.static || effective.text !== 'curl') {
279
- continue;
280
- }
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;
281
261
 
282
262
  // Frames run outermost first, so the last `function` frame is the
283
263
  // function that directly contains this command.
284
264
  const fn = site.context.findLast((frame) => frame.kind === 'function');
285
265
  if (fn) {
286
- context.report({
287
- node: site.node,
288
- messageId: 'curlInFunction',
289
- data: { name: fn.name },
290
- });
266
+ const [name] = fn.names;
267
+ if (typeof name === 'string') {
268
+ context.report({ node: command, messageId: 'curlInFunction', data: { name } });
269
+ } else {
270
+ context.report({ node: command, messageId: 'curlInUnnamedFunction' });
271
+ }
291
272
  }
292
273
  }
293
274
  },
@@ -302,13 +283,12 @@ Register it the same way as the rule in step 3. For
302
283
 
303
284
  ```sh
304
285
  fetch() {
305
- sudo curl -fsSL "$1"
286
+ sudo /usr/bin/curl -fsSL "$1"
306
287
  }
307
288
  curl -fsSL https://example.com
308
289
  ```
309
290
 
310
- it reports once, on line 2: the `curl` in `fetch` runs through `sudo`, and the top-level `curl` is
311
- 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`
312
292
  `Linter`.
313
293
 
314
294
  ## 6. Report on an operator
@@ -413,7 +393,7 @@ import { walk, printSync, type Node, type PrintOptions } from 'sh-ast';
413
393
  import { enumerateCommands, resolveArgv0, type CommandInventory } from 'sh-analysis';
414
394
  ```
415
395
 
416
- The supported dependency ranges are `sh-ast@^0.11.0` and `sh-analysis@^0.1.0`.
396
+ The supported dependency ranges are `sh-ast@^0.13.0` and `sh-analysis@^0.4.0`.
417
397
  There are no plugin or umbrella syntax forwarding subpaths. Keep using source helpers when you
418
398
  need ESLint nodes, UTF-16 locations or fixes: they map the original syntax by identity.
419
399
 
@@ -707,36 +687,36 @@ TypeScript rule needs no `@eslint/core` import and no rule types of its own:
707
687
  `docs/examples/no-listed-commands-rule.ts`:
708
688
 
709
689
  ```ts
710
- /**
711
- * The TypeScript custom rule from the custom-rule tutorial
712
- * (`../custom-rule-tutorial.md`, step 10). This package's test suite
713
- * asserts the tutorial's code fence matches this file byte-for-byte,
714
- * type-checks it against the package's published declarations, and runs it
715
- * through a real `eslint` `Linter`.
716
- *
717
- * It reports any command named in its `commands` option, including through a
718
- * wrapper such as `sudo`. Every type comes from `@eslint-sh/eslint-plugin`:
719
- * the options and message ids passed to `defineShellRule` flow into
720
- * `context.options` and `context.report`, and `ShellRuleContext` types the
721
- * helper that reports outside `create()`.
722
- *
723
- * @see ../custom-rule-tutorial.md — the tutorial this rule backs
724
- */
725
690
  import { defineShellRule } from '@eslint-sh/eslint-plugin';
726
691
  import type { ShellCommandSite, ShellRuleContext } from '@eslint-sh/eslint-plugin';
727
692
 
728
693
  /** The rule's one options object; `commands` defaults to `[]`. */
729
694
  type Options = [{ commands?: string[] }?];
730
695
 
731
- /** 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. */
732
697
  function reportIfListed(
733
698
  context: ShellRuleContext<Options, 'listed'>,
734
699
  site: ShellCommandSite,
735
700
  listed: ReadonlySet<string>,
736
701
  ): void {
737
- const { effective } = site.resolveInvokedCommand({ embeddedCommandInterpreters: [] });
738
- if (effective.static && listed.has(effective.text)) {
739
- 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 } });
740
720
  }
741
721
  }
742
722
 
@@ -773,9 +753,11 @@ export default noListedCommands;
773
753
  ```
774
754
 
775
755
  Enable it with its options, the same way as the rule in step 3:
776
- `'my-rules/no-listed-commands': ['error', { commands: ['telnet'] }]`. For `sudo telnet example.com`
777
- it reports `` `telnet` is not allowed in this project. ``, because `resolveInvokedCommand()` sees
778
- 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.
779
761
 
780
762
  ## 11. Test your rule
781
763
 
@@ -940,3 +922,14 @@ Both appear when the test file runs, before any case is checked. A rule built wi
940
922
  declares `meta.languages: ['sh/sh']`, so ESLint refuses to run it under any other language.
941
923
 
942
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.
@@ -0,0 +1,71 @@
1
+ # Require reasons for ESLint disable directives
2
+
3
+ Select the `sh/require-disable-justification` processor to require a written reason after
4
+ `--` on every block, same-line, and next-line disable directive in a shell file.
5
+ A justification must contain text beyond whitespace. One reason applies to the whole
6
+ comment, including a comma-separated list of rule IDs.
7
+ `eslint-enable` needs no reason. The processor uses the shell language's configured
8
+ `directivePrefix`.
9
+
10
+ ```js
11
+ import sh from 'eslint-sh';
12
+
13
+ export default [
14
+ {
15
+ files: ['**/*.sh'],
16
+ plugins: { sh },
17
+ language: 'sh/sh',
18
+ processor: 'sh/require-disable-justification',
19
+ },
20
+ ];
21
+ ```
22
+
23
+ The processor reports an error at the comment after ESLint applies inline suppression and
24
+ checks for unused directives. A directive can still suppress the policy rule it names.
25
+ ESLint can still report and fix unused directives. The processor checks written
26
+ directives even when `linterOptions.noInlineConfig` prevents them from taking effect.
27
+
28
+ ## Options
29
+
30
+ Use `createDisableJustificationProcessor({ rules })` to select which rule IDs need reasons.
31
+ Each entry is an exact rule ID or a literal prefix ending in `*`. For example, `policy/*`
32
+ matches every ID starting with `policy/`. A directive is in scope if it disables any
33
+ selected rule. A directive without rule IDs disables all rules, so it is in scope for any
34
+ nonempty selection. Omit `rules` to check all directives or use `[]` to select none.
35
+
36
+ ```js
37
+ import sh, { createDisableJustificationProcessor } from 'eslint-sh';
38
+
39
+ export default [
40
+ {
41
+ files: ['**/*.sh'],
42
+ plugins: { sh },
43
+ language: 'sh/sh',
44
+ processor: createDisableJustificationProcessor({ rules: ['policy/*', 'sh/no-eval'] }),
45
+ },
46
+ ];
47
+ ```
48
+
49
+ ## Examples
50
+
51
+ These comments need reasons with the default processor.
52
+
53
+ ```sh
54
+ # eslint-disable
55
+ run_legacy_task
56
+ # eslint-enable
57
+
58
+ run_legacy_task # eslint-disable-line
59
+ # eslint-disable-next-line policy/no-legacy-task, sh/no-eval
60
+ run_legacy_task
61
+ ```
62
+
63
+ This comment supplies a reason.
64
+
65
+ ```sh
66
+ # eslint-disable-next-line policy/no-legacy-task -- The compatibility test exercises the legacy entry point.
67
+ run_legacy_task
68
+ ```
69
+
70
+ Enable the processor per file group. ESLint selects one processor for a file, so a
71
+ file group that already uses a processor needs to choose which processor to apply.
@@ -67,6 +67,10 @@ plugin's source helpers also preserve analysis resource/invalid-wrapper failures
67
67
  and printed replacements preserve upstream printer errors. Returning a partial
68
68
  command inventory on a depth refusal would silently omit real commands.
69
69
 
70
+ Match dependency failures by `code`. An analysis helper can throw an error from
71
+ the `sh-ast` version installed under `sh-analysis`, so constructor identity can
72
+ differ from the version imported by a rule or by the plugin.
73
+
70
74
  | Dependency code | Meaning |
71
75
  | --- | --- |
72
76
  | `SH_AST_SYNTAX_PARSE` | Invalid shell source. The language presents fatal diagnostics; raw syntax calls retain the error. |
@@ -0,0 +1,11 @@
1
+ import sh from '@eslint-sh/eslint-plugin';
2
+ import noSampleCommand from './no-sample-command-rule.mjs';
3
+
4
+ export default [
5
+ {
6
+ files: ['**/*.sh'],
7
+ plugins: { sh, local: { rules: { 'no-sample-command': noSampleCommand } } },
8
+ language: 'sh/sh',
9
+ rules: { 'local/no-sample-command': 'warn' },
10
+ },
11
+ ];
@@ -1,17 +1,3 @@
1
- /**
2
- * The "every command in the file" custom rule from the custom-rule tutorial
3
- * (`../custom-rule-tutorial.md`, step 5). Plain, directly-runnable
4
- * JavaScript; this package's test suite imports this exact file and
5
- * asserts the tutorial's code fence matches it byte-for-byte.
6
- *
7
- * It reports `curl` run anywhere inside a shell function, including through a
8
- * wrapper (`sudo curl …`) or inside a command substitution in that function.
9
- * Instead of tracking "am I inside a function?" while visiting nodes, it reads
10
- * every command once from `context.sourceCode.getCommandInventory().commands`, whose
11
- * `context` frames (outermost first) already say how each command is reached.
12
- *
13
- * @see ../custom-rule-tutorial.md — the tutorial this rule backs
14
- */
15
1
  import { defineShellRule } from '@eslint-sh/eslint-plugin';
16
2
 
17
3
  const noCurlInFunctions = defineShellRule({
@@ -23,26 +9,37 @@ const noCurlInFunctions = defineShellRule({
23
9
  schema: [],
24
10
  messages: {
25
11
  curlInFunction: 'Function `{{name}}` runs `curl`; fetch data before calling it.',
12
+ curlInUnnamedFunction: 'This function runs `curl`; fetch data before calling it.',
26
13
  },
27
14
  },
28
15
  create(context) {
29
16
  return {
30
17
  File() {
31
18
  for (const site of context.sourceCode.getCommandInventory().commands) {
32
- const { effective } = site.resolveInvokedCommand();
33
- if (!effective.static || effective.text !== 'curl') {
34
- continue;
35
- }
19
+ const { effective, chainIndices } = site.resolveInvokedCommand();
20
+ const index = chainIndices.at(-1);
21
+ if (index === undefined || (!effective.static && chainIndices.length > 1)) continue;
22
+
23
+ const facts = site.argvFacts.at(index);
24
+ if (facts?.resolution !== effective) continue;
25
+
26
+ const text = effective.static ? effective.text : undefined;
27
+ const name = facts.basename.known
28
+ ? facts.basename.text
29
+ : text?.slice(text.lastIndexOf('/') + 1);
30
+ const command = site.node.args.at(index);
31
+ if (name !== 'curl' || !command) continue;
36
32
 
37
33
  // Frames run outermost first, so the last `function` frame is the
38
34
  // function that directly contains this command.
39
35
  const fn = site.context.findLast((frame) => frame.kind === 'function');
40
36
  if (fn) {
41
- context.report({
42
- node: site.node,
43
- messageId: 'curlInFunction',
44
- data: { name: fn.name },
45
- });
37
+ const [name] = fn.names;
38
+ if (typeof name === 'string') {
39
+ context.report({ node: command, messageId: 'curlInFunction', data: { name } });
40
+ } else {
41
+ context.report({ node: command, messageId: 'curlInUnnamedFunction' });
42
+ }
46
43
  }
47
44
  }
48
45
  },