@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,3 +1,44 @@
1
+ /**
2
+ * `sh/prefer-local`: a variable assigned inside a function must be declared
3
+ * `local` (or `declare`/`typeset`) in that function, so the function does not
4
+ * overwrite a global its caller may depend on. Shell variables are global by
5
+ * default, and a helper that assigns `i`, `tmp` or `result` silently corrupts
6
+ * the same-named variable of every caller.
7
+ *
8
+ * **What counts as an assignment** inside a function body:
9
+ *
10
+ * - a plain assignment statement (`x=1`, `x+=1`, `x=$(cmd)`); an assignment
11
+ * that prefixes a command (`x=1 cmd`) only reaches that command's
12
+ * environment and is not reported;
13
+ * - the variables named by `read` (`read -r a b`, `read -a arr`);
14
+ * - the loop variable of `for x in …` / `select x in …`.
15
+ *
16
+ * **What is exempt:** a name that is declared `local`, `declare` or `typeset`
17
+ * earlier in the function; a name assigned at top level before the function is
18
+ * defined (an intentional global); a name declared with `declare -g`/
19
+ * `typeset -g` or by `export`/`readonly` (an explicit global); and a name the
20
+ * `allow` option lists or the `allowPattern` option matches (UPPER_CASE
21
+ * globals by default). Each function is its own scope: nested function
22
+ * definitions are checked on their own, and subshells, command substitutions
23
+ * and process substitutions are skipped because their assignments cannot leak.
24
+ * So is every element of a pipeline (`cmd | read x`, `ls | while read l; …`):
25
+ * pipeline elements run in subshells, except that the last one runs in the
26
+ * current shell when the file enables `shopt -s lastpipe`.
27
+ * A function whose body is a subshell (`f() ( … )`) is skipped for the same
28
+ * reason.
29
+ *
30
+ * Only the first assignment to a name in a function is reported: the
31
+ * declaration that fixes it covers the rest.
32
+ *
33
+ * Adding a local declaration can change reads through dynamic scope and
34
+ * which writes remain visible to the caller. Choosing that scope is a manual
35
+ * edit.
36
+ *
37
+ * `local` is not POSIX, so the rule is inert under `dialect: "posix"`.
38
+ *
39
+ * The language resolves command names and words in their AST positions.
40
+ */
41
+ import { resolveWordTextAtPosition } from '../language/word-resolution.js';
1
42
  import { childNodes, walkShell } from '../language/syntax-view.js';
2
43
  import { createRule } from './create-rule.js';
3
44
  import { compileUserPattern } from './user-pattern.js';
@@ -23,18 +64,24 @@ const READ_OPTIONS_WITH_ARGUMENT = new Set([
23
64
  * the rest of the cluster, or else the next word. `-a`'s array name is an
24
65
  * ordinary target word. Words that are not static are not guessed at.
25
66
  */
26
- function readTargets(args, sourceCode) {
67
+ function readTargets(args, sourceCode, canReadCoprocess) {
27
68
  const targets = [];
28
69
  let optionsEnded = false;
29
- let nextIsOptionArgument = false;
70
+ let argumentTo;
71
+ const unprovenMkshCoprocess = sourceCode.dialect === 'mksh' && !canReadCoprocess;
30
72
  for (const word of args.slice(1)) {
31
- const text = sourceCode.resolveWordText(word);
32
- if (nextIsOptionArgument) {
33
- nextIsOptionArgument = false;
73
+ const text = resolveWordTextAtPosition(sourceCode, word);
74
+ if (argumentTo !== undefined) {
75
+ if (unprovenMkshCoprocess && argumentTo === 'u' && (text === null || text === 'p'))
76
+ return [];
77
+ argumentTo = undefined;
34
78
  continue;
35
79
  }
36
- if (text === null)
80
+ if (text === null) {
81
+ if (unprovenMkshCoprocess && !optionsEnded)
82
+ return [];
37
83
  continue;
84
+ }
38
85
  if (!optionsEnded && text === '--') {
39
86
  optionsEnded = true;
40
87
  continue;
@@ -42,8 +89,15 @@ function readTargets(args, sourceCode) {
42
89
  if (!optionsEnded && text.startsWith('-') && text.length > 1) {
43
90
  for (let index = 1; index < text.length; index += 1) {
44
91
  const letter = text.charAt(index);
45
- if (READ_OPTIONS_WITH_ARGUMENT.has(letter)) {
46
- nextIsOptionArgument = index === text.length - 1;
92
+ const coprocess = letter === 'p' && (sourceCode.dialect === 'zsh' || sourceCode.dialect === 'mksh');
93
+ if (coprocess && !canReadCoprocess)
94
+ return [];
95
+ if (!coprocess && READ_OPTIONS_WITH_ARGUMENT.has(letter)) {
96
+ const attached = text.slice(index + 1);
97
+ if (unprovenMkshCoprocess && letter === 'u' && attached === 'p')
98
+ return [];
99
+ if (attached === '')
100
+ argumentTo = letter;
47
101
  break;
48
102
  }
49
103
  }
@@ -59,7 +113,7 @@ function readTargets(args, sourceCode) {
59
113
  * `declare`/`typeset` with a `-g` flag, and every non-scoped declaration
60
114
  * (`export`, `readonly`), bind their names as intentional globals.
61
115
  */
62
- function bindingsOf(node, sourceCode) {
116
+ function bindingsOf(node, sourceCode, coprocessReads) {
63
117
  if (node.type === 'ForClause') {
64
118
  const { loop } = node;
65
119
  if (loop?.type !== 'WordIter' || loop.name === undefined)
@@ -72,13 +126,15 @@ function bindingsOf(node, sourceCode) {
72
126
  ? []
73
127
  : [{ name: assign.name.value, kind: 'assign', node: assign }]);
74
128
  }
75
- return sourceCode.getCommandName(node) === 'read' ? readTargets(node.args, sourceCode) : [];
129
+ return sourceCode.getCommandName(node) === 'read'
130
+ ? readTargets(node.args, sourceCode, sourceCode.dialect !== 'mksh' || coprocessReads.has(node))
131
+ : [];
76
132
  }
77
133
  if (node.type === 'DeclClause') {
78
134
  const variant = node.variant?.value;
79
135
  const flags = node.args
80
136
  .filter((arg) => arg.naked && arg.name === undefined && arg.value !== undefined)
81
- .map((arg) => (arg.value === undefined ? null : sourceCode.resolveWordText(arg.value)));
137
+ .map((arg) => arg.value === undefined ? null : resolveWordTextAtPosition(sourceCode, arg.value));
82
138
  const isGlobal = variant === undefined ||
83
139
  !SCOPED_DECLARATIONS.has(variant) ||
84
140
  flags.some((flag) => flag !== null && /^-[A-Za-z]*g/u.test(flag));
@@ -114,12 +170,75 @@ function enablesLastpipe(root, sourceCode) {
114
170
  walkShell(root, (node) => {
115
171
  if (node.type !== 'CallExpr' || sourceCode.getCommandName(node) !== 'shopt')
116
172
  return;
117
- const words = node.args.slice(1).map((word) => sourceCode.resolveWordText(word));
173
+ const words = node.args.slice(1).map((word) => resolveWordTextAtPosition(sourceCode, word));
118
174
  if (words.includes('-s') && words.includes('lastpipe'))
119
175
  enabled = true;
120
176
  });
121
177
  return enabled;
122
178
  }
179
+ /** An unconditional statement in the current shell, with no redirection to set up. */
180
+ function plainStatement(stmt) {
181
+ return !stmt.background && !stmt.disown && !stmt.negated && stmt.redirs.length === 0;
182
+ }
183
+ /**
184
+ * mksh starts with no coprocess. A direct launch can supply a following read
185
+ * before an intervening command can replace or consume its pipe. Follow only
186
+ * the first command of a directly invoked function, and stop at opaque code.
187
+ */
188
+ function provenMkshCoprocessReads(source) {
189
+ const reads = new Set();
190
+ const functions = new Map();
191
+ if (source.dialect !== 'mksh')
192
+ return reads;
193
+ function literalCall(stmt) {
194
+ if (stmt === undefined || !plainStatement(stmt) || stmt.cmd?.type !== 'CallExpr')
195
+ return undefined;
196
+ const call = stmt.cmd;
197
+ return call.assigns.length === 0 &&
198
+ call.args.every((word) => resolveWordTextAtPosition(source, word) !== null)
199
+ ? call
200
+ : undefined;
201
+ }
202
+ let live = false;
203
+ for (const stmt of source.ast.stmts) {
204
+ if (!plainStatement(stmt))
205
+ break;
206
+ if (!stmt.coprocess && stmt.cmd?.type === 'FuncDecl') {
207
+ const { name, body } = stmt.cmd;
208
+ if (name === undefined || body === undefined)
209
+ break;
210
+ functions.set(name.value, body);
211
+ continue;
212
+ }
213
+ const call = literalCall(stmt);
214
+ if (call === undefined)
215
+ break;
216
+ if (stmt.coprocess) {
217
+ live = true;
218
+ continue;
219
+ }
220
+ const name = source.getCommandName(call);
221
+ if (name === null)
222
+ break;
223
+ const body = functions.get(name);
224
+ if (body === undefined || !plainStatement(body) || body.coprocess)
225
+ break;
226
+ const statements = body.cmd?.type === 'Block' ? body.cmd.stmts : [body];
227
+ const first = statements.at(0);
228
+ const startsCoprocess = (first?.coprocess ?? false) && literalCall(first) !== undefined;
229
+ const readStatement = statements[startsCoprocess ? 1 : 0];
230
+ const read = literalCall(readStatement);
231
+ if ((live || startsCoprocess) &&
232
+ read !== undefined &&
233
+ !readStatement.coprocess &&
234
+ source.getCommandName(read) === 'read' &&
235
+ !functions.has('read')) {
236
+ reads.add(read);
237
+ }
238
+ break;
239
+ }
240
+ return reads;
241
+ }
123
242
  /**
124
243
  * Every binding in `root`'s own scope, in source order. Nested function
125
244
  * definitions and isolated scopes (subshells, substitutions, background jobs)
@@ -127,7 +246,7 @@ function enablesLastpipe(root, sourceCode) {
127
246
  * Pipeline elements run in subshells, so only the last element of a pipeline
128
247
  * is entered, and only when `lastpipe` is enabled.
129
248
  */
130
- function scopeBindings(root, sourceCode, lastpipe) {
249
+ function scopeBindings(root, sourceCode, lastpipe, coprocessReads) {
131
250
  const found = [];
132
251
  // Pre-order with an explicit stack: children are pushed in reverse so they pop in source order.
133
252
  const pending = [root];
@@ -141,7 +260,7 @@ function scopeBindings(root, sourceCode, lastpipe) {
141
260
  pending.push(node.y);
142
261
  continue;
143
262
  }
144
- found.push(...bindingsOf(node, sourceCode));
263
+ found.push(...bindingsOf(node, sourceCode, coprocessReads));
145
264
  const children = childNodes(node);
146
265
  for (let index = children.length - 1; index >= 0; index--)
147
266
  pending.push(children[index]);
@@ -182,6 +301,7 @@ const preferLocal = createRule({
182
301
  if (sourceCode.dialect === 'posix')
183
302
  return {};
184
303
  const lastpipe = enablesLastpipe(sourceCode.ast, sourceCode);
304
+ const coprocessReads = provenMkshCoprocessReads(sourceCode);
185
305
  // Names assigned or declared outside every function, with where each
186
306
  // binding ends: assigned before a function is defined, they are globals
187
307
  // the function is meant to share.
@@ -189,7 +309,7 @@ const preferLocal = createRule({
189
309
  let topLevelCollected = false;
190
310
  const topLevelBefore = (position) => {
191
311
  if (!topLevelCollected) {
192
- topLevelBindings.push(...scopeBindings(sourceCode.ast, sourceCode, lastpipe));
312
+ topLevelBindings.push(...scopeBindings(sourceCode.ast, sourceCode, lastpipe, coprocessReads));
193
313
  topLevelCollected = true;
194
314
  }
195
315
  return new Set(topLevelBindings.filter((b) => b.node.range[1] <= position).map((b) => b.name));
@@ -202,7 +322,7 @@ const preferLocal = createRule({
202
322
  const global = topLevelBefore(func.range[0]);
203
323
  const declared = new Set();
204
324
  const functionName = func.name?.value ?? '';
205
- for (const binding of scopeBindings(body, sourceCode, lastpipe)) {
325
+ for (const binding of scopeBindings(body, sourceCode, lastpipe, coprocessReads)) {
206
326
  const { name } = binding;
207
327
  if (binding.kind !== 'assign') {
208
328
  declared.add(name);
@@ -3,9 +3,9 @@ export interface RequireStrictModeOptions {
3
3
  /**
4
4
  * Nonempty, unique long option names from the existing `set -o` domain.
5
5
  * When absent, POSIX requires errexit/nounset and other dialects also require
6
- * pipefail. The formatter, rather than consumer text, owns autofix spelling.
6
+ * pipefail. The formatter, rather than consumer text, owns the inserted spelling.
7
7
  */
8
8
  readonly requiredOptions?: readonly string[];
9
9
  }
10
10
  /** Built-in rule `sh/require-strict-mode`. @internal */
11
- export declare const requireStrictMode: import("./define-shell-rule.js").ShellRule<[RequireStrictModeOptions], "missingStrictMode">;
11
+ export declare const requireStrictMode: import("./define-shell-rule.js").ShellRule<[RequireStrictModeOptions], "missingStrictMode" | "enableStrictMode">;
@@ -1,6 +1,6 @@
1
1
  import { createRule } from './create-rule.js';
2
2
  import { SET_OPTION_NAMES, formatSetCommand, shebangOptionChanges } from './set-options.js';
3
- import { enabledAfter, resolveStrictModePrologue, setStatementChanges, } from './strict-mode-prologue.js';
3
+ import { enabledAfter, resolveStrictModePrologue, setStatementArguments, } from './strict-mode-prologue.js';
4
4
  import { shellLineBreakOf } from '../language/line-breaks.js';
5
5
  /**
6
6
  * Dialect-aware policy defaults. Bats runs under Bash; POSIX omits pipefail
@@ -17,7 +17,7 @@ export const requireStrictMode = createRule({
17
17
  docs: {
18
18
  description: 'require the configured strict-mode options (`set -euo pipefail` by default, `set -eu` for POSIX) near the top of the file',
19
19
  },
20
- fixable: 'code',
20
+ hasSuggestions: true,
21
21
  schema: [
22
22
  {
23
23
  type: 'object',
@@ -35,6 +35,7 @@ export const requireStrictMode = createRule({
35
35
  // Absence must survive defaulting so each file's dialect selects its policy.
36
36
  defaultOptions: [{}],
37
37
  messages: {
38
+ enableStrictMode: 'Insert `{{prologue}}` to change the shell options for this script.',
38
39
  missingStrictMode: 'Enable strict mode with `{{prologue}}` within {{window}}; not enabled: {{missing}}.',
39
40
  },
40
41
  },
@@ -49,7 +50,8 @@ export const requireStrictMode = createRule({
49
50
  const text = sourceCode.text;
50
51
  const shebangChanges = allowShebangOnly ? shebangOptionChanges(text) : [];
51
52
  const statements = node.stmts.slice(0, withinStatements);
52
- const statementChanges = statements.map((stmt) => setStatementChanges(stmt, sourceCode));
53
+ const argumentsByStatement = statements.map((stmt) => setStatementArguments(stmt, sourceCode));
54
+ const statementChanges = argumentsByStatement.map((args) => args?.changes ?? []);
53
55
  const enabled = enabledAfter(shebangChanges, statementChanges);
54
56
  const missing = required.filter((option) => !enabled.has(option));
55
57
  if (missing.length === 0)
@@ -58,7 +60,8 @@ export const requireStrictMode = createRule({
58
60
  // holds one fewer original statement. Fix only if that would pass.
59
61
  const prologueChanges = required.map((option) => ({ option, enable: true }));
60
62
  const fixedEnabled = enabledAfter([...shebangChanges, ...prologueChanges], statementChanges.slice(0, withinStatements - 1));
61
- const fixSatisfies = required.every((option) => fixedEnabled.has(option));
63
+ const insertionSatisfies = argumentsByStatement.every((args) => args?.stoppedBy !== 'unknown') &&
64
+ required.every((option) => fixedEnabled.has(option));
62
65
  context.report({
63
66
  loc: { line: 1, column: 1 },
64
67
  messageId: 'missingStrictMode',
@@ -69,20 +72,26 @@ export const requireStrictMode = createRule({
69
72
  : `the first ${String(withinStatements)} statements`,
70
73
  missing: missing.join(', '),
71
74
  },
72
- fix: fixSatisfies
73
- ? (fixer) => {
74
- let bodyStart = 0;
75
- if (text.startsWith('#!')) {
76
- const headerEnd = text.indexOf('\n');
77
- if (headerEnd === -1) {
78
- return fixer.insertTextAfterRange([0, text.length], '\n' + prologue);
79
- }
80
- bodyStart = headerEnd + 1;
81
- }
82
- const lineBreak = shellLineBreakOf(text, bodyStart);
83
- return fixer.insertTextBeforeRange([bodyStart, bodyStart], prologue + lineBreak);
84
- }
85
- : null,
75
+ suggest: insertionSatisfies
76
+ ? [
77
+ {
78
+ messageId: 'enableStrictMode',
79
+ data: { prologue },
80
+ fix: (fixer) => {
81
+ let bodyStart = 0;
82
+ if (text.startsWith('#!')) {
83
+ const headerEnd = text.indexOf('\n');
84
+ if (headerEnd === -1) {
85
+ return fixer.insertTextAfterRange([0, text.length], '\n' + prologue);
86
+ }
87
+ bodyStart = headerEnd + 1;
88
+ }
89
+ const lineBreak = shellLineBreakOf(text, bodyStart);
90
+ return fixer.insertTextBeforeRange([bodyStart, bodyStart], prologue + lineBreak);
91
+ },
92
+ },
93
+ ]
94
+ : [],
86
95
  });
87
96
  },
88
97
  };
@@ -11,5 +11,7 @@ export interface RequireTtyGuardOptions {
11
11
  }
12
12
  /** Message ids of this rule. @internal */
13
13
  export type RequireTtyGuardMessageId = 'unguardedInteractive' | 'wrapInTtyGuard';
14
+ /** What the rule can establish about the command's input source. @internal */
15
+ export type InputSource = 'stdin' | 'explicit' | 'unknown' | 'terminal';
14
16
  /** Built-in rule `sh/require-tty-guard`. @internal */
15
17
  export declare const requireTtyGuard: import("./define-shell-rule.js").ShellRule<[RequireTtyGuardOptions?], RequireTtyGuardMessageId>;