@eslint-sh/eslint-plugin 0.11.0 → 0.13.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 (84) hide show
  1. package/README.md +5 -2
  2. package/dist/api.d.ts +1 -1
  3. package/dist/command-harvest/harvest-commands.d.ts +10 -4
  4. package/dist/command-harvest/harvest-commands.js +39 -10
  5. package/dist/eslint-plugin-api.d.ts +36 -14
  6. package/dist/language/command-resolution.d.ts +16 -6
  7. package/dist/language/command-resolution.js +44 -17
  8. package/dist/language/line-breaks.d.ts +10 -4
  9. package/dist/language/line-breaks.js +14 -5
  10. package/dist/language/shell-language.d.ts +2 -0
  11. package/dist/language/shell-language.js +10 -1
  12. package/dist/language/shell-source-code.d.ts +29 -13
  13. package/dist/language/shell-source-code.js +126 -55
  14. package/dist/language/word-resolution.d.ts +18 -12
  15. package/dist/language/word-resolution.js +133 -3
  16. package/dist/rules/compat/bash-builtin-destination.d.ts +2 -0
  17. package/dist/rules/compat/bash-builtin-destination.js +4 -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 +16 -19
  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 +38 -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 +243 -61
  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 +34 -46
  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 +54 -25
  42. package/dist/rules/no-unused-declarations.js +127 -30
  43. package/dist/rules/prefer-local.js +146 -52
  44. package/dist/rules/require-shebang.js +23 -21
  45. package/dist/rules/require-strict-mode.d.ts +2 -2
  46. package/dist/rules/require-strict-mode.js +28 -16
  47. package/dist/rules/require-tty-guard.d.ts +2 -0
  48. package/dist/rules/require-tty-guard.js +205 -50
  49. package/dist/rules/set-options.d.ts +5 -16
  50. package/dist/rules/set-options.js +17 -45
  51. package/dist/rules/shebang-interpreter.d.ts +33 -10
  52. package/dist/rules/shebang-interpreter.js +522 -53
  53. package/dist/rules/shebang-matches-dialect.js +4 -4
  54. package/dist/rules/strict-mode-prologue.d.ts +9 -2
  55. package/dist/rules/strict-mode-prologue.js +45 -8
  56. package/dist/rules/variable-reads.d.ts +12 -0
  57. package/dist/rules/variable-reads.js +31 -0
  58. package/docs/custom-rule-tutorial.md +19 -10
  59. package/docs/error-codes.md +6 -1
  60. package/docs/examples/no-curl-in-functions-rule.mjs +7 -5
  61. package/docs/rules/README.md +5 -5
  62. package/docs/rules/compat/no-mapfile.md +11 -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 +7 -1
  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 +4 -1
  72. package/docs/rules/no-secret-flags.md +22 -2
  73. package/docs/rules/no-unchecked-cd.md +2 -1
  74. package/docs/rules/no-undeclared-commands.md +1 -1
  75. package/docs/rules/no-unused-declarations.md +18 -9
  76. package/docs/rules/prefer-local.md +15 -33
  77. package/docs/rules/require-network-wrapper.md +1 -1
  78. package/docs/rules/require-shebang.md +46 -3
  79. package/docs/rules/require-strict-mode.md +40 -15
  80. package/docs/rules/require-tty-guard.md +27 -4
  81. package/docs/rules/shebang-matches-dialect.md +3 -0
  82. package/docs/shellcheck.md +1 -1
  83. package/docs/wrapper-rules.md +1 -1
  84. package/package.json +4 -4
@@ -13,6 +13,7 @@
13
13
  * gating an option `local` shares (`-n`, `-l`, `-u`) adds `local` with
14
14
  * {@link DECLARATION_AND_LOCAL_COMMANDS}.
15
15
  */
16
+ import { resolveWordTextAtPosition } from '../../language/word-resolution.js';
16
17
  import { DEFAULT_TRANSPARENT_WRAPPERS } from 'sh-analysis';
17
18
  import { resolveTransparentWrappers } from '../resolve-transparent-wrappers.js';
18
19
  import { BUILTIN_WRAPPER } from '../transparent-wrappers.js';
@@ -40,26 +41,25 @@ const TRANSPARENT_WRAPPERS = [
40
41
  BUILTIN_WRAPPER,
41
42
  ];
42
43
  /**
43
- * Finds the option word carrying `flag` among a declaration command's
44
- * arguments (the words after the command name), together with all of the
45
- * command's option words, or `undefined` when no option word carries it.
44
+ * Finds every word carrying the flag among a declaration command's
45
+ * arguments. Each match shares the list of the command's option words.
46
46
  * Option processing stops at the first operand, at `--`, and at a word that
47
47
  * is not static, because what follows it may not be an option.
48
48
  */
49
- function findFlagOption(sourceCode, flagPattern, args) {
50
- let report;
49
+ function findFlagOptions(sourceCode, flagPattern, args) {
50
+ const matches = [];
51
51
  const options = [];
52
52
  for (const { report: node, word } of args) {
53
53
  if (word === undefined)
54
54
  break;
55
- const text = sourceCode.resolveWordText(word);
55
+ const text = resolveWordTextAtPosition(sourceCode, word);
56
56
  if (text === null || text === '--' || !/^[-+]./u.test(text))
57
57
  break;
58
58
  options.push(text);
59
- if (report === undefined && flagPattern.test(text))
60
- report = node;
59
+ if (flagPattern.test(text))
60
+ matches.push({ report: node, text });
61
61
  }
62
- return report === undefined ? undefined : { report, options };
62
+ return matches.map((match) => ({ ...match, options }));
63
63
  }
64
64
  /**
65
65
  * The arguments of a `DeclClause` as candidates. An option such as `-A` is an
@@ -72,25 +72,33 @@ function declClauseArgs(node) {
72
72
  return { report: word ?? assign, word };
73
73
  });
74
74
  }
75
+ /** Reports the selected matching option words of one command. */
76
+ function optionReporter(sourceCode, flagPattern, report, reportEveryOption) {
77
+ return (command, args) => {
78
+ const matches = findFlagOptions(sourceCode, flagPattern, args);
79
+ for (const option of reportEveryOption ? matches : matches.slice(0, 1)) {
80
+ report(option.report, command, option.options, option.text);
81
+ }
82
+ };
83
+ }
75
84
  /**
76
- * Builds the listeners that call `report(optionWord, command, optionWords)` for each
85
+ * Builds the listeners that call `report(node, command, options, text)` for each
77
86
  * `declare` / `typeset` (or each of `commands`) whose option cluster contains
78
87
  * `flag`: one letter, or a character class such as `[lu]` for either of two.
79
88
  *
80
89
  * @internal
81
90
  */
82
- export function declarationFlagVisitor(context, flag, report, commands = DECLARATION_COMMANDS) {
91
+ export function declarationFlagVisitor(context, flag, report, commands = DECLARATION_COMMANDS, reportEveryOption = false) {
83
92
  const { sourceCode } = context;
84
93
  const transparentWrappers = resolveTransparentWrappers(context, TRANSPARENT_WRAPPERS);
85
94
  const flagPattern = new RegExp(`^-[a-zA-Z]*${flag}[a-zA-Z]*$`, 'u');
95
+ const reportOptions = optionReporter(sourceCode, flagPattern, report, reportEveryOption);
86
96
  return {
87
97
  DeclClause(node) {
88
98
  const command = node.variant?.value;
89
99
  if (command === undefined || !commands.has(command))
90
100
  return;
91
- const option = findFlagOption(sourceCode, flagPattern, declClauseArgs(node));
92
- if (option !== undefined)
93
- report(option.report, command, option.options);
101
+ reportOptions(command, declClauseArgs(node));
94
102
  },
95
103
  CallExpr(node) {
96
104
  const invoked = sourceCode.resolveInvokedCommand(node, {
@@ -105,9 +113,7 @@ export function declarationFlagVisitor(context, flag, report, commands = DECLARA
105
113
  const operands = node.args
106
114
  .slice((invoked.chainIndices.at(-1) ?? 0) + 1)
107
115
  .map((word) => ({ report: word, word }));
108
- const option = findFlagOption(sourceCode, flagPattern, operands);
109
- if (option !== undefined)
110
- report(option.report, command, option.options);
116
+ reportOptions(command, operands);
111
117
  },
112
118
  };
113
119
  }
@@ -41,9 +41,7 @@ export const noCaseAttributes = createCompatRule({
41
41
  },
42
42
  },
43
43
  create(context, gate) {
44
- const { sourceCode } = context;
45
- return declarationFlagVisitor(context, '[lu]', (node, command) => {
46
- const option = (node.type === 'Word' ? sourceCode.resolveWordText(node) : null) ?? '';
44
+ return declarationFlagVisitor(context, '[lu]', (node, command, _options, option) => {
47
45
  if (option.includes('l') && option.includes('u')) {
48
46
  context.report({
49
47
  node,
@@ -58,6 +56,6 @@ export const noCaseAttributes = createCompatRule({
58
56
  messageId: 'caseAttribute',
59
57
  data: { ...gate, command, flag, tr: TR_FOR[flag] },
60
58
  });
61
- }, DECLARATION_AND_LOCAL_COMMANDS);
59
+ }, DECLARATION_AND_LOCAL_COMMANDS, true);
62
60
  },
63
61
  });
@@ -9,24 +9,13 @@
9
9
  * transparent wrappers (`command mapfile …`, `builtin readarray …`), through
10
10
  * `ShellSourceCode.resolveInvokedCommand`.
11
11
  *
12
- * The suggestion rewrites the one shape whose array contents a loop
13
- * reproduces exactly, `mapfile -t [NAME]` written directly (no wrapper, no leading
14
- * `VAR=value` assignment) in a Bash-family file: it becomes a brace group
15
- * that empties the array and appends each line read by
16
- * `while IFS= read -r … || [ -n "$REPLY" ]`. The `|| [ -n "$REPLY" ]` keeps a
17
- * final line that has no trailing newline, as `mapfile -t` does. Reading with
18
- * no variable name keeps every byte of the line, but it assigns `REPLY`:
19
- * unlike `mapfile`, the loop leaves `REPLY` set to the empty string, whatever
20
- * it held (or whether it was set) before. `REPLY` is `read`'s own default
21
- * variable, so this is the narrowest side effect a read loop can have; the
22
- * alternatives (a named loop variable, or saving and restoring `REPLY` in
23
- * another variable) overwrite a name the script is likelier to use. The
24
- * suggestion message states the tradeoff. The brace group keeps the command a single
25
- * unit, so a redirection (`< file`) or pipeline (`cmd | mapfile -t a`) still
26
- * feeds the loop. Other options (`-d`, `-n`, `-O`, `-s`, `-u`, `-C`, or no
27
- * `-t`, which keeps each newline) and POSIX files, which have no arrays at
28
- * all, get the report without a suggestion.
12
+ * The suggestion replaces a direct `mapfile -t` with a read loop when a
13
+ * trailing here-string supplies stdin. Here-strings provide shell text, while
14
+ * files, pipes and inherited stdin may contain NUL bytes that mapfile and read
15
+ * handle differently. The loop intentionally sets `REPLY` to the empty string.
29
16
  */
17
+ import { resolveWordTextAtPosition } from '../../language/word-resolution.js';
18
+ import { WordHdoc } from 'sh-ast';
30
19
  import { DEFAULT_TRANSPARENT_WRAPPERS } from 'sh-analysis';
31
20
  import { resolveTransparentWrappers } from '../resolve-transparent-wrappers.js';
32
21
  import { BUILTIN_WRAPPER } from '../transparent-wrappers.js';
@@ -64,11 +53,19 @@ function rewritableArray(sourceCode, node) {
64
53
  return undefined;
65
54
  if (node.assigns.length > 0)
66
55
  return undefined;
67
- const words = node.args.slice(1).map((word) => sourceCode.resolveWordText(word));
56
+ const stmt = sourceCode.getParent(node);
57
+ if (stmt?.type !== 'Stmt' || stmt.redirs.length !== 1)
58
+ return undefined;
59
+ const [input] = stmt.redirs;
60
+ if (input.op !== WordHdoc ||
61
+ (input.n !== undefined && !/^0+$/u.test(input.n.value)) ||
62
+ input.range[0] < node.range[1])
63
+ return undefined;
64
+ const words = node.args.slice(1).map((word) => resolveWordTextAtPosition(sourceCode, word));
68
65
  if (words.length === 0 || words.length > 2 || words[0] !== '-t')
69
66
  return undefined;
70
67
  const name = words.length === 2 ? words[1] : DEFAULT_ARRAY;
71
- return name !== null && IDENTIFIER.test(name) ? name : undefined;
68
+ return name !== null && name !== 'REPLY' && IDENTIFIER.test(name) ? name : undefined;
72
69
  }
73
70
  /**
74
71
  * The `sh/compat/no-mapfile` rule module.
@@ -1,13 +1,8 @@
1
- /**
2
- * Message ids this rule reports with: `negativeIndex` for the report and
3
- * `useArrayLength` for its suggestion.
4
- *
5
- * @internal
6
- */
7
- export type NoNegativeArrayIndexMessageId = 'negativeIndex' | 'useArrayLength';
1
+ /** Message id for an unsupported negative subscript. @internal */
2
+ export type NoNegativeArrayIndexMessageId = 'negativeIndex';
8
3
  /**
9
4
  * The `sh/compat/no-negative-array-index` rule module.
10
5
  *
11
6
  * @internal
12
7
  */
13
- export declare const noNegativeArrayIndex: import("../define-shell-rule.js").ShellRule<[], NoNegativeArrayIndexMessageId>;
8
+ export declare const noNegativeArrayIndex: import("../define-shell-rule.js").ShellRule<[], "negativeIndex">;
@@ -6,14 +6,8 @@
6
6
  *
7
7
  * Bash 3.2 evaluates `-1` as the arithmetic value minus one and fails with
8
8
  * "bad array subscript", so the read yields nothing and the assignment is
9
- * refused. The message suggests the portable alternative: count from the
10
- * array length, `${arr[$((${#arr[@]}-1))]}`.
11
- *
12
- * The suggestion rewrites exactly a bare `${NAME[-N]}` read to
13
- * `${NAME[$((${#NAME[@]}-N))]}`. Negative subscripts count back from the
14
- * highest assigned index plus one, while `${#NAME[@]}` counts set elements,
15
- * so the two agree only for arrays without holes; the suggestion message says
16
- * so. Assignments and other expansion forms are reported without a suggestion.
9
+ * refused. A length-based index is only equivalent for a dense zero-based
10
+ * array. The rule reports the incompatible syntax without rewriting it.
17
11
  *
18
12
  * What is read: an `Index` that is a unary minus applied to a static
19
13
  * integer (decimal, octal, hexadecimal or base#digits), on a `ParamExp` or an `Assign`.
@@ -27,13 +21,12 @@
27
21
  * `unset` command's operand text, since the parser keeps that operand as an
28
22
  * ordinary word; option words (`-v`) never match an element name.
29
23
  */
24
+ import { resolveWordTextAtPosition } from '../../language/word-resolution.js';
30
25
  import { Minus } from 'sh-ast';
31
26
  import { DEFAULT_TRANSPARENT_WRAPPERS } from 'sh-analysis';
32
27
  import { resolveTransparentWrappers } from '../resolve-transparent-wrappers.js';
33
28
  import { BUILTIN_WRAPPER } from '../transparent-wrappers.js';
34
29
  import { createCompatRule } from './create-compat-rule.js';
35
- /** A bare negative-subscript read, the only shape the suggestion rewrites. */
36
- const BARE_READ = /^\$\{([A-Za-z_][A-Za-z0-9_]*)\[\s*-\s*(\d+)\s*\]\}$/u;
37
30
  /**
38
31
  * The wrappers followed to find an `unset` command: `sh-analysis`'s
39
32
  * defaults (which include `command`) plus Bash's `builtin`.
@@ -80,13 +73,11 @@ export const noNegativeArrayIndex = createCompatRule({
80
73
  feature: 'negativeArrayIndex',
81
74
  meta: {
82
75
  type: 'problem',
83
- hasSuggestions: true,
84
76
  docs: {
85
77
  description: 'Disallow negative array subscripts (`${arr[-1]}`) when the target shell lacks them',
86
78
  },
87
79
  messages: {
88
- negativeIndex: 'Negative array subscripts need {{required}}, but this file must support {{target}}. Count from the length instead, for example `${arr[$((${#arr[@]}-1))]}`.',
89
- useArrayLength: 'Replace with `${{{name}}[$((${#{{name}}[@]}-{{n}}))]}` (the two differ only for an array with unset elements).',
80
+ negativeIndex: 'Negative array subscripts need {{required}}, but this file must support {{target}}. Use a nonnegative index. A length-based index is equivalent only for a dense zero-based array.',
90
81
  },
91
82
  },
92
83
  create(context, gate) {
@@ -101,7 +92,7 @@ export const noNegativeArrayIndex = createCompatRule({
101
92
  // only a Word can be resolved, and `-0` is zero, not a negative index.
102
93
  if (operand?.type !== 'Word')
103
94
  return false;
104
- const digits = sourceCode.resolveWordText(operand) ?? '';
95
+ const digits = resolveWordTextAtPosition(sourceCode, operand) ?? '';
105
96
  return isNonzeroInteger(digits);
106
97
  }
107
98
  return {
@@ -115,7 +106,7 @@ export const noNegativeArrayIndex = createCompatRule({
115
106
  for (const word of node.args.slice((invoked.chainIndices.at(-1) ?? 0) + 1)) {
116
107
  // An unquoted `a[-1]` holds a glob bracket, so it is not "static"; its
117
108
  // written text is what names the element.
118
- const text = sourceCode.resolveWordText(word) ?? sourceCode.getText(word);
109
+ const text = resolveWordTextAtPosition(sourceCode, word) ?? sourceCode.getText(word);
119
110
  if (text === '--')
120
111
  continue;
121
112
  const match = UNSET_NEGATIVE.exec(text);
@@ -127,21 +118,7 @@ export const noNegativeArrayIndex = createCompatRule({
127
118
  ParamExp(node) {
128
119
  if (!isNegativeLiteral(node.index))
129
120
  return;
130
- const match = BARE_READ.exec(sourceCode.getText(node));
131
- context.report({
132
- node,
133
- messageId: 'negativeIndex',
134
- data: { ...gate },
135
- suggest: match === null
136
- ? []
137
- : [
138
- {
139
- messageId: 'useArrayLength',
140
- data: { name: match[1], n: match[2] },
141
- fix: (fixer) => fixer.replaceText(node, `\${${match[1]}[$((\${#${match[1]}[@]}-${match[2]}))]}`),
142
- },
143
- ],
144
- });
121
+ context.report({ node, messageId: 'negativeIndex', data: { ...gate } });
145
122
  },
146
123
  Assign(node) {
147
124
  if (!isNegativeLiteral(node.index))
@@ -42,10 +42,12 @@
42
42
  * `nounset-array-proof.ts` owns those boundaries. Reports remain conditional:
43
43
  * unknown state is a reason to report, not proof that the array is empty.
44
44
  */
45
+ import { parseSetWords } from '../strict-mode-prologue.js';
46
+ import { resolveWordTextAtPosition } from '../../language/word-resolution.js';
45
47
  import { AlternateUnset, AlternateUnsetOrNull } from 'sh-ast';
46
48
  import { createCompatRule } from './create-compat-rule.js';
47
49
  import { createArraySafetyProof } from './nounset-array-proof.js';
48
- import { parseSetArguments, shebangOptionChanges } from '../set-options.js';
50
+ import { shebangOptionChanges } from '../set-options.js';
49
51
  /** A shell variable name. */
50
52
  const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/u;
51
53
  /**
@@ -88,7 +90,7 @@ export const noNounsetEmptyArray = createCompatRule({
88
90
  function wholeArraySubscript(index) {
89
91
  if (index?.type !== 'Word')
90
92
  return undefined;
91
- const text = sourceCode.resolveWordText(index) ?? sourceCode.getText(index);
93
+ const text = resolveWordTextAtPosition(sourceCode, index) ?? sourceCode.getText(index);
92
94
  return text === '@' || text === '*' ? text : undefined;
93
95
  }
94
96
  /**
@@ -121,8 +123,8 @@ export const noNounsetEmptyArray = createCompatRule({
121
123
  CallExpr(node) {
122
124
  if (sourceCode.getCommandName(node) !== 'set')
123
125
  return;
124
- const args = node.args.slice(1).map((word) => sourceCode.resolveWordText(word));
125
- if (enablesNounset(parseSetArguments(args).changes))
126
+ const args = node.args.slice(1);
127
+ if (enablesNounset(parseSetWords(sourceCode, args).changes))
126
128
  nounset = true;
127
129
  },
128
130
  ParamExp(node) {
@@ -142,9 +144,10 @@ export const noNounsetEmptyArray = createCompatRule({
142
144
  'File:exit'() {
143
145
  if (!nounset || candidates.length === 0)
144
146
  return;
145
- const provenSafe = createArraySafetyProof(sourceCode);
147
+ const arraySafety = createArraySafetyProof(sourceCode);
146
148
  for (const { node, name, subscript } of candidates) {
147
- if (provenSafe(node, name))
149
+ const safety = arraySafety(node, name);
150
+ if (safety === 'safe')
148
151
  continue;
149
152
  const replacement = guardedExpansion(name, subscript);
150
153
  const quoted = wholeQuotedWord(node);
@@ -152,7 +155,7 @@ export const noNounsetEmptyArray = createCompatRule({
152
155
  node,
153
156
  messageId: 'emptyArray',
154
157
  data: { ...gate, name, subscript, example: replacement },
155
- suggest: quoted === undefined
158
+ suggest: quoted === undefined || safety === 'unresolved-word'
156
159
  ? []
157
160
  : [
158
161
  {
@@ -19,6 +19,7 @@
19
19
  * What is read: a `ParamExp` whose expansion operator is `@` followed by one
20
20
  * of the letters above. The report is on the whole expansion.
21
21
  */
22
+ import { resolveWordTextAtPosition } from '../../language/word-resolution.js';
22
23
  import { OtherParamOps } from 'sh-ast';
23
24
  import { createMultiFeatureCompatRule } from './create-compat-rule.js';
24
25
  import { TO_LOWER, TO_UPPER, trExample } from './no-case-modification.js';
@@ -96,7 +97,7 @@ export const noParameterTransformation = createMultiFeatureCompatRule({
96
97
  const { exp } = node;
97
98
  if (exp?.op !== OtherParamOps || exp.word === undefined)
98
99
  return;
99
- const operator = sourceCode.resolveWordText(exp.word);
100
+ const operator = resolveWordTextAtPosition(sourceCode, exp.word);
100
101
  if (operator === null)
101
102
  return;
102
103
  const feature = OPERATOR_FEATURES.get(operator);
@@ -7,17 +7,16 @@
7
7
  * nothing is printed. The message suggests the portable alternative for the
8
8
  * current time: `date '+fmt'`, which takes the same `strftime` format.
9
9
  *
10
- * What is read: a `printf` command (after transparent wrappers such as
11
- * `builtin`) whose format argument, after an optional `-v name` and `--`, is
12
- * a static word containing a `%(…)T` directive. The format is scanned as
13
- * `printf` reads it: `%%` is a literal percent sign, and a directive may
14
- * carry flags, a width and a precision before the `(`. A format that is not
15
- * static cannot be read, and is not reported. The report is on the format
16
- * word.
10
+ * The rule reads the first format field of a `printf` invocation, after
11
+ * optional `-v name` and `--` operands. It scans exact text and known
12
+ * literal edges for directives, honoring `%%`, flags, width and precision.
13
+ * The report points to the format word.
17
14
  */
15
+ import { describeWordAtPosition, isSingleField } from '../../language/word-resolution.js';
18
16
  import { DEFAULT_TRANSPARENT_WRAPPERS } from 'sh-analysis';
19
17
  import { resolveTransparentWrappers } from '../resolve-transparent-wrappers.js';
20
18
  import { BUILTIN_WRAPPER } from '../transparent-wrappers.js';
19
+ import { isBashBuiltinDestination } from './bash-builtin-destination.js';
21
20
  import { createCompatRule } from './create-compat-rule.js';
22
21
  /**
23
22
  * The wrappers followed to find the `printf` command: `sh-analysis`'s
@@ -80,21 +79,44 @@ export const noPrintfTimeFormat = createCompatRule({
80
79
  if (invoked?.effective.static !== true || invoked.effective.text !== 'printf')
81
80
  return;
82
81
  // `chainIndices` index `node.args` directly, so slice before filtering.
83
- const words = node.args.slice((invoked.chainIndices.at(-1) ?? 0) + 1);
82
+ const words = node.args
83
+ .slice((invoked.chainIndices.at(-1) ?? 0) + 1)
84
+ .map((word) => ({ word, facts: describeWordAtPosition(sourceCode, word) }))
85
+ .filter(({ facts }) => facts.fields.max !== 0);
84
86
  let index = 0;
85
- const first = words.at(0);
86
- if (first !== undefined && sourceCode.resolveWordText(first) === '-v')
87
+ const first = words.at(0)?.facts.resolution;
88
+ if (first?.static && first.text === '-v') {
89
+ const destination = words.at(1)?.facts;
90
+ if (destination === undefined || !isSingleField(destination))
91
+ return;
92
+ if (destination.resolution.static &&
93
+ !isBashBuiltinDestination(destination.resolution.text))
94
+ return;
87
95
  index = 2;
88
- if (index < words.length && sourceCode.resolveWordText(words[index]) === '--')
96
+ }
97
+ else if (first?.static && first.text.startsWith('-v')) {
98
+ if (!isBashBuiltinDestination(first.text.slice(2)))
99
+ return;
100
+ index = 1;
101
+ }
102
+ const option = words.at(index)?.facts.resolution;
103
+ if (option?.static && option.text === '--')
89
104
  index++;
90
- const formatWord = words.at(index);
91
- if (formatWord === undefined)
105
+ const entry = words.at(index);
106
+ if (entry === undefined || !isSingleField(entry.facts))
92
107
  return;
93
- const text = sourceCode.resolveWordText(formatWord);
94
- const format = text === null ? undefined : timeFormatIn(text);
108
+ const { word, facts } = entry;
109
+ const text = facts.resolution.static ? facts.resolution.text : facts.knownPrefix;
110
+ let format = timeFormatIn(text);
111
+ if (format === undefined &&
112
+ facts.features.every((feature) => feature === 'locale' || feature === 'tilde')) {
113
+ // The exact format can depend on encoding or a tilde directory.
114
+ // Recognize the directive in the literal suffix of that format.
115
+ format = timeFormatIn(facts.knownSuffix);
116
+ }
95
117
  if (format === undefined)
96
118
  return;
97
- context.report({ node: formatWord, messageId: 'printfTime', data: { ...gate, format } });
119
+ context.report({ node: word, messageId: 'printfTime', data: { ...gate, format } });
98
120
  },
99
121
  };
100
122
  },
@@ -1,13 +1,8 @@
1
- /**
2
- * Message ids this rule reports with: `source` for the report and `useDot` for
3
- * its suggestion.
4
- *
5
- * @internal
6
- */
7
- export type NoSourceMessageId = 'source' | 'useDot';
1
+ /** The message id this rule reports with. @internal */
2
+ export type NoSourceMessageId = 'source';
8
3
  /**
9
4
  * The `sh/compat/no-source` rule module.
10
5
  *
11
6
  * @internal
12
7
  */
13
- export declare const noSource: import("../define-shell-rule.js").ShellRule<[], NoSourceMessageId>;
8
+ export declare const noSource: import("../define-shell-rule.js").ShellRule<[], "source">;
@@ -19,46 +19,14 @@
19
19
  * calls still fail on dash. A call through a wrapper is never exempt, because
20
20
  * wrappers such as `command`, `env` and `exec` do not run functions.
21
21
  *
22
- * The suggestion replaces the word with `.` only where the two read the same
23
- * file with the same effect, apart from a file that cannot be read: `.` then
24
- * ends the script on a POSIX shell, so a `|| fallback` never runs, and the
25
- * suggestion's text says so. The conditions are:
26
- *
27
- * - The command is written directly, with no wrapper.
28
- * - It has no leading `VAR=value`. Such an assignment persists after `.` on a
29
- * POSIX shell, while Bash outside POSIX mode scopes it to the `source`
30
- * command.
31
- * - It has exactly one operand. `.` takes one in POSIX, and dash ignores any
32
- * others where `source` would set the positional parameters.
33
- * - The operand has a literal `/`. A name without one makes `.` search `PATH`.
22
+ * The diagnostic gives the portable spelling. The edit requires a readable
23
+ * shell file at runtime, which lint cannot establish.
34
24
  */
35
25
  import { definedFunctionNames } from '../../command-harvest/harvest-commands.js';
36
- import { childNodes } from '../../language/syntax-view.js';
37
26
  import { createCompatRule } from './create-compat-rule.js';
38
27
  import { reachableCommandWord } from './posix-absent-command.js';
39
28
  /** The builtin this rule gates. */
40
29
  const SOURCE = 'source';
41
- /**
42
- * Whether `word` holds a `/` that no expansion can remove: in unquoted or
43
- * quoted literal text, whatever its other parts expand to. A `/` inside an
44
- * expansion (`${x%/*}`, `$(pwd)`) does not count, so the walk stops at anything
45
- * that is not literal text or a double-quoted group.
46
- */
47
- function hasLiteralSlash(word) {
48
- return childNodes(word).some((part) => {
49
- if (part.type === 'Lit' || part.type === 'SglQuoted')
50
- return part.value.includes('/');
51
- return part.type === 'DblQuoted' && hasLiteralSlash(part);
52
- });
53
- }
54
- /** Whether `.` is an exact replacement for this `source` command (see the module comment). */
55
- function dotIsEquivalent(sourceCode, node) {
56
- if (sourceCode.getCommandName(node) !== SOURCE)
57
- return false;
58
- if (node.assigns.length > 0 || node.args.length !== 2)
59
- return false;
60
- return hasLiteralSlash(node.args[1]);
61
- }
62
30
  /**
63
31
  * The `sh/compat/no-source` rule module.
64
32
  *
@@ -69,13 +37,11 @@ export const noSource = createCompatRule({
69
37
  feature: 'sourceCommand',
70
38
  meta: {
71
39
  type: 'problem',
72
- hasSuggestions: true,
73
40
  docs: {
74
41
  description: 'Disallow the `source` builtin when the target shell is POSIX sh',
75
42
  },
76
43
  messages: {
77
- source: '`source` is not part of {{target}}. dash fails with `source: not found` and the file is never read. Use the `.` special built-in with a path that contains a slash, for example `. ./lib.sh`.',
78
- useDot: 'Replace `source` with `.`, which ends the script if the file is missing.',
44
+ source: '`source` is not part of {{target}}. dash fails with `source: not found` and the file is never read. To execute a readable shell file, use the `.` special built-in with a path that contains a slash, for example `. ./lib.sh`. An unreadable file can end the script.',
79
45
  },
80
46
  },
81
47
  create(context, gate) {
@@ -94,9 +60,6 @@ export const noSource = createCompatRule({
94
60
  node: word,
95
61
  messageId: 'source',
96
62
  data: { target: gate.target },
97
- suggest: dotIsEquivalent(sourceCode, node)
98
- ? [{ messageId: 'useDot', fix: (fixer) => fixer.replaceText(word, '.') }]
99
- : [],
100
63
  });
101
64
  },
102
65
  };