bash32-lint 0.1.0__py3-none-any.whl
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.
- bash32_lint/__init__.py +10 -0
- bash32_lint/__main__.py +7 -0
- bash32_lint/checker.py +273 -0
- bash32_lint/cli.py +155 -0
- bash32_lint/lexer.py +581 -0
- bash32_lint/py.typed +0 -0
- bash32_lint/rules.py +155 -0
- bash32_lint/runner.py +100 -0
- bash32_lint-0.1.0.dist-info/METADATA +239 -0
- bash32_lint-0.1.0.dist-info/RECORD +13 -0
- bash32_lint-0.1.0.dist-info/WHEEL +4 -0
- bash32_lint-0.1.0.dist-info/entry_points.txt +2 -0
- bash32_lint-0.1.0.dist-info/licenses/LICENSE +21 -0
bash32_lint/__init__.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""Find bash constructs that break on macOS's /bin/bash 3.2, and run scripts under a real bash 3.2."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
6
|
+
|
|
7
|
+
try:
|
|
8
|
+
__version__ = version("bash32-lint")
|
|
9
|
+
except PackageNotFoundError:
|
|
10
|
+
__version__ = "0.0.0"
|
bash32_lint/__main__.py
ADDED
bash32_lint/checker.py
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
"""Run the rules over one script and return its findings, suppressions applied."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import bisect
|
|
6
|
+
import re
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from typing import TYPE_CHECKING, Protocol
|
|
9
|
+
|
|
10
|
+
from bash32_lint.lexer import COMMAND_PREFIX_WORDS, IDENT, Expansion, Lexed, Token, lex
|
|
11
|
+
from bash32_lint.rules import RULES, TRANSFORM_VERSIONS, VARIABLE_VERSIONS
|
|
12
|
+
|
|
13
|
+
if TYPE_CHECKING:
|
|
14
|
+
from collections.abc import Iterable
|
|
15
|
+
|
|
16
|
+
_ASSIGNMENT = re.compile(r"[A-Za-z_][A-Za-z0-9_]*(\[[^\]]*\])?\+?=")
|
|
17
|
+
_NEGATIVE_ASSIGNMENT = re.compile(r"[A-Za-z_][A-Za-z0-9_]*\[\s*-\s*[0-9$]")
|
|
18
|
+
_NEGATIVE_SUBSCRIPT = re.compile(r"\s*-\s*[0-9$]")
|
|
19
|
+
_NEGATIVE_LENGTH = re.compile(r":(?![-=+?])[^:]*:\s*-")
|
|
20
|
+
_SUPPRESS = re.compile(r"#\s*bash32-ignore\s+([A-Za-z0-9_,\s-]+)")
|
|
21
|
+
_NOUNSET_SHEBANG = re.compile(r"#!\S*(?:\s+\S+)*\s+-[A-Za-z]*u")
|
|
22
|
+
_PREFIX_WORDS = COMMAND_PREFIX_WORDS | {"-p"} # time -p
|
|
23
|
+
_DECLARE = frozenset({"declare", "typeset", "local", "readonly"})
|
|
24
|
+
_ALWAYS_SET_ARRAYS = frozenset({"BASH_SOURCE", "BASH_LINENO", "BASH_VERSINFO", "PIPESTATUS", "GROUPS"})
|
|
25
|
+
_DEFAULTING = ("-", "=", "+", ":-", ":=", ":+")
|
|
26
|
+
_READ_ARG_OPTIONS = "adinNptu"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class _Report(Protocol):
|
|
30
|
+
def __call__(self, offset: int, rule: str, detail: str = "", version: str = "", fix: str = "") -> None: ...
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True)
|
|
34
|
+
class Finding:
|
|
35
|
+
"""One construct bash 3.2 does not accept, at a 1-based line and column."""
|
|
36
|
+
|
|
37
|
+
line: int
|
|
38
|
+
col: int
|
|
39
|
+
rule: str
|
|
40
|
+
message: str
|
|
41
|
+
fix: str
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class _Positions:
|
|
45
|
+
def __init__(self, src: str) -> None:
|
|
46
|
+
self.starts = [0] + [i + 1 for i, c in enumerate(src) if c == "\n"]
|
|
47
|
+
|
|
48
|
+
def at(self, offset: int) -> tuple[int, int]:
|
|
49
|
+
line = bisect.bisect_right(self.starts, offset)
|
|
50
|
+
return line, offset - self.starts[line - 1] + 1
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def check_source(src: str, ignore: Iterable[str] = ()) -> list[Finding]:
|
|
54
|
+
"""Every finding in ``src``, sorted by position, without suppressed or ignored rules."""
|
|
55
|
+
lexed = lex(src)
|
|
56
|
+
positions = _Positions(src)
|
|
57
|
+
raw: list[tuple[int, str, str, str]] = []
|
|
58
|
+
|
|
59
|
+
def report(offset: int, rule: str, detail: str = "", version: str = "", fix: str = "") -> None:
|
|
60
|
+
r = RULES[rule]
|
|
61
|
+
text = f"{detail}: " if detail else ""
|
|
62
|
+
message = f"{text}{r.summary} before bash {version or r.version} (macOS /bin/bash is 3.2)"
|
|
63
|
+
raw.append((offset, rule, message, fix or r.fix))
|
|
64
|
+
|
|
65
|
+
_check_operators(lexed, report)
|
|
66
|
+
for words in lexed.commands:
|
|
67
|
+
_check_command(words, lexed.functions, report)
|
|
68
|
+
_check_expansions(lexed, report, nounset=_enables_nounset(src, lexed))
|
|
69
|
+
|
|
70
|
+
suppressed = _suppressions(lexed, positions, src)
|
|
71
|
+
skip = set(ignore)
|
|
72
|
+
findings: list[Finding] = []
|
|
73
|
+
for offset, rule, message, fix in sorted(raw):
|
|
74
|
+
line, col = positions.at(offset)
|
|
75
|
+
if rule in skip or rule in suppressed.get(line, ()):
|
|
76
|
+
continue
|
|
77
|
+
findings.append(Finding(line, col, rule, message, fix))
|
|
78
|
+
return findings
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _check_operators(lexed: Lexed, report: _Report) -> None:
|
|
82
|
+
for tok in lexed.operators:
|
|
83
|
+
if tok.text == "|&":
|
|
84
|
+
report(tok.start, "pipe-stderr")
|
|
85
|
+
elif tok.text == "&>>":
|
|
86
|
+
report(tok.start, "append-both")
|
|
87
|
+
elif tok.text in (";&", ";;&"):
|
|
88
|
+
report(tok.start, "case-fallthrough", tok.text)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _command_name(words: list[Token]) -> int:
|
|
92
|
+
"""Index of the command name, past reserved words, assignments and ``command``/``builtin``."""
|
|
93
|
+
i = 0
|
|
94
|
+
while i < len(words):
|
|
95
|
+
value = words[i].value
|
|
96
|
+
if (
|
|
97
|
+
value in _PREFIX_WORDS
|
|
98
|
+
or (value is not None and _ASSIGNMENT.match(value))
|
|
99
|
+
or (words[i].value is None and _ASSIGNMENT.match(words[i].text))
|
|
100
|
+
or (value in ("command", "builtin") and i + 1 < len(words) and words[i + 1].value not in ("-v", "-V"))
|
|
101
|
+
):
|
|
102
|
+
i += 1
|
|
103
|
+
else:
|
|
104
|
+
return i
|
|
105
|
+
return i
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _options(args: list[Token]) -> list[tuple[Token, str]]:
|
|
109
|
+
"""The leading option words with their values, up to the first operand or ``--``."""
|
|
110
|
+
opts: list[tuple[Token, str]] = []
|
|
111
|
+
for tok in args:
|
|
112
|
+
value = tok.value
|
|
113
|
+
if value is None or value in {"--", "-", "+"} or not value.startswith(("-", "+")):
|
|
114
|
+
break
|
|
115
|
+
opts.append((tok, value))
|
|
116
|
+
return opts
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _check_command(words: list[Token], functions: set[str], report: _Report) -> None:
|
|
120
|
+
i = _command_name(words)
|
|
121
|
+
for tok in words[:i]:
|
|
122
|
+
if _NEGATIVE_ASSIGNMENT.match(tok.text):
|
|
123
|
+
report(tok.start, "negative-index", tok.text.split("=")[0], "4.3")
|
|
124
|
+
if i >= len(words):
|
|
125
|
+
return
|
|
126
|
+
name = words[i].value
|
|
127
|
+
args = words[i + 1 :]
|
|
128
|
+
if name is None or name in functions:
|
|
129
|
+
return
|
|
130
|
+
if name == "[[" or name in ("[", "test"):
|
|
131
|
+
_check_test_v(words[i:], report)
|
|
132
|
+
elif name in _DECLARE:
|
|
133
|
+
for opt, value in _options(args):
|
|
134
|
+
if "A" in value:
|
|
135
|
+
report(opt.start, "assoc-array", f"{name} {value}")
|
|
136
|
+
if "n" in value and name != "readonly":
|
|
137
|
+
report(opt.start, "nameref", f"{name} {value}")
|
|
138
|
+
for tok in args:
|
|
139
|
+
if _NEGATIVE_ASSIGNMENT.match(tok.text):
|
|
140
|
+
report(tok.start, "negative-index", tok.text.split("=")[0], "4.3")
|
|
141
|
+
elif name in ("mapfile", "readarray", "coproc"):
|
|
142
|
+
report(words[i].start, "coproc" if name == "coproc" else "mapfile", name)
|
|
143
|
+
elif name == "printf":
|
|
144
|
+
_check_printf(args, report)
|
|
145
|
+
elif name == "shopt":
|
|
146
|
+
_check_shopt(args, report)
|
|
147
|
+
elif name == "wait":
|
|
148
|
+
for opt, value in _options(args):
|
|
149
|
+
if "n" in value:
|
|
150
|
+
report(opt.start, "wait-n")
|
|
151
|
+
elif name == "read":
|
|
152
|
+
_check_read(args, report)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _check_test_v(words: list[Token], report: _Report) -> None:
|
|
156
|
+
before = ("[[", "[", "test", "!", "&&", "||", "(", "-a", "-o")
|
|
157
|
+
for prev, tok in zip(words, words[1:]):
|
|
158
|
+
if tok.value == "-v" and prev.text in before:
|
|
159
|
+
report(tok.start, "test-v", f"{words[0].text} -v")
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _check_printf(args: list[Token], report: _Report) -> None:
|
|
163
|
+
for j, (opt, value) in enumerate(_options(args)):
|
|
164
|
+
if value == "-v" and j + 1 < len(args):
|
|
165
|
+
target = args[j + 1].value
|
|
166
|
+
if target and "[" in target:
|
|
167
|
+
report(args[j + 1].start, "printf-v-array", f"printf -v {target}")
|
|
168
|
+
return
|
|
169
|
+
if value.startswith("-v") and "[" in value:
|
|
170
|
+
report(opt.start, "printf-v-array", f"printf {value}")
|
|
171
|
+
return
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _check_shopt(args: list[Token], report: _Report) -> None:
|
|
175
|
+
opts = _options(args)
|
|
176
|
+
if any("q" in value for _, value in opts):
|
|
177
|
+
return
|
|
178
|
+
for tok in args[len(opts) :]:
|
|
179
|
+
if tok.value in ("globstar", "lastpipe"):
|
|
180
|
+
report(tok.start, tok.value, f"shopt {tok.value}")
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _check_read(args: list[Token], report: _Report) -> None:
|
|
184
|
+
j = 0
|
|
185
|
+
while j < len(args):
|
|
186
|
+
value = args[j].value
|
|
187
|
+
if value is None or not value.startswith("-") or value in {"--", "-"}:
|
|
188
|
+
return
|
|
189
|
+
k = 1
|
|
190
|
+
while k < len(value):
|
|
191
|
+
letter = value[k]
|
|
192
|
+
if letter == "i":
|
|
193
|
+
report(args[j].start, "read-i")
|
|
194
|
+
return
|
|
195
|
+
if letter in _READ_ARG_OPTIONS:
|
|
196
|
+
if k == len(value) - 1:
|
|
197
|
+
j += 1
|
|
198
|
+
break
|
|
199
|
+
k += 1
|
|
200
|
+
j += 1
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _check_expansions(lexed: Lexed, report: _Report, *, nounset: bool) -> None:
|
|
204
|
+
for exp in lexed.expansions:
|
|
205
|
+
_check_expansion(exp, report, nounset=nounset)
|
|
206
|
+
for arith in lexed.arith_names:
|
|
207
|
+
if arith.name in VARIABLE_VERSIONS:
|
|
208
|
+
report(arith.start, "new-variables", arith.name, VARIABLE_VERSIONS[arith.name])
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _check_expansion(exp: Expansion, report: _Report, *, nounset: bool) -> None:
|
|
212
|
+
rest = exp.rest
|
|
213
|
+
shown = f"${{{exp.prefix}{exp.name}{'' if exp.subscript is None else f'[{exp.subscript}]'}{rest}}}"
|
|
214
|
+
if exp.name in VARIABLE_VERSIONS and not rest.startswith(_DEFAULTING) and not exp.prefix:
|
|
215
|
+
report(exp.start, "new-variables", exp.name, VARIABLE_VERSIONS[exp.name])
|
|
216
|
+
if not exp.braced:
|
|
217
|
+
return
|
|
218
|
+
if rest[:1] in ("^", ","):
|
|
219
|
+
report(exp.start, "case-modification", shown)
|
|
220
|
+
elif rest[:1] == "@" and rest[1:2] in TRANSFORM_VERSIONS:
|
|
221
|
+
report(exp.start, "param-transform", shown, TRANSFORM_VERSIONS[rest[1:2]])
|
|
222
|
+
if exp.subscript is not None and exp.prefix != "!" and _NEGATIVE_SUBSCRIPT.match(exp.subscript):
|
|
223
|
+
report(exp.start, "negative-index", shown, "4.2")
|
|
224
|
+
if exp.subscript not in ("@", "*") and exp.name not in ("@", "*") and _NEGATIVE_LENGTH.match(rest):
|
|
225
|
+
report(exp.start, "negative-length", shown)
|
|
226
|
+
if (
|
|
227
|
+
nounset
|
|
228
|
+
and exp.subscript in ("@", "*")
|
|
229
|
+
and not exp.prefix
|
|
230
|
+
and (rest == "" or rest.startswith(("?", ":?")))
|
|
231
|
+
and exp.name not in exp.guarded
|
|
232
|
+
and exp.name not in _ALWAYS_SET_ARRAYS
|
|
233
|
+
and IDENT.fullmatch(exp.name)
|
|
234
|
+
):
|
|
235
|
+
ref = f"${{{exp.name}[{exp.subscript}]}}"
|
|
236
|
+
fix = (
|
|
237
|
+
f'${{{exp.name}[{exp.subscript}]+"{ref}"}}'
|
|
238
|
+
if exp.alone_in_quotes
|
|
239
|
+
else f"${{{exp.name}[{exp.subscript}]+{ref}}}"
|
|
240
|
+
)
|
|
241
|
+
report(exp.start, "empty-array-nounset", ref, fix=fix)
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _enables_nounset(src: str, lexed: Lexed) -> bool:
|
|
245
|
+
if _NOUNSET_SHEBANG.match(src.split("\n", 1)[0]):
|
|
246
|
+
return True
|
|
247
|
+
for words in lexed.commands:
|
|
248
|
+
i = _command_name(words)
|
|
249
|
+
if i >= len(words) or words[i].value != "set":
|
|
250
|
+
continue
|
|
251
|
+
args = [w.value or "" for w in words[i + 1 :]]
|
|
252
|
+
for j, arg in enumerate(args):
|
|
253
|
+
if arg == "--":
|
|
254
|
+
break
|
|
255
|
+
if arg.startswith("-") and not arg.startswith("--") and "u" in arg.lstrip("-").split("o")[0]:
|
|
256
|
+
return True
|
|
257
|
+
if arg.startswith("-") and "o" in arg and j + 1 < len(args) and args[j + 1] == "nounset":
|
|
258
|
+
return True
|
|
259
|
+
return False
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def _suppressions(lexed: Lexed, positions: _Positions, src: str) -> dict[int, set[str]]:
|
|
263
|
+
out: dict[int, set[str]] = {}
|
|
264
|
+
for comment in lexed.comments:
|
|
265
|
+
m = _SUPPRESS.search(comment.text)
|
|
266
|
+
if not m:
|
|
267
|
+
continue
|
|
268
|
+
rules = {r for r in re.split(r"[,\s]+", m.group(1)) if r}
|
|
269
|
+
line, _ = positions.at(comment.start)
|
|
270
|
+
out.setdefault(line, set()).update(rules)
|
|
271
|
+
if not src[positions.starts[line - 1] : comment.start].strip():
|
|
272
|
+
out.setdefault(line + 1, set()).update(rules)
|
|
273
|
+
return out
|
bash32_lint/cli.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
"""The ``bash32-lint`` command line: ``check``, ``run`` and ``rules``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import subprocess
|
|
9
|
+
import sys
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import TYPE_CHECKING
|
|
12
|
+
|
|
13
|
+
from bash32_lint import __version__
|
|
14
|
+
from bash32_lint.checker import Finding, check_source
|
|
15
|
+
from bash32_lint.rules import RULES
|
|
16
|
+
from bash32_lint.runner import DEFAULT_IMAGE, RunnerError, Target, build_command, syntax_commands
|
|
17
|
+
|
|
18
|
+
if TYPE_CHECKING:
|
|
19
|
+
from collections.abc import Iterator, Sequence
|
|
20
|
+
|
|
21
|
+
_SHEBANG = re.compile(r"#!\s*(\S+)(?:\s+(\S+))?")
|
|
22
|
+
_OTHER_SHELLS = frozenset({"zsh", "ksh", "mksh", "fish", "dash", "ash", "csh", "tcsh"})
|
|
23
|
+
_SKIP_DIRS = frozenset({".git", ".hg", ".svn", "node_modules", ".venv", "venv", "__pycache__"})
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _interpreter(head: str) -> str | None:
|
|
27
|
+
m = _SHEBANG.match(head)
|
|
28
|
+
if not m:
|
|
29
|
+
return None
|
|
30
|
+
program = Path(m.group(1)).name
|
|
31
|
+
return Path(m.group(2)).name if program == "env" and m.group(2) else program
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _wanted(path: Path, *, explicit: bool) -> bool:
|
|
35
|
+
try:
|
|
36
|
+
with path.open(encoding="utf-8", errors="replace") as f:
|
|
37
|
+
head = f.readline()
|
|
38
|
+
except OSError:
|
|
39
|
+
return False
|
|
40
|
+
shell = _interpreter(head)
|
|
41
|
+
if shell in _OTHER_SHELLS:
|
|
42
|
+
return False
|
|
43
|
+
return explicit or path.suffix in (".sh", ".bash") or shell in ("bash", "sh")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def iter_scripts(paths: Sequence[str]) -> Iterator[Path]:
|
|
47
|
+
"""The scripts to check: each file named, and the shell scripts under each directory."""
|
|
48
|
+
for name in paths:
|
|
49
|
+
path = Path(name)
|
|
50
|
+
if path.is_dir():
|
|
51
|
+
for root, dirs, files in os.walk(path):
|
|
52
|
+
dirs[:] = sorted(d for d in dirs if d not in _SKIP_DIRS)
|
|
53
|
+
for file in sorted(files):
|
|
54
|
+
candidate = Path(root) / file
|
|
55
|
+
if _wanted(candidate, explicit=False):
|
|
56
|
+
yield candidate
|
|
57
|
+
elif _wanted(path, explicit=True):
|
|
58
|
+
yield path
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _escape(text: str, *, prop: bool = False) -> str:
|
|
62
|
+
text = text.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A")
|
|
63
|
+
return text.replace(":", "%3A").replace(",", "%2C") if prop else text
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def format_finding(path: Path, finding: Finding, fmt: str) -> str:
|
|
67
|
+
"""One finding as text (``file:line:col: rule message`` plus the fix) or a GitHub annotation."""
|
|
68
|
+
if fmt == "github":
|
|
69
|
+
props = f"file={_escape(str(path), prop=True)},line={finding.line},col={finding.col}"
|
|
70
|
+
title = _escape(f"bash32-lint {finding.rule}", prop=True)
|
|
71
|
+
return f"::error {props},title={title}::{_escape(finding.message)}. Fix: {_escape(finding.fix)}"
|
|
72
|
+
return f"{path}:{finding.line}:{finding.col}: {finding.rule} {finding.message}\n fix: {finding.fix}"
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _check(args: argparse.Namespace) -> int:
|
|
76
|
+
ignore = {r for chunk in args.ignore for r in chunk.split(",") if r}
|
|
77
|
+
unknown = ignore - RULES.keys()
|
|
78
|
+
if unknown:
|
|
79
|
+
print(f"bash32-lint: unknown rule(s): {', '.join(sorted(unknown))}", file=sys.stderr)
|
|
80
|
+
return 2
|
|
81
|
+
missing = [name for name in args.paths if not Path(name).exists()]
|
|
82
|
+
if missing:
|
|
83
|
+
print(f"bash32-lint: no such file or directory: {', '.join(missing)}", file=sys.stderr)
|
|
84
|
+
return 2
|
|
85
|
+
total = 0
|
|
86
|
+
for path in iter_scripts(args.paths):
|
|
87
|
+
try:
|
|
88
|
+
src = path.read_text(encoding="utf-8", errors="replace")
|
|
89
|
+
except OSError as exc:
|
|
90
|
+
print(f"bash32-lint: {path}: {exc.strerror}", file=sys.stderr)
|
|
91
|
+
return 2
|
|
92
|
+
for finding in check_source(src, ignore):
|
|
93
|
+
print(format_finding(path, finding, args.format))
|
|
94
|
+
total += 1
|
|
95
|
+
if total and args.format == "text":
|
|
96
|
+
sys.stdout.flush()
|
|
97
|
+
print(f"{total} finding(s)", file=sys.stderr)
|
|
98
|
+
return 1 if total else 0
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _run(args: argparse.Namespace) -> int:
|
|
102
|
+
target = Target(Path.cwd().resolve(), os.environ, args.bash, args.docker, args.image)
|
|
103
|
+
try:
|
|
104
|
+
if args.syntax_only:
|
|
105
|
+
commands = syntax_commands([args.script, *args.args], target)
|
|
106
|
+
else:
|
|
107
|
+
commands = [build_command(args.script, args.args, target)]
|
|
108
|
+
except RunnerError as exc:
|
|
109
|
+
print(f"bash32-lint: {exc}", file=sys.stderr)
|
|
110
|
+
return 2
|
|
111
|
+
rc = 0
|
|
112
|
+
for cmd in commands:
|
|
113
|
+
rc = max(rc, subprocess.run(cmd, check=False).returncode) # noqa: S603
|
|
114
|
+
return rc
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _rules(_: argparse.Namespace) -> int:
|
|
118
|
+
for rule in RULES.values():
|
|
119
|
+
print(f"{rule.id:<20} bash {rule.version}+ {rule.summary}")
|
|
120
|
+
return 0
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
124
|
+
parser = argparse.ArgumentParser(prog="bash32-lint", description=__doc__)
|
|
125
|
+
parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
|
|
126
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
127
|
+
|
|
128
|
+
check = sub.add_parser("check", help="statically scan scripts for constructs bash 3.2 rejects")
|
|
129
|
+
check.add_argument("paths", nargs="+", help="scripts, or directories to search for *.sh, *.bash and bash shebangs")
|
|
130
|
+
check.add_argument("--ignore", action="append", default=[], metavar="RULE[,RULE]", help="skip these rules")
|
|
131
|
+
check.add_argument("--format", choices=("text", "github"), default="text")
|
|
132
|
+
check.set_defaults(func=_check)
|
|
133
|
+
|
|
134
|
+
run = sub.add_parser("run", help="run a script under a real bash 3.2 (local binary, else the bash:3.2 image)")
|
|
135
|
+
run.add_argument("--bash", help="path to a bash 3.2 binary (default: $BASH32, /bin/bash, bash on PATH)")
|
|
136
|
+
run.add_argument("--docker", action="store_true", help="always use the container, even with a local bash 3.2")
|
|
137
|
+
run.add_argument("--image", default=DEFAULT_IMAGE, help=f"container image (default: {DEFAULT_IMAGE})")
|
|
138
|
+
run.add_argument("--syntax-only", action="store_true", help="only parse each file with bash -n")
|
|
139
|
+
run.add_argument("script")
|
|
140
|
+
run.add_argument("args", nargs=argparse.REMAINDER)
|
|
141
|
+
run.set_defaults(func=_run)
|
|
142
|
+
|
|
143
|
+
rules = sub.add_parser("rules", help="list the rules")
|
|
144
|
+
rules.set_defaults(func=_rules)
|
|
145
|
+
return parser
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
149
|
+
"""Run on ``argv`` (default ``sys.argv[1:]``) and return the exit status instead of exiting.
|
|
150
|
+
|
|
151
|
+
``check`` returns 1 on findings and 2 on an unknown rule or a missing or unreadable file; ``run`` returns the
|
|
152
|
+
script's status, or 2 when no bash 3.2 can run it. A malformed command line still exits 2 through argparse.
|
|
153
|
+
"""
|
|
154
|
+
args = _build_parser().parse_args(argv)
|
|
155
|
+
return args.func(args)
|