@eslint-sh/eslint-plugin 0.10.1 → 0.12.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 (34) hide show
  1. package/dist/command-harvest/harvest-commands.d.ts +6 -2
  2. package/dist/command-harvest/harvest-commands.js +13 -6
  3. package/dist/eslint-plugin-api.d.ts +11 -3
  4. package/dist/language/line-breaks.d.ts +10 -4
  5. package/dist/language/line-breaks.js +14 -5
  6. package/dist/language/shell-language.d.ts +2 -0
  7. package/dist/language/shell-language.js +10 -1
  8. package/dist/language/shell-source-code.d.ts +11 -3
  9. package/dist/language/shell-source-code.js +102 -30
  10. package/dist/rules/no-masked-exit-status.js +5 -29
  11. package/dist/rules/no-unused-declarations.js +81 -16
  12. package/dist/rules/prefer-local.js +10 -36
  13. package/dist/rules/require-shebang.js +23 -21
  14. package/dist/rules/require-strict-mode.js +11 -8
  15. package/dist/rules/require-tty-guard.js +8 -5
  16. package/dist/rules/set-options.d.ts +2 -15
  17. package/dist/rules/set-options.js +12 -44
  18. package/dist/rules/shebang-interpreter.d.ts +33 -10
  19. package/dist/rules/shebang-interpreter.js +522 -53
  20. package/dist/rules/shebang-matches-dialect.js +4 -4
  21. package/dist/rules/variable-reads.d.ts +12 -0
  22. package/dist/rules/variable-reads.js +31 -0
  23. package/docs/custom-rule-tutorial.md +9 -3
  24. package/docs/error-codes.md +2 -1
  25. package/docs/rules/README.md +1 -1
  26. package/docs/rules/no-masked-exit-status.md +2 -0
  27. package/docs/rules/no-unused-declarations.md +9 -4
  28. package/docs/rules/prefer-local.md +11 -33
  29. package/docs/rules/require-shebang.md +46 -3
  30. package/docs/rules/require-strict-mode.md +23 -6
  31. package/docs/rules/require-tty-guard.md +1 -0
  32. package/docs/rules/shebang-matches-dialect.md +3 -0
  33. package/docs/shellcheck.md +1 -1
  34. package/package.json +3 -3
@@ -1,7 +1,6 @@
1
1
  import { childNodes, walkShell } from '../language/syntax-view.js';
2
2
  import { createRule } from './create-rule.js';
3
3
  import { compileUserPattern } from './user-pattern.js';
4
- import { lineBreakOf } from '../language/line-breaks.js';
5
4
  /** The `allowPattern` used when none is configured: UPPER_CASE globals. */
6
5
  const DEFAULT_ALLOW_PATTERN = '^[A-Z][A-Z0-9_]*$';
7
6
  /** A valid shell variable name; anything else is not a binding target. */
@@ -96,7 +95,12 @@ function bindingsOf(node, sourceCode) {
96
95
  return [];
97
96
  }
98
97
  /** Node types whose contents run in a child process and cannot leak assignments. */
99
- const ISOLATED_SCOPES = new Set(['Subshell', 'CmdSubst', 'ProcSubst']);
98
+ const ISOLATED_SCOPES = new Set([
99
+ 'Subshell',
100
+ 'CmdSubst',
101
+ 'ProcSubst',
102
+ 'CoprocClause',
103
+ ]);
100
104
  /** `BinaryCmd.op` values for `|` and `|&`, the pipeline operators. */
101
105
  const PIPE_OPS = new Set([13, 14]);
102
106
  /**
@@ -118,7 +122,8 @@ function enablesLastpipe(root, sourceCode) {
118
122
  }
119
123
  /**
120
124
  * Every binding in `root`'s own scope, in source order. Nested function
121
- * definitions and isolated scopes (subshells, substitutions) are not entered.
125
+ * definitions and isolated scopes (subshells, substitutions, background jobs)
126
+ * are not entered.
122
127
  * Pipeline elements run in subshells, so only the last element of a pipeline
123
128
  * is entered, and only when `lastpipe` is enabled.
124
129
  */
@@ -129,6 +134,8 @@ function scopeBindings(root, sourceCode, lastpipe) {
129
134
  for (let node = pending.pop(); node !== undefined; node = pending.pop()) {
130
135
  if (node.type === 'FuncDecl' || ISOLATED_SCOPES.has(node.type))
131
136
  continue;
137
+ if (node.type === 'Stmt' && (node.background || node.coprocess || node.disown))
138
+ continue;
132
139
  if (node.type === 'BinaryCmd' && PIPE_OPS.has(node.op)) {
133
140
  if (lastpipe && node.y !== undefined)
134
141
  pending.push(node.y);
@@ -149,7 +156,6 @@ const preferLocal = createRule({
149
156
  docs: {
150
157
  description: 'require variables assigned inside a function to be declared `local`, unless intentionally global',
151
158
  },
152
- fixable: 'code',
153
159
  schema: [
154
160
  {
155
161
  type: 'object',
@@ -175,7 +181,6 @@ const preferLocal = createRule({
175
181
  // `local` is not POSIX: under `posix` there is nothing to declare with.
176
182
  if (sourceCode.dialect === 'posix')
177
183
  return {};
178
- const text = sourceCode.text;
179
184
  const lastpipe = enablesLastpipe(sourceCode.ast, sourceCode);
180
185
  // Names assigned or declared outside every function, with where each
181
186
  // binding ends: assigned before a function is defined, they are globals
@@ -189,26 +194,6 @@ const preferLocal = createRule({
189
194
  }
190
195
  return new Set(topLevelBindings.filter((b) => b.node.range[1] <= position).map((b) => b.name));
191
196
  };
192
- /**
193
- * The one `local` declaration that covers `names`, as `[index, text]`, or
194
- * `null` when the function has no `{ … }` block with a first statement to
195
- * insert before. Every report of a function carries this same insertion
196
- * (with the function's whole name list), because fixes that insert at one
197
- * offset conflict: ESLint applies one per pass and stops after 10, so a
198
- * function with more than 10 names would otherwise never settle.
199
- */
200
- const insertionFor = (func, names) => {
201
- const block = func.body?.cmd;
202
- if (block?.type !== 'Block')
203
- return null;
204
- const first = block.stmts.at(0);
205
- if (first === undefined)
206
- return null;
207
- const lineStart = Math.max(text.lastIndexOf('\n', first.range[0] - 1), text.lastIndexOf('\r', first.range[0] - 1));
208
- const indent = text.slice(lineStart + 1, first.range[0]);
209
- const separator = /^[ \t]*$/u.test(indent) ? lineBreakOf(text) + indent : '; ';
210
- return [first.range[0], `local ${names.join(' ')}${separator}`];
211
- };
212
197
  return {
213
198
  FuncDecl(func) {
214
199
  const { body } = func;
@@ -217,7 +202,6 @@ const preferLocal = createRule({
217
202
  const global = topLevelBefore(func.range[0]);
218
203
  const declared = new Set();
219
204
  const functionName = func.name?.value ?? '';
220
- const leaks = [];
221
205
  for (const binding of scopeBindings(body, sourceCode, lastpipe)) {
222
206
  const { name } = binding;
223
207
  if (binding.kind !== 'assign') {
@@ -231,20 +215,10 @@ const preferLocal = createRule({
231
215
  continue;
232
216
  }
233
217
  declared.add(name);
234
- leaks.push(binding);
235
- }
236
- if (leaks.length === 0)
237
- return;
238
- const insertion = insertionFor(func, leaks.map((binding) => binding.name));
239
- for (const binding of leaks) {
240
- const { name } = binding;
241
218
  context.report({
242
219
  node: binding.node,
243
220
  messageId: 'preferLocal',
244
221
  data: { name, function: functionName },
245
- fix: insertion === null
246
- ? null
247
- : (fixer) => fixer.insertTextBeforeRange([insertion[0], insertion[0]], insertion[1]),
248
222
  });
249
223
  }
250
224
  },
@@ -1,19 +1,6 @@
1
+ import { sourceHasBOM } from '../language/shell-language.js';
1
2
  import { createRule } from './create-rule.js';
2
- import { shebangShell } from './shebang-interpreter.js';
3
- /**
4
- * Interpreter basenames this rule accepts in a shebang. Any of them makes the
5
- * file's interpreter explicit; which one is right for the configured dialect
6
- * is a separate rule's question.
7
- */
8
- const RECOGNIZED_SHELLS = new Set([
9
- 'bash',
10
- 'sh',
11
- 'dash',
12
- 'ksh',
13
- 'mksh',
14
- 'zsh',
15
- 'bats',
16
- ]);
3
+ import { kernelShebangLine, RECOGNIZED_SHELLS, shebangShell } from './shebang-interpreter.js';
17
4
  /**
18
5
  * The interpreter the autofix names for each configured dialect. `posix` has
19
6
  * no shell of its own name, so it maps to `sh`.
@@ -27,6 +14,22 @@ const SHELL_FOR_DIALECT = {
27
14
  };
28
15
  /** The UTF-8 byte order mark as it appears in a decoded string. */
29
16
  const BOM = '\uFEFF';
17
+ const WHITESPACE_ESCAPES = new Map([
18
+ [' ', '\\x20'],
19
+ ['\t', '\\t'],
20
+ ['\v', '\\v'],
21
+ ['\f', '\\f'],
22
+ ['\r', '\\r'],
23
+ ]);
24
+ function displayShebang(text) {
25
+ const line = kernelShebangLine(text);
26
+ let end = line.length;
27
+ while (end > 0 && /[\p{White_Space}\uFEFF]/u.test(line[end - 1]))
28
+ end--;
29
+ const suffix = Array.from(line.slice(end), (character) => WHITESPACE_ESCAPES.get(character) ??
30
+ '\\u' + character.charCodeAt(0).toString(16).padStart(4, '0')).join('');
31
+ return line.slice(0, end).replaceAll('\r', '\\r') + suffix;
32
+ }
30
33
  /** The shebang line the fix inserts for `dialect`, in the configured `style`. */
31
34
  function shebangFor(dialect, style) {
32
35
  const shell = SHELL_FOR_DIALECT[dialect];
@@ -75,25 +78,24 @@ export const requireShebang = createRule({
75
78
  end: { line: 1, column: firstLine.length + 1 },
76
79
  };
77
80
  if (text.startsWith('#!')) {
78
- const shebangLine = firstLine.startsWith(BOM) ? firstLine.slice(1) : firstLine;
79
- const shell = shebangShell(shebangLine.slice('#!'.length));
81
+ const shell = shebangShell(text.slice('#!'.length));
80
82
  if (shell === undefined || !RECOGNIZED_SHELLS.has(shell)) {
81
83
  context.report({
82
84
  loc,
83
85
  messageId: 'unrecognizedInterpreter',
84
- data: { shebang: shebangLine.trimEnd() },
86
+ data: { shebang: displayShebang(text) },
85
87
  });
86
88
  }
87
89
  return;
88
90
  }
89
91
  const shebang = shebangFor(sourceCode.dialect, style);
90
- // Keep the file's own line-ending style: a CRLF file gets a CRLF shebang.
91
- const lineBreak = /^[^\n]*\r\n/u.test(sourceCode.text) ? '\r\n' : '\n';
92
92
  context.report({
93
93
  loc,
94
94
  messageId: 'missingShebang',
95
95
  data: { shebang },
96
- fix: (fixer) => fixer.insertTextBeforeRange([0, 0], `${shebang}${lineBreak}`),
96
+ // ESLint strips the BOM from source coordinates. A range crossing
97
+ // zero tells its fixer to remove the BOM. The kernel needs LF here.
98
+ fix: (fixer) => fixer.replaceTextRange([sourceHasBOM(sourceCode) ? -1 : 0, 0], `${shebang}\n`),
97
99
  });
98
100
  },
99
101
  };
@@ -1,7 +1,7 @@
1
1
  import { createRule } from './create-rule.js';
2
2
  import { SET_OPTION_NAMES, formatSetCommand, shebangOptionChanges } from './set-options.js';
3
3
  import { enabledAfter, resolveStrictModePrologue, setStatementChanges, } from './strict-mode-prologue.js';
4
- import { lineBreakOf } from '../language/line-breaks.js';
4
+ import { shellLineBreakOf } from '../language/line-breaks.js';
5
5
  /**
6
6
  * Dialect-aware policy defaults. Bats runs under Bash; POSIX omits pipefail
7
7
  * because older dash and BusyBox ash reject it. Explicit requirements win.
@@ -71,13 +71,16 @@ export const requireStrictMode = createRule({
71
71
  },
72
72
  fix: fixSatisfies
73
73
  ? (fixer) => {
74
- const eol = lineBreakOf(text);
75
- if (!text.startsWith('#!'))
76
- return fixer.insertTextBeforeRange([0, 0], prologue + eol);
77
- const shebangEnd = text.search(/\r\n|\n|\r/u);
78
- return shebangEnd === -1
79
- ? fixer.insertTextAfterRange([0, text.length], eol + prologue)
80
- : fixer.insertTextAfterRange([0, shebangEnd], eol + prologue);
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);
81
84
  }
82
85
  : null,
83
86
  });
@@ -32,7 +32,7 @@
32
32
  */
33
33
  import { DashHdoc, Hdoc } from 'sh-ast';
34
34
  import { createRule } from './create-rule.js';
35
- import { lineBreakOf } from '../language/line-breaks.js';
35
+ import { lineBreakOf, shellLineBreakOf } from '../language/line-breaks.js';
36
36
  /** Registry name of this rule. */
37
37
  const RULE_NAME = 'require-tty-guard';
38
38
  /** The interactive commands checked when `commands` is not configured. */
@@ -184,11 +184,14 @@ function sharesHeredocOpenerLine(stmt, text) {
184
184
  * must stay alone on its line.
185
185
  */
186
186
  function wrapInGuard(text, start, stmtText, endsInHeredoc) {
187
- const eol = lineBreakOf(text);
187
+ const end = start + stmtText.length;
188
+ const closing = text.startsWith('\r\n', end) ? 'fi #' : 'fi';
188
189
  const startsLine = /^[ \t]*$/u.test(text.slice(text.lastIndexOf('\n', start - 1) + 1, start));
189
- if (startsLine && stmtText.includes('\n'))
190
- return `if [ -t 0 ]; then${eol}${stmtText}${eol}fi`;
191
- return `if [ -t 0 ]; then ${stmtText}${endsInHeredoc ? eol : '; '}fi`;
190
+ if (startsLine && stmtText.includes('\n')) {
191
+ const bodyEnd = endsInHeredoc ? lineBreakOf(text, end) : shellLineBreakOf(text, end);
192
+ return `if [ -t 0 ]; then${shellLineBreakOf(text, start)}${stmtText}${bodyEnd}${closing}`;
193
+ }
194
+ return `if [ -t 0 ]; then ${stmtText}${endsInHeredoc ? lineBreakOf(text, end) : '; '}${closing}`;
192
195
  }
193
196
  /** Built-in rule `sh/require-tty-guard`. @internal */
194
197
  export const requireTtyGuard = createRule({
@@ -89,21 +89,8 @@ export declare function applySetOptionChanges(enabled: Set<string>, changes: rea
89
89
  */
90
90
  export declare function formatSetCommand(options: readonly string[]): string;
91
91
  /**
92
- * The option changes the shebang line passes to the shell (read by
93
- * the shared prologue definition and by
94
- * `compat/no-nounset-empty-array`). Only spellings the kernel hands to the shell as written
95
- * are read:
96
- *
97
- * - `#!/path/to/shell <word>`: the kernel passes everything after the
98
- * interpreter as one argument, so exactly one flag word is read
99
- * (`#!/bin/bash -eu`); more than one word (`#!/bin/bash -e -u`) arrives as a
100
- * single argument the shell rejects, and counts as nothing.
101
- * - `#!/usr/bin/env -S <shell> <words…>`: `env -S` splits the rest into words,
102
- * so every word after the shell name is read. GNU env's
103
- * `--split-string=<shell> <words…>` is read the same way; macOS env supports only `-S`.
104
- *
105
- * Plain `#!/usr/bin/env <shell> <flags>` counts as nothing: without `-S`,
106
- * Linux passes `<shell> <flags>` to `env` as one command name.
92
+ * Read the options from the kernel/GNU env argv using the shared set parser.
93
+ * An env directory or argv0 override can change the script that is read.
107
94
  *
108
95
  * @internal
109
96
  */
@@ -19,6 +19,7 @@
19
19
  * @see https://www.gnu.org/software/bash/manual/html_node/The-Set-Builtin.html
20
20
  * @see https://pubs.opengroup.org/onlinepubs/9799919799/utilities/V3_chap02.html#set
21
21
  */
22
+ import { readShebangInvocation } from './shebang-interpreter.js';
22
23
  /**
23
24
  * Every long option name `set -o` accepts in bash or POSIX sh, mapped to the
24
25
  * single-letter flag that toggles the same option, or `undefined` when the
@@ -158,56 +159,23 @@ export function formatSetCommand(options) {
158
159
  return words.join(' ');
159
160
  }
160
161
  /**
161
- * The option changes the shebang line passes to the shell (read by
162
- * the shared prologue definition and by
163
- * `compat/no-nounset-empty-array`). Only spellings the kernel hands to the shell as written
164
- * are read:
165
- *
166
- * - `#!/path/to/shell <word>`: the kernel passes everything after the
167
- * interpreter as one argument, so exactly one flag word is read
168
- * (`#!/bin/bash -eu`); more than one word (`#!/bin/bash -e -u`) arrives as a
169
- * single argument the shell rejects, and counts as nothing.
170
- * - `#!/usr/bin/env -S <shell> <words…>`: `env -S` splits the rest into words,
171
- * so every word after the shell name is read. GNU env's
172
- * `--split-string=<shell> <words…>` is read the same way; macOS env supports only `-S`.
173
- *
174
- * Plain `#!/usr/bin/env <shell> <flags>` counts as nothing: without `-S`,
175
- * Linux passes `<shell> <flags>` to `env` as one command name.
162
+ * Read the options from the kernel/GNU env argv using the shared set parser.
163
+ * An env directory or argv0 override can change the script that is read.
176
164
  *
177
165
  * @internal
178
166
  */
179
167
  export function shebangOptionChanges(text) {
180
168
  if (!text.startsWith('#!'))
181
169
  return [];
182
- const lineEnd = text.search(/\r?\n|\r/u);
183
- const words = text
184
- .slice(2, lineEnd === -1 ? undefined : lineEnd)
185
- .trim()
186
- .split(/\s+/u);
187
- const [interpreter = '', ...rest] = words;
188
- // Relative interpreters are resolved against the caller's directory, never through PATH.
189
- if (!interpreter.startsWith('/'))
170
+ const invocation = readShebangInvocation(text.slice(2));
171
+ if (invocation === undefined ||
172
+ invocation.chdirRequested === true ||
173
+ invocation.argv0Overridden === true) {
190
174
  return [];
191
- const isEnv = interpreter.endsWith('/env');
192
- let flagWords;
193
- if (isEnv) {
194
- const [split = '', , ...shellArgs] = rest;
195
- // The kernel's single argument makes `--split-string bash -eu` an unknown long option.
196
- if (split === '-S') {
197
- flagWords = shellArgs;
198
- }
199
- else if (split.startsWith('--split-string=')) {
200
- // The first word carries the command when attached; an empty value puts it next.
201
- flagWords = rest.slice(split === '--split-string=' ? 2 : 1);
202
- }
203
- else {
204
- return [];
205
- }
206
175
  }
207
- else {
208
- if (rest.length !== 1)
209
- return [];
210
- flagWords = rest;
211
- }
212
- return parseSetArguments(flagWords).changes;
176
+ // The original header tokenizer split at whitespace. A single resolved
177
+ // argument containing whitespace does not fit that token grammar.
178
+ if (invocation.args.some((arg) => arg !== null && /\s/u.test(arg)))
179
+ return [];
180
+ return parseSetArguments(invocation.args).changes;
213
181
  }
@@ -1,18 +1,41 @@
1
1
  /**
2
- * Shared reading of a shebang line's interpreter, so every rule that asks
3
- * "which shell does this file name?" gets one answer instead of re-deriving it.
2
+ * Read the kernel's interpreter path and optional argument, then apply the GNU
3
+ * env argument grammar when the path names env. A shebang is a shell comment.
4
4
  */
5
+ /** The interpreter names accepted by require-shebang. @internal */
6
+ export declare const RECOGNIZED_SHELLS: ReadonlySet<string>;
5
7
  /**
6
- * The shell basename a shebang's interpreter part (everything after `#!`)
7
- * runs, or `undefined` when it names no usable interpreter: either an absolute
8
- * path (`/usr/local/bin/bash` → `bash`), or an absolute path to `env` whose
9
- * command is the shell (`/usr/bin/env bash`, `/usr/bin/env -S bash -e` →
10
- * `bash`). A relative interpreter (`#!bash`) yields `undefined`: the kernel
11
- * would resolve it against the caller's working directory, not `PATH`.
8
+ * A work limit shared by all readings of one env argument. Each charge covers
9
+ * a bounded amount of work per argument node or code unit. Charge before
10
+ * scanning, copying, or looking up input-sized strings.
12
11
  *
13
- * Which names count as a shell, and whether one agrees with the configured
14
- * dialect, are the callers' questions; this only answers "what runs".
12
+ * @internal
13
+ */
14
+ export declare class EnvReadBudget {
15
+ private remaining;
16
+ constructor(length: number);
17
+ charge(units: number): void;
18
+ }
19
+ /** An interpreter selected from the kernel header. @internal */
20
+ export interface ShebangInvocation {
21
+ readonly shell: string;
22
+ /** GNU env requested a directory change in at least one reading. */
23
+ readonly chdirRequested?: true;
24
+ /** GNU env can change the executable's startup identity independently of its path. */
25
+ readonly argv0Overridden?: true;
26
+ /** Arguments before the kernel-supplied script path. Null marks uncertainty. */
27
+ readonly args: readonly (string | null)[];
28
+ }
29
+ /** Apply the kernel's LF, NUL, and blank handling to the physical header. @internal */
30
+ export declare function kernelShebangLine(text: string): string;
31
+ /**
32
+ * Read the interpreter basename and its initial arguments from the text
33
+ * after `#!`. An absolute path names the interpreter directly or, for `env`,
34
+ * through its command operand. A relative path depends on the caller's
35
+ * working directory.
15
36
  *
16
37
  * @internal
17
38
  */
39
+ export declare function readShebangInvocation(interpreterSpec: string): ShebangInvocation | undefined;
40
+ /** The interpreter basename, independent of its arguments. @internal */
18
41
  export declare function shebangShell(interpreterSpec: string): string | undefined;