@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
package/README.md CHANGED
@@ -161,6 +161,8 @@ ShellLanguage }, rules, configs: { recommended, 'agent-authored', 'bash-3.2', 'p
161
161
  when a bound convention declares nothing. See [reading
162
162
  the convention in your own
163
163
  rule](./docs/declaration-conventions.md#reading-the-convention-in-your-own-rule).
164
+ - `createDisableJustificationProcessor` — configures the opt-in processor that requires reasons on ESLint
165
+ disable directives. See [disable justification](./docs/disable-justification.md).
164
166
  - `defineShellRule` / `ShellRule` / `ShellRuleSpec` / `ShellRuleMeta` / `ShellRuleContext` /
165
167
  `ShellRuleVisitor` / `ShellListener` / `ShellTypedListeners` — the rule-authoring helper and its types. `defineShellRule({ meta, create })`
166
168
  returns an ordinary ESLint rule with `meta.languages: ['sh/sh']` set, so ESLint refuses to run it
@@ -241,23 +243,39 @@ syntax error. Until the parser accepts them, write the workaround in the right-h
241
243
 
242
244
  ## Writing your own rules
243
245
 
244
- Build a rule with `defineShellRule`. It takes the `{ meta, create(context) }` object you would
245
- write for any ESLint rule and returns an ESLint rule you register in a plugin's `rules`:
246
+ Start with [Rules about commands](./docs/rules-about-commands.md) for a runnable example
247
+ that recognizes quoted, escaped, path-qualified, and wrapped invocations. Use the
248
+ [selector cookbook](./docs/selectors.md) for rules about syntax.
246
249
 
247
250
  ```js
248
251
  import { defineShellRule } from '@eslint-sh/eslint-plugin';
249
252
 
250
253
  export default defineShellRule({
251
254
  meta: {
252
- type: 'problem',
255
+ type: 'suggestion',
253
256
  schema: [],
254
- messages: { noEval: 'Avoid `eval`; it runs a string as code.' },
257
+ messages: { match: 'This script invokes sample-tool.' },
255
258
  },
256
259
  create(context) {
257
260
  return {
258
- CallExpr(node) {
259
- if (context.sourceCode.getCommandName(node) === 'eval') {
260
- context.report({ node, messageId: 'noEval' });
261
+ File() {
262
+ const { commands } = context.sourceCode.getCommandInventory();
263
+ for (const site of commands) {
264
+ const { effective, chainIndices } = site.resolveInvokedCommand();
265
+ const index = chainIndices.at(-1);
266
+ if (index === undefined || (!effective.static && chainIndices.length > 1)) continue;
267
+
268
+ const facts = site.argvFacts.at(index);
269
+ if (facts?.resolution !== effective) continue;
270
+
271
+ const text = effective.static ? effective.text : undefined;
272
+ const name = facts.basename.known
273
+ ? facts.basename.text
274
+ : text?.slice(text.lastIndexOf('/') + 1);
275
+ const word = site.node.args.at(index);
276
+ if (name === 'sample-tool' && word) {
277
+ context.report({ node: word, messageId: 'match' });
278
+ }
261
279
  }
262
280
  },
263
281
  };
@@ -276,9 +294,8 @@ accepts only the message ids in `meta.messages`, with no `@eslint/core` import o
276
294
  receive: narrow a `ShellNode` on `type` and read its fields, typed, with one worked rule.
277
295
 
278
296
  The [custom-rule tutorial](./docs/custom-rule-tutorial.md) is a complete, CI-tested walkthrough: a
279
- selector from the cookbook, a full rule with `context.report`, the flat-config wiring to run it,
280
- fixes (and when a printed fix reflows code, so a position-based text edit is the better choice),
281
- and a TypeScript rule. `docs/` ships with this package (see `package.json#files`), so the
297
+ minimal flat config for one local rule, a full rule with `context.report`, fixes, and a
298
+ TypeScript rule. `docs/` ships with this package (see `package.json#files`), so the
282
299
  tutorial and its example files (`docs/examples/`) are available in every installed copy — not just
283
300
  on GitHub.
284
301
 
package/dist/api.d.ts CHANGED
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import type { ConfigObject } from '@eslint/core';
7
7
  import { ShellLanguage } from './language/shell-language.js';
8
+ import { createDisableJustificationProcessor } from './processors/disable-justification.js';
8
9
  export type { ShellLanguage } from './language/shell-language.js';
9
10
  export type { ShellSourceCode } from './language/shell-source-code.js';
10
11
  export type { NormalizedShellLanguageOptions, ShellLanguageOptions, ShellLanguageOptionsJSON, } from './language/shell-language-options.js';
@@ -21,6 +22,7 @@ export type { TransparentWrappersBindingContext } from './rules/resolve-transpar
21
22
  export { resolveDeclarationConvention } from './rules/resolve-declaration-convention.js';
22
23
  export { defineShellRule } from './rules/define-shell-rule.js';
23
24
  export type { ShellListener, ShellRule, ShellRuleContext, ShellRuleMeta, ShellRuleSpec, ShellRuleVisitor, ShellTypedListeners, } from './rules/define-shell-rule.js';
25
+ export { createDisableJustificationProcessor };
24
26
  export { createWrapperRule } from './rules/create-wrapper-rule.js';
25
27
  export type { WrapperRuleConfig, WrapperRuleLocalInvocation, WrapperRuleLocalOperand, WrapperRuleSubcommands, } from './rules/create-wrapper-rule.js';
26
28
  export type { WrapperSpec } from 'sh-analysis';
@@ -38,6 +40,11 @@ export type { WrapperSpec } from 'sh-analysis';
38
40
  * own rules, built with the same `defineShellRule`, while sharing parsing,
39
41
  * selectors, source coordinates, and directive semantics.
40
42
  *
43
+ * Select `processors['require-disable-justification']` as
44
+ * `processor: 'sh/require-disable-justification'` to require reasons on
45
+ * shell disable directives. Use {@link createDisableJustificationProcessor}
46
+ * to select which rule IDs the policy covers.
47
+ *
41
48
  * `configs.recommended` is the `sh/recommended` preset: a single config
42
49
  * object carrying `plugins: { sh }` and `language: "sh/sh"` but no `files`,
43
50
  * so it inherits the globs of the entry that extends it:
@@ -82,6 +89,9 @@ declare const plugin: {
82
89
  sh: ShellLanguage;
83
90
  };
84
91
  rules: Record<string, import("@eslint/core").RuleDefinition<import("@eslint/core").RuleDefinitionTypeOptions>>;
92
+ processors: {
93
+ 'require-disable-justification': import("@eslint/core").Processor<string | import("@eslint/core").ProcessorFile>;
94
+ };
85
95
  configs: {
86
96
  recommended: ConfigObject;
87
97
  "agent-authored": ConfigObject;
package/dist/api.js CHANGED
@@ -3,6 +3,7 @@ import { createBash32Config } from './configs/bash-3-2.js';
3
3
  import { createPosixPortableConfig } from './configs/posix-portable.js';
4
4
  import { createRecommendedConfig } from './configs/recommended.js';
5
5
  import { ShellLanguage } from './language/shell-language.js';
6
+ import { createDisableJustificationProcessor } from './processors/disable-justification.js';
6
7
  import { rules } from './rules/index.js';
7
8
  import { readPackageVersion } from './version.js';
8
9
  export { getDeclaredCommands } from './declaration-conventions/get-declared-commands.js';
@@ -10,6 +11,7 @@ export { commentPragma } from './declaration-conventions/comment-pragma.js';
10
11
  export { resolveTransparentWrappers } from './rules/resolve-transparent-wrappers.js';
11
12
  export { resolveDeclarationConvention } from './rules/resolve-declaration-convention.js';
12
13
  export { defineShellRule } from './rules/define-shell-rule.js';
14
+ export { createDisableJustificationProcessor };
13
15
  export { createWrapperRule } from './rules/create-wrapper-rule.js';
14
16
  /* eslint-disable @api-extractor-tools/public-on-non-exported -- `plugin` is exported below as
15
17
  `export default plugin`; the rule only recognizes inline exports. */
@@ -27,6 +29,11 @@ export { createWrapperRule } from './rules/create-wrapper-rule.js';
27
29
  * own rules, built with the same `defineShellRule`, while sharing parsing,
28
30
  * selectors, source coordinates, and directive semantics.
29
31
  *
32
+ * Select `processors['require-disable-justification']` as
33
+ * `processor: 'sh/require-disable-justification'` to require reasons on
34
+ * shell disable directives. Use {@link createDisableJustificationProcessor}
35
+ * to select which rule IDs the policy covers.
36
+ *
30
37
  * `configs.recommended` is the `sh/recommended` preset: a single config
31
38
  * object carrying `plugins: { sh }` and `language: "sh/sh"` but no `files`,
32
39
  * so it inherits the globs of the entry that extends it:
@@ -71,6 +78,7 @@ const plugin = {
71
78
  sh: new ShellLanguage(),
72
79
  },
73
80
  rules,
81
+ processors: { 'require-disable-justification': createDisableJustificationProcessor() },
74
82
  // Filled in below: each shipped config registers this very object under
75
83
  // `plugins.sh`, so the plugin must exist before its configs can.
76
84
  configs: {},
@@ -11,6 +11,8 @@ import type { Node } from 'sh-ast';
11
11
  import type { OkParseResult } from '@eslint/core';
12
12
  import type { ParseResult } from '@eslint/core';
13
13
  import type { PrintOptions } from 'sh-ast';
14
+ import { Processor } from '@eslint/core';
15
+ import { ProcessorFile } from '@eslint/core';
14
16
  import type { Replace } from 'sh-ast';
15
17
  import { ResolveArgv0Options } from 'sh-analysis';
16
18
  import type { ResolveWordOptions } from 'sh-analysis';
@@ -68,6 +70,17 @@ export { CommandContext }
68
70
  */
69
71
  export declare const commentPragma: Readonly<Required<DeclarationConvention>>;
70
72
 
73
+ /**
74
+ * Creates a shell processor that requires reasons on inline disable directives.
75
+ * Use with `language: 'sh/sh'`. Omit `rules` to check all directives, or
76
+ * supply exact ESLint rule IDs or literal prefixes ending in `*`.
77
+ *
78
+ * @public
79
+ */
80
+ export declare function createDisableJustificationProcessor(options?: {
81
+ readonly rules?: readonly string[];
82
+ }): Processor;
83
+
71
84
  /**
72
85
  * Creates a rule that reports every listed command that is not run through
73
86
  * `config.wrapper`, for a rule pack's "must be wrapped by X" policies:
@@ -356,6 +369,11 @@ export declare interface NormalizedShellLanguageOptions extends Record<string, u
356
369
  * own rules, built with the same `defineShellRule`, while sharing parsing,
357
370
  * selectors, source coordinates, and directive semantics.
358
371
  *
372
+ * Select `processors['require-disable-justification']` as
373
+ * `processor: 'sh/require-disable-justification'` to require reasons on
374
+ * shell disable directives. Use {@link createDisableJustificationProcessor}
375
+ * to select which rule IDs the policy covers.
376
+ *
359
377
  * `configs.recommended` is the `sh/recommended` preset: a single config
360
378
  * object carrying `plugins: { sh }` and `language: "sh/sh"` but no `files`,
361
379
  * so it inherits the globs of the entry that extends it:
@@ -400,6 +418,9 @@ declare const plugin: {
400
418
  sh: ShellLanguage;
401
419
  };
402
420
  rules: Record<string, RuleDefinition<RuleDefinitionTypeOptions>>;
421
+ processors: {
422
+ 'require-disable-justification': Processor<string | ProcessorFile>;
423
+ };
403
424
  configs: {
404
425
  recommended: ConfigObject;
405
426
  "agent-authored": ConfigObject;
@@ -542,6 +563,14 @@ export declare interface ShellCommandSite {
542
563
  * `ShellSourceCode.resolveInvokedCommand(node, options)`; both read the
543
564
  * same per-file index.
544
565
  *
566
+ * The final `chainIndices` entry indexes the word associated with
567
+ * `effective` in `node.args`. If `effective` is the same object as that
568
+ * position's `argvFacts[index].resolution`, it describes the word itself.
569
+ * A non-static word reached through a wrapper may still be an operand
570
+ * whose role is unresolved. The `basename` fact can be known even when
571
+ * the directory is dynamic. If the basename fact is unknown and `effective`
572
+ * is static, its `text` supplies the whole path.
573
+ *
545
574
  * @param options - Wrapper and interpreter settings. Resolution uses the parsed dialect.
546
575
  * `transparentWrappers` replaces `sh-analysis`'s
547
576
  * `DEFAULT_TRANSPARENT_WRAPPERS`; spread the defaults into the array to
@@ -1121,7 +1150,14 @@ export declare interface ShellRuleVisitor extends ShellTypedListeners {
1121
1150
  * {@link ShellSourceCode.getCommandInventory} reports it). When `effective` is
1122
1151
  * static, the effective command's arguments are
1123
1152
  * `argv.slice(chainIndices.at(-1)! + 1)`: every entry after the effective
1124
- * command's own index. For an interpreter command string the final chain
1153
+ * command's own index. For basename matching, check that `effective` is
1154
+ * the same object as `argvFacts[index].resolution` on the inventory site.
1155
+ * A non-static word reached through a wrapper may still be an operand
1156
+ * whose role is unresolved. A known `basename` supplies its `text` even
1157
+ * with a dynamic directory.
1158
+ * If the basename fact is unknown and `effective` is static, its `text`
1159
+ * supplies the whole path.
1160
+ * For an interpreter command string the final chain
1125
1161
  * index instead locates the selector flag; the interpreter is in `chain.at(-2)`.
1126
1162
  * `embeddedCommandInterpreters: []` retains the interpreter as the static
1127
1163
  * effective command when a policy needs program identity. Utility wrappers
@@ -1364,6 +1400,9 @@ export declare interface ShellRuleVisitor extends ShellTypedListeners {
1364
1400
  * source as the named ecosystem precedent), generalized to a configurable
1365
1401
  * prefix instead of the hardcoded `"eslint"` label.
1366
1402
  *
1403
+ * Diagnostics about a directive should use the node's location. Its range may extend beyond the
1404
+ * comment so ESLint can remove an unused directive cleanly.
1405
+ *
1367
1406
  * Unlike `JSONSourceCode` (whose block comments can span multiple
1368
1407
  * physical lines, making `<prefix>-disable-line` spanning lines a real,
1369
1408
  * reportable problem), mvdan/sh's `#` line comments cannot contain an
@@ -72,6 +72,14 @@ export interface ShellCommandSite {
72
72
  * `ShellSourceCode.resolveInvokedCommand(node, options)`; both read the
73
73
  * same per-file index.
74
74
  *
75
+ * The final `chainIndices` entry indexes the word associated with
76
+ * `effective` in `node.args`. If `effective` is the same object as that
77
+ * position's `argvFacts[index].resolution`, it describes the word itself.
78
+ * A non-static word reached through a wrapper may still be an operand
79
+ * whose role is unresolved. The `basename` fact can be known even when
80
+ * the directory is dynamic. If the basename fact is unknown and `effective`
81
+ * is static, its `text` supplies the whole path.
82
+ *
75
83
  * @param options - Wrapper and interpreter settings. Resolution uses the parsed dialect.
76
84
  * `transparentWrappers` replaces `sh-analysis`'s
77
85
  * `DEFAULT_TRANSPARENT_WRAPPERS`; spread the defaults into the array to
@@ -1,5 +1,6 @@
1
1
  /** Adapts upstream parsing and diagnostics to ESLint's synchronous Language contract. */
2
2
  import { LangError, ParseError, ShParseMaxDepthError, parseWithPositionsSync, } from 'sh-ast';
3
+ import { collectDisableJustificationFindings } from '../processors/disable-justification.js';
3
4
  import { SHELL_VARIANTS } from '../shell-dialect.js';
4
5
  import { nonShellFileError } from './non-shell-file-guard.js';
5
6
  import { matchesSelectorClass as matchesShellSelectorClass } from './selector-classes.js';
@@ -178,6 +179,7 @@ export class ShellLanguage {
178
179
  });
179
180
  if (file.bom)
180
181
  sourcesWithBOM.add(sourceCode);
182
+ collectDisableJustificationFindings(file.path, sourceCode);
181
183
  return sourceCode;
182
184
  }
183
185
  }
@@ -196,7 +196,14 @@ export declare class ShellSourceCode extends TextSourceCodeBase<{
196
196
  * {@link ShellSourceCode.getCommandInventory} reports it). When `effective` is
197
197
  * static, the effective command's arguments are
198
198
  * `argv.slice(chainIndices.at(-1)! + 1)`: every entry after the effective
199
- * command's own index. For an interpreter command string the final chain
199
+ * command's own index. For basename matching, check that `effective` is
200
+ * the same object as `argvFacts[index].resolution` on the inventory site.
201
+ * A non-static word reached through a wrapper may still be an operand
202
+ * whose role is unresolved. A known `basename` supplies its `text` even
203
+ * with a dynamic directory.
204
+ * If the basename fact is unknown and `effective` is static, its `text`
205
+ * supplies the whole path.
206
+ * For an interpreter command string the final chain
200
207
  * index instead locates the selector flag; the interpreter is in `chain.at(-2)`.
201
208
  * `embeddedCommandInterpreters: []` retains the interpreter as the static
202
209
  * effective command when a policy needs program identity. Utility wrappers
@@ -439,6 +446,9 @@ export declare class ShellSourceCode extends TextSourceCodeBase<{
439
446
  * source as the named ecosystem precedent), generalized to a configurable
440
447
  * prefix instead of the hardcoded `"eslint"` label.
441
448
  *
449
+ * Diagnostics about a directive should use the node's location. Its range may extend beyond the
450
+ * comment so ESLint can remove an unused directive cleanly.
451
+ *
442
452
  * Unlike `JSONSourceCode` (whose block comments can span multiple
443
453
  * physical lines, making `<prefix>-disable-line` spanning lines a real,
444
454
  * reportable problem), mvdan/sh's `#` line comments cannot contain an
@@ -599,7 +599,14 @@ export class ShellSourceCode extends TextSourceCodeBase {
599
599
  * {@link ShellSourceCode.getCommandInventory} reports it). When `effective` is
600
600
  * static, the effective command's arguments are
601
601
  * `argv.slice(chainIndices.at(-1)! + 1)`: every entry after the effective
602
- * command's own index. For an interpreter command string the final chain
602
+ * command's own index. For basename matching, check that `effective` is
603
+ * the same object as `argvFacts[index].resolution` on the inventory site.
604
+ * A non-static word reached through a wrapper may still be an operand
605
+ * whose role is unresolved. A known `basename` supplies its `text` even
606
+ * with a dynamic directory.
607
+ * If the basename fact is unknown and `effective` is static, its `text`
608
+ * supplies the whole path.
609
+ * For an interpreter command string the final chain
603
610
  * index instead locates the selector flag; the interpreter is in `chain.at(-2)`.
604
611
  * `embeddedCommandInterpreters: []` retains the interpreter as the static
605
612
  * effective command when a policy needs program identity. Utility wrappers
@@ -1012,6 +1019,9 @@ export class ShellSourceCode extends TextSourceCodeBase {
1012
1019
  * source as the named ecosystem precedent), generalized to a configurable
1013
1020
  * prefix instead of the hardcoded `"eslint"` label.
1014
1021
  *
1022
+ * Diagnostics about a directive should use the node's location. Its range may extend beyond the
1023
+ * comment so ESLint can remove an unused directive cleanly.
1024
+ *
1015
1025
  * Unlike `JSONSourceCode` (whose block comments can span multiple
1016
1026
  * physical lines, making `<prefix>-disable-line` spanning lines a real,
1017
1027
  * reportable problem), mvdan/sh's `#` line comments cannot contain an
@@ -0,0 +1,20 @@
1
+ import type { Processor } from '@eslint/core';
2
+ import type { ShellSourceCode } from '../language/shell-source-code.js';
3
+ /**
4
+ * Uses the actual linted source and its language options. Findings are held
5
+ * outside ESLint's rule pass and appended after suppression and unused-directive
6
+ * accounting. The comment location is independent of the unused fix range.
7
+ *
8
+ * @internal
9
+ */
10
+ export declare function collectDisableJustificationFindings(filename: string, sourceCode: ShellSourceCode): void;
11
+ /**
12
+ * Creates a shell processor that requires reasons on inline disable directives.
13
+ * Use with `language: 'sh/sh'`. Omit `rules` to check all directives, or
14
+ * supply exact ESLint rule IDs or literal prefixes ending in `*`.
15
+ *
16
+ * @public
17
+ */
18
+ export declare function createDisableJustificationProcessor(options?: {
19
+ readonly rules?: readonly string[];
20
+ }): Processor;
@@ -0,0 +1,124 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { ConfigCommentParser } from '@eslint/plugin-kit';
3
+ import { readPackageVersion } from '../version.js';
4
+ const name = 'require-disable-justification';
5
+ const ruleId = `sh/${name}`;
6
+ const version = readPackageVersion();
7
+ const commentParser = new ConfigCommentParser();
8
+ const hasReasonText = /[^\s\p{White_Space}]/u;
9
+ /**
10
+ * ESLint calls preprocess, constructs the source code for the unchanged block,
11
+ * and calls postprocess synchronously. The per-file stack lets nested lint
12
+ * calls collect their own findings. Pending checks retain diagnostics only.
13
+ */
14
+ const pending = new Map();
15
+ function removePending(filename, check) {
16
+ const checks = pending.get(filename);
17
+ if (!checks)
18
+ return;
19
+ const index = checks.lastIndexOf(check);
20
+ if (index !== -1)
21
+ checks.splice(index, 1);
22
+ if (checks.length === 0)
23
+ pending.delete(filename);
24
+ }
25
+ /**
26
+ * An empty directive list disables every selected rule. Named directives use
27
+ * the same comma and quote handling as ESLint's suppression pipeline.
28
+ */
29
+ function matchesDirective(value, rules) {
30
+ if (rules === undefined)
31
+ return true;
32
+ const ids = Object.keys(commentParser.parseListConfig(value));
33
+ return (ids.length === 0 ||
34
+ rules.some((rule) => rule.endsWith('*') ? ids.some((id) => id.startsWith(rule.slice(0, -1))) : ids.includes(rule)));
35
+ }
36
+ /**
37
+ * Uses the actual linted source and its language options. Findings are held
38
+ * outside ESLint's rule pass and appended after suppression and unused-directive
39
+ * accounting. The comment location is independent of the unused fix range.
40
+ *
41
+ * @internal
42
+ */
43
+ export function collectDisableJustificationFindings(filename, sourceCode) {
44
+ const check = pending.get(filename)?.at(-1);
45
+ if (!check || check.findings)
46
+ return;
47
+ const findings = [];
48
+ if (check.rules?.length !== 0) {
49
+ for (const directive of sourceCode.getDisableDirectives().directives) {
50
+ if (directive.type === 'enable' || hasReasonText.test(directive.justification ?? ''))
51
+ continue;
52
+ if (!matchesDirective(directive.value, check.rules))
53
+ continue;
54
+ // ShellSourceCode builds each directive from a projected shell comment.
55
+ const { start, end } = sourceCode.getLoc(directive.node);
56
+ findings.push({
57
+ ruleId,
58
+ message: 'Explain this disable directive with a justification after "--".',
59
+ severity: 2,
60
+ line: start.line,
61
+ column: start.column,
62
+ endLine: end.line,
63
+ endColumn: end.column,
64
+ });
65
+ }
66
+ }
67
+ check.findings = findings;
68
+ }
69
+ /** Ensures a malformed factory option cannot silently skip the directive check. */
70
+ function isRuleSelection(value) {
71
+ return (Array.isArray(value) &&
72
+ Array.from(value).every((rule) => typeof rule === 'string' && rule.trim() !== ''));
73
+ }
74
+ /**
75
+ * Creates a shell processor that requires reasons on inline disable directives.
76
+ * Use with `language: 'sh/sh'`. Omit `rules` to check all directives, or
77
+ * supply exact ESLint rule IDs or literal prefixes ending in `*`.
78
+ *
79
+ * @public
80
+ */
81
+ export function createDisableJustificationProcessor(options = {}) {
82
+ const { rules: configured } = options;
83
+ if (configured !== undefined && !isRuleSelection(configured)) {
84
+ throw new TypeError('createDisableJustificationProcessor: rules must be an array of nonempty strings.');
85
+ }
86
+ const rules = configured === undefined ? undefined : [...configured];
87
+ // ESLint's config cache serializes processor metadata rather than closures.
88
+ const fingerprint = rules === undefined
89
+ ? ''
90
+ : '/' + createHash('sha256').update(JSON.stringify(rules)).digest('hex');
91
+ const processor = {
92
+ meta: { name: `eslint-sh/${name}${fingerprint}`, version },
93
+ supportsAutofix: true,
94
+ preprocess(text, filename) {
95
+ const check = { processor, rules };
96
+ const checks = pending.get(filename) ?? [];
97
+ checks.push(check);
98
+ pending.set(filename, checks);
99
+ // A thrown lint aborts before postprocess. Release the orphaned frame
100
+ // once the synchronous lint stack unwinds.
101
+ queueMicrotask(() => {
102
+ removePending(filename, check);
103
+ });
104
+ return [text];
105
+ },
106
+ postprocess(groups, filename) {
107
+ const check = pending
108
+ .get(filename)
109
+ ?.slice()
110
+ .reverse()
111
+ .find((entry) => entry.processor === processor);
112
+ if (check)
113
+ removePending(filename, check);
114
+ const messages = groups.flat();
115
+ if (!check?.findings && messages.every((message) => !message.fatal)) {
116
+ throw new TypeError(`${ruleId} requires the eslint-sh shell language.`);
117
+ }
118
+ if (!check?.findings?.length)
119
+ return messages;
120
+ return [...messages, ...check.findings].sort((a, b) => a.line - b.line || a.column - b.column);
121
+ },
122
+ };
123
+ return processor;
124
+ }
@@ -1,2 +1,19 @@
1
- /** Whether a resolved destination can name a Bash variable or array member. @internal */
1
+ /**
2
+ * Whether a resolved destination can name a Bash variable or array member:
3
+ * a name, or a name followed by a non-empty subscript whose closing bracket
4
+ * ends the text. Bash rejects anything else, such as `a[1][2]` or `a["1]`, as
5
+ * "not a valid identifier" before the builtin does anything else. A
6
+ * subscript holding a command substitution or `${` is assumed to be valid
7
+ * when the text ends with `]`.
8
+ *
9
+ * @internal
10
+ */
2
11
  export declare function isBashBuiltinDestination(text: string): boolean;
12
+ /**
13
+ * Whether `prefix`, the known start of an expanded destination, can begin a
14
+ * name or an array member that the rest of the text completes: a name, or a
15
+ * name with a subscript that the prefix does not already close.
16
+ *
17
+ * @internal
18
+ */
19
+ export declare function canStartBashBuiltinDestination(prefix: string): boolean;
@@ -1,4 +1,83 @@
1
- /** Whether a resolved destination can name a Bash variable or array member. @internal */
1
+ /**
2
+ * Where the subscript opened at `open` closes, following Bash's
3
+ * `skip_matched_pair` as `valid_array_reference` uses it: nested brackets
4
+ * count, a backslash escapes the next character, and single- and
5
+ * double-quoted strings are skipped. `null` means the subscript never
6
+ * closes. `undefined` means it holds a backquote, `$(` or `${`, whose extent
7
+ * Bash finds by parsing a command or expansion, which is not modeled here.
8
+ */
9
+ function subscriptClose(text, open) {
10
+ let depth = 0;
11
+ for (let index = open; index < text.length; index++) {
12
+ const char = text[index];
13
+ const next = text[index + 1];
14
+ if (char === '`' || (char === '$' && (next === '(' || next === '{')))
15
+ return undefined;
16
+ if (char === '\\') {
17
+ index++;
18
+ }
19
+ else if (char === '[') {
20
+ depth++;
21
+ }
22
+ else if (char === ']') {
23
+ depth--;
24
+ if (depth === 0)
25
+ return index;
26
+ }
27
+ else if (char === "'") {
28
+ index = text.indexOf("'", index + 1);
29
+ if (index === -1)
30
+ return null;
31
+ }
32
+ else if (char === '"') {
33
+ for (index++; index < text.length && text[index] !== '"'; index++) {
34
+ const quoted = text[index];
35
+ if (quoted === '`' || (quoted === '$' && /[({]/u.test(text[index + 1] ?? ''))) {
36
+ return undefined;
37
+ }
38
+ if (quoted === '\\')
39
+ index++;
40
+ }
41
+ if (index >= text.length)
42
+ return null;
43
+ }
44
+ }
45
+ return null;
46
+ }
47
+ /**
48
+ * Whether a resolved destination can name a Bash variable or array member:
49
+ * a name, or a name followed by a non-empty subscript whose closing bracket
50
+ * ends the text. Bash rejects anything else, such as `a[1][2]` or `a["1]`, as
51
+ * "not a valid identifier" before the builtin does anything else. A
52
+ * subscript holding a command substitution or `${` is assumed to be valid
53
+ * when the text ends with `]`.
54
+ *
55
+ * @internal
56
+ */
2
57
  export function isBashBuiltinDestination(text) {
3
- return /^[A-Za-z_][A-Za-z0-9_]*(?:\[[\s\S]+\])?$/u.test(text);
58
+ const name = /^[A-Za-z_][A-Za-z0-9_]*/u.exec(text)?.[0];
59
+ if (name === undefined)
60
+ return false;
61
+ if (name.length === text.length)
62
+ return true;
63
+ if (text[name.length] !== '[' || text[name.length + 1] === ']' || !text.endsWith(']')) {
64
+ return false;
65
+ }
66
+ const close = subscriptClose(text, name.length);
67
+ return close === undefined || close === text.length - 1;
68
+ }
69
+ /**
70
+ * Whether `prefix`, the known start of an expanded destination, can begin a
71
+ * name or an array member that the rest of the text completes: a name, or a
72
+ * name with a subscript that the prefix does not already close.
73
+ *
74
+ * @internal
75
+ */
76
+ export function canStartBashBuiltinDestination(prefix) {
77
+ const name = /^[A-Za-z_][A-Za-z0-9_]*/u.exec(prefix)?.[0];
78
+ if (name === undefined)
79
+ return prefix === '';
80
+ if (name.length === prefix.length)
81
+ return true;
82
+ return prefix[name.length] === '[' && typeof subscriptClose(prefix, name.length) !== 'number';
4
83
  }
@@ -13,17 +13,32 @@
13
13
  * trailing here-string supplies stdin. Here-strings provide shell text, while
14
14
  * files, pipes and inherited stdin may contain NUL bytes that mapfile and read
15
15
  * handle differently. The loop intentionally sets `REPLY` to the empty string.
16
+ * It is withheld when the file may give `REPLY` attributes: a `declare`,
17
+ * `typeset`, `local` or `readonly` naming `REPLY`, or one with an operand that
18
+ * is not static. An integer `REPLY` reads as `0` after the last line, so the
19
+ * loop never ends, and other attributes (case conversion, `readonly`, a
20
+ * nameref) change what the loop stores.
16
21
  */
17
22
  import { resolveWordTextAtPosition } from '../../language/word-resolution.js';
18
23
  import { WordHdoc } from 'sh-ast';
19
24
  import { DEFAULT_TRANSPARENT_WRAPPERS } from 'sh-analysis';
20
25
  import { resolveTransparentWrappers } from '../resolve-transparent-wrappers.js';
26
+ import { someShellNode } from '../../language/syntax-view.js';
21
27
  import { BUILTIN_WRAPPER } from '../transparent-wrappers.js';
22
28
  import { createCompatRule } from './create-compat-rule.js';
23
29
  /** The builtin's two names. */
24
30
  const MAPFILE_COMMANDS = new Set(['mapfile', 'readarray']);
25
31
  /** The array `mapfile` fills when no name is given. */
26
32
  const DEFAULT_ARRAY = 'MAPFILE';
33
+ /** The commands that can give a variable attributes. */
34
+ const DECLARATION_COMMANDS = new Set([
35
+ 'declare',
36
+ 'typeset',
37
+ 'local',
38
+ 'readonly',
39
+ ]);
40
+ /** A declaration operand that names `REPLY`, with or without a value or subscript. */
41
+ const REPLY_OPERAND = /^REPLY(?:$|[=+[])/u;
27
42
  /** A shell variable name, the only operand shape the suggestion rewrites. */
28
43
  const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/u;
29
44
  /**
@@ -90,6 +105,26 @@ export const noMapfile = createCompatRule({
90
105
  const { sourceCode } = context;
91
106
  const transparentWrappers = resolveTransparentWrappers(context, TRANSPARENT_WRAPPERS);
92
107
  const arraysAvailable = sourceCode.dialect !== 'posix';
108
+ let replyDeclared;
109
+ /** Whether any declaration command in the file may set attributes on `REPLY`. */
110
+ const mayDeclareReply = () => (replyDeclared ??=
111
+ someShellNode(sourceCode.ast, (part) => part.type === 'DeclClause' &&
112
+ DECLARATION_COMMANDS.has(part.variant?.value ?? '') &&
113
+ part.args.some((arg) => {
114
+ if (arg.name !== undefined)
115
+ return arg.name.value === 'REPLY';
116
+ if (arg.value === undefined)
117
+ return false;
118
+ const text = resolveWordTextAtPosition(sourceCode, arg.value);
119
+ return text === null || REPLY_OPERAND.test(text);
120
+ })) ||
121
+ sourceCode.getCommandInventory().commands.some((site) => {
122
+ const { effective, chainIndices } = site.resolveInvokedCommand({ transparentWrappers });
123
+ return ((!effective.static || DECLARATION_COMMANDS.has(effective.text)) &&
124
+ site.argv
125
+ .slice((chainIndices.at(-1) ?? 0) + 1)
126
+ .some((word) => !word.static || REPLY_OPERAND.test(word.text)));
127
+ }));
93
128
  return {
94
129
  CallExpr(node) {
95
130
  const invoked = sourceCode.resolveInvokedCommand(node, {
@@ -100,7 +135,7 @@ export const noMapfile = createCompatRule({
100
135
  const command = invoked.effective.text;
101
136
  if (!MAPFILE_COMMANDS.has(command))
102
137
  return;
103
- const array = arraysAvailable ? rewritableArray(sourceCode, node) : undefined;
138
+ const array = arraysAvailable && !mayDeclareReply() ? rewritableArray(sourceCode, node) : undefined;
104
139
  context.report({
105
140
  node,
106
141
  messageId: 'mapfile',