kneepad 0.3.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.
kneepad/rules.py ADDED
@@ -0,0 +1,210 @@
1
+ """Footgun database: loading, strict validation, and the matching DSL."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import tomllib
7
+ from dataclasses import dataclass, field
8
+ from importlib import resources
9
+ from typing import Dict, List
10
+
11
+ from .argvtools import ParsedArgv, sub_matches
12
+
13
+ SEVERITIES = ("low", "medium", "high", "critical")
14
+ ACTIONS = ("allow", "ask", "deny")
15
+ ACTION_RANK = {"allow": 0, "ask": 1, "deny": 2}
16
+ SNAPSHOT_KINDS = ("none", "files", "git-stash", "git-branch", "git-clean")
17
+ REVERSIBLE = ("yes", "partial", "no")
18
+
19
+ MATCH_KEYS = {
20
+ "cmd", "cmd_re", "sub", "sub_icase", "pos_any", "pos_icase", "flags_any", "flags_all",
21
+ "flags_none", "flag_values", "args_regex", "args_regex_none", "tokens_any", "raw_regex",
22
+ }
23
+ RULE_ID = re.compile(r"^[a-z0-9]+(-[a-z0-9]+)*$")
24
+
25
+
26
+ @dataclass
27
+ class Rule:
28
+ id: str
29
+ title: str
30
+ family: str
31
+ severity: str
32
+ action: str
33
+ why: str
34
+ safer: str
35
+ recipe: str = ""
36
+ reversible: str = "no"
37
+ snapshot: str = "none"
38
+ refs: List[str] = field(default_factory=list)
39
+ match: dict = field(default_factory=dict)
40
+ examples: Dict[str, List[str]] = field(default_factory=dict)
41
+ virtual: bool = False
42
+ no_override: bool = False
43
+
44
+
45
+ def _validate_regex(pattern: str, where: str, errors: List[str]) -> None:
46
+ try:
47
+ re.compile(pattern)
48
+ except re.error as exc:
49
+ errors.append(f"{where}: invalid regex {pattern!r}: {exc}")
50
+
51
+
52
+ def validate_rule_dict(d: dict, seen: set) -> List[str]:
53
+ """Return a list of error strings for one raw rule table (empty when valid)."""
54
+ errors: List[str] = []
55
+ rid = d.get("id", "<missing id>")
56
+ pre = f"rule {rid}"
57
+ for key in ("id", "title", "family", "severity", "action", "why", "safer"):
58
+ if not isinstance(d.get(key), str) or not d.get(key, "").strip():
59
+ errors.append(f"{pre}: missing or empty string field {key!r}")
60
+ if errors and "id" not in d:
61
+ return errors
62
+ if isinstance(d.get("id"), str):
63
+ if not RULE_ID.match(d["id"]):
64
+ errors.append(f"{pre}: id must be kebab-case")
65
+ if d["id"] in seen:
66
+ errors.append(f"{pre}: duplicate id")
67
+ seen.add(d["id"])
68
+ if d.get("severity") not in SEVERITIES:
69
+ errors.append(f"{pre}: severity must be one of {SEVERITIES}")
70
+ if d.get("action") not in ACTIONS:
71
+ errors.append(f"{pre}: action must be one of {ACTIONS}")
72
+ if d.get("snapshot", "none") not in SNAPSHOT_KINDS:
73
+ errors.append(f"{pre}: snapshot must be one of {SNAPSHOT_KINDS}")
74
+ if d.get("reversible", "no") not in REVERSIBLE:
75
+ errors.append(f"{pre}: reversible must be one of {REVERSIBLE}")
76
+ if d.get("action") == "allow" and d.get("snapshot", "none") == "none" and d.get("severity") in ("high", "critical"):
77
+ errors.append(f"{pre}: a high or critical rule cannot simply allow without a snapshot")
78
+ if d.get("severity") == "critical" and d.get("action") != "deny" and not d.get("virtual"):
79
+ errors.append(f"{pre}: critical rules must deny")
80
+ for url in d.get("refs", []):
81
+ if not isinstance(url, str) or not url.startswith("https://"):
82
+ errors.append(f"{pre}: refs must be https URLs")
83
+ if d.get("virtual"):
84
+ return errors
85
+ m = d.get("match")
86
+ if not isinstance(m, dict) or not m:
87
+ errors.append(f"{pre}: needs a non-empty [rule.match] table (or virtual = true)")
88
+ return errors
89
+ unknown = set(m) - MATCH_KEYS
90
+ if unknown:
91
+ errors.append(f"{pre}: unknown match keys {sorted(unknown)}")
92
+ if "raw_regex" not in m and not ({"cmd", "cmd_re"} & set(m)):
93
+ errors.append(f"{pre}: match needs cmd, cmd_re or raw_regex so it cannot fire on every command")
94
+ for key in ("args_regex", "args_regex_none", "raw_regex", "cmd_re"):
95
+ if key in m:
96
+ vals = m[key] if isinstance(m[key], list) else [m[key]]
97
+ for v in vals:
98
+ if not isinstance(v, str):
99
+ errors.append(f"{pre}: {key} must be a string")
100
+ else:
101
+ _validate_regex(v, f"{pre}.{key}", errors)
102
+ if "sub" in m:
103
+ sub = m["sub"]
104
+ if not isinstance(sub, list) or not all(isinstance(a, list) and a and all(isinstance(x, str) for x in a) for a in sub):
105
+ errors.append(f"{pre}: sub must be a list of non-empty string lists")
106
+ else:
107
+ for alts in sub:
108
+ for a in alts:
109
+ if a.startswith("re:"):
110
+ _validate_regex(a[3:], f"{pre}.sub", errors)
111
+ for key in ("cmd", "pos_any", "flags_any", "flags_all", "flags_none", "tokens_any"):
112
+ if key in m and not (isinstance(m[key], list) and all(isinstance(x, str) for x in m[key])):
113
+ errors.append(f"{pre}: {key} must be a list of strings")
114
+ if "flag_values" in m:
115
+ fv = m["flag_values"]
116
+ if not isinstance(fv, dict) or not all(isinstance(v, list) for v in fv.values()):
117
+ errors.append(f"{pre}: flag_values must map flag -> list of values")
118
+ ex = d.get("examples", {})
119
+ if not (isinstance(ex.get("match"), list) and ex["match"]):
120
+ errors.append(f"{pre}: examples.match needs at least one command")
121
+ if not (isinstance(ex.get("no_match"), list) and ex["no_match"]):
122
+ errors.append(f"{pre}: examples.no_match needs at least one command")
123
+ return errors
124
+
125
+
126
+ def load_rules_text(text: str) -> List[Rule]:
127
+ data = tomllib.loads(text)
128
+ raw_rules = data.get("rule", [])
129
+ seen: set = set()
130
+ errors: List[str] = []
131
+ for d in raw_rules:
132
+ errors.extend(validate_rule_dict(d, seen))
133
+ if errors:
134
+ raise ValueError("invalid footgun database:\n " + "\n ".join(errors))
135
+ rules: List[Rule] = []
136
+ for d in raw_rules:
137
+ rules.append(
138
+ Rule(
139
+ id=d["id"], title=d["title"], family=d["family"], severity=d["severity"],
140
+ action=d["action"], why=d["why"].strip(), safer=d["safer"].strip(),
141
+ recipe=d.get("recipe", "").strip(), reversible=d.get("reversible", "no"),
142
+ snapshot=d.get("snapshot", "none"), refs=list(d.get("refs", [])),
143
+ match=dict(d.get("match", {})), examples=dict(d.get("examples", {})),
144
+ virtual=bool(d.get("virtual", False)), no_override=bool(d.get("no_override", False)),
145
+ )
146
+ )
147
+ return rules
148
+
149
+
150
+ def load_default_rules() -> List[Rule]:
151
+ base = resources.files("kneepad").joinpath("data")
152
+ names = sorted(p.name for p in base.iterdir() if p.name.startswith("footguns") and p.name.endswith(".toml"))
153
+ names.sort(key=lambda n: (n != "footguns.toml", n)) # core file first
154
+ text = "\n\n".join(base.joinpath(n).read_text(encoding="utf-8") for n in names)
155
+ return load_rules_text(text)
156
+
157
+
158
+ REGEX_INPUT_CAP = 16384
159
+
160
+
161
+ def bounded_args(argstr: str) -> str:
162
+ """Bound the text regexes run on so a hostile or enormous command cannot stall the hook.
163
+
164
+ Longer inputs keep their head and tail; the engine separately raises an "uninspectable" finding.
165
+ """
166
+ if len(argstr) <= REGEX_INPUT_CAP:
167
+ return argstr
168
+ half = REGEX_INPUT_CAP // 2
169
+ return argstr[:half] + " " + argstr[-half:]
170
+
171
+
172
+ def match_argv(rule: Rule, pa: ParsedArgv) -> bool:
173
+ """Evaluate the argv part of a rule's match table against one command."""
174
+ m = rule.match
175
+ if "cmd" in m and pa.name not in m["cmd"]:
176
+ return False
177
+ if "cmd_re" in m and not re.fullmatch(m["cmd_re"], pa.name):
178
+ return False
179
+ if "cmd" not in m and "cmd_re" not in m:
180
+ return False
181
+ if "sub" in m and not sub_matches(pa, m["sub"], bool(m.get("sub_icase"))):
182
+ return False
183
+ if "pos_any" in m:
184
+ icase = bool(m.get("pos_icase"))
185
+ want = [x.lower() for x in m["pos_any"]] if icase else m["pos_any"]
186
+ have = [p.lower() for p in pa.pos] if icase else pa.pos
187
+ if not any(p in want for p in have):
188
+ return False
189
+ if "flags_any" in m and not any(f in pa.flags for f in m["flags_any"]):
190
+ return False
191
+ if "flags_all" in m and not all(f in pa.flags for f in m["flags_all"]):
192
+ return False
193
+ if "flags_none" in m and any(f in pa.flags for f in m["flags_none"]):
194
+ return False
195
+ if "flag_values" in m:
196
+ ok = False
197
+ for flag, values in m["flag_values"].items():
198
+ got = pa.flag_values.get(flag)
199
+ if got is not None and got.lower() in [v.lower() for v in values]:
200
+ ok = True
201
+ if not ok:
202
+ return False
203
+ text = bounded_args(pa.argstr) if ("args_regex" in m or "args_regex_none" in m) else ""
204
+ if "args_regex" in m and not re.search(m["args_regex"], text):
205
+ return False
206
+ if "args_regex_none" in m and re.search(m["args_regex_none"], text):
207
+ return False
208
+ if "tokens_any" in m and not any(t in pa.tokens for t in m["tokens_any"]):
209
+ return False
210
+ return True
kneepad/shellparse.py ADDED
@@ -0,0 +1,489 @@
1
+ """A small, dependency-free shell lexer and parser built for safety analysis.
2
+
3
+ It never executes anything. It splits a script into simple commands, understands
4
+ quoting, escapes, command substitution, process substitution, redirections,
5
+ heredocs, pipelines and comments, and exposes the nested scripts (for example the
6
+ body of ``$(...)``) so callers can analyse them recursively.
7
+
8
+ It is deliberately forgiving: unterminated quotes or substitutions never raise,
9
+ they consume to the end of input. Parsing is linear in the input size.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import re
15
+ from dataclasses import dataclass, field
16
+ from typing import List, Optional, Tuple
17
+
18
+ MAX_SRC = 1_000_000
19
+ MAX_DEPTH = 6
20
+
21
+ RESERVED = frozenset(
22
+ {
23
+ "if", "then", "else", "elif", "fi", "do", "done", "while", "until", "for",
24
+ "in", "case", "esac", "select", "function", "{", "}", "!", "time", "coproc",
25
+ "[[", "]]",
26
+ }
27
+ )
28
+
29
+ _REDIR_OPS = ("&>>", "&>", "<<<", "<<-", "<<", "<&", ">&", ">>", ">|", "<>", ">", "<")
30
+ _ASSIGN_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*\+?=")
31
+
32
+
33
+ @dataclass
34
+ class Word:
35
+ """One shell word after quote removal. Variable expansions stay literal."""
36
+
37
+ text: str
38
+ raw: str = ""
39
+ quoted: bool = False
40
+ has_var: bool = False
41
+ glob: bool = False
42
+ subs: List[str] = field(default_factory=list)
43
+
44
+
45
+ @dataclass
46
+ class Cmd:
47
+ """A simple command: words, redirections and heredoc bodies."""
48
+
49
+ argv: List[Word]
50
+ redirects: List[Tuple[str, Word]]
51
+ heredocs: List[str]
52
+ raw: str
53
+ pipe_in: bool = False
54
+ pipe_out: bool = False
55
+ background: bool = False
56
+
57
+
58
+ class _Heredoc:
59
+ __slots__ = ("delim", "strip_tabs", "body")
60
+
61
+ def __init__(self, delim: str, strip_tabs: bool) -> None:
62
+ self.delim = delim
63
+ self.strip_tabs = strip_tabs
64
+ self.body = ""
65
+
66
+
67
+ class _Lexer:
68
+ def __init__(self, src: str) -> None:
69
+ self.s = src
70
+ self.n = len(src)
71
+ self.i = 0
72
+ self.tokens: List[tuple] = []
73
+ self.pending: List[_Heredoc] = []
74
+
75
+ # ---- helpers -------------------------------------------------------
76
+ def _paren_body(self, start: int) -> Tuple[str, int]:
77
+ """Return (body, index_after_closing_paren) for a ``$(`` already opened."""
78
+ s, n = self.s, self.n
79
+ depth = 1
80
+ i = start
81
+ while i < n:
82
+ c = s[i]
83
+ if c == "\\":
84
+ i += 2
85
+ continue
86
+ if c == "'":
87
+ j = s.find("'", i + 1)
88
+ i = n if j == -1 else j + 1
89
+ continue
90
+ if c == '"':
91
+ i += 1
92
+ while i < n and s[i] != '"':
93
+ i += 2 if s[i] == "\\" else 1
94
+ i += 1
95
+ continue
96
+ if c == "`":
97
+ j = i + 1
98
+ while j < n and s[j] != "`":
99
+ j += 2 if s[j] == "\\" else 1
100
+ i = j + 1
101
+ continue
102
+ if c == "(":
103
+ depth += 1
104
+ elif c == ")":
105
+ depth -= 1
106
+ if depth == 0:
107
+ return s[start:i], i + 1
108
+ i += 1
109
+ return s[start:], n
110
+
111
+ def _arith_end(self, start: int) -> int:
112
+ s, n = self.s, self.n
113
+ depth = 2
114
+ i = start
115
+ while i < n:
116
+ c = s[i]
117
+ if c == "(":
118
+ depth += 1
119
+ elif c == ")":
120
+ depth -= 1
121
+ if depth == 0:
122
+ return i + 1
123
+ i += 1
124
+ return n
125
+
126
+ def _backtick_body(self, start: int) -> Tuple[str, int]:
127
+ s, n = self.s, self.n
128
+ i = start
129
+ while i < n and s[i] != "`":
130
+ i += 2 if s[i] == "\\" else 1
131
+ end = min(i, n)
132
+ return s[start:end].replace("\\`", "`"), min(i + 1, n)
133
+
134
+ def _brace_end(self, start: int, w: Word) -> int:
135
+ """Skip a ``${...}`` expansion, collecting nested command substitutions."""
136
+ s, n = self.s, self.n
137
+ depth = 1
138
+ i = start
139
+ while i < n:
140
+ c = s[i]
141
+ if c == "\\":
142
+ i += 2
143
+ continue
144
+ if c == "'":
145
+ j = s.find("'", i + 1)
146
+ i = n if j == -1 else j + 1
147
+ continue
148
+ if c == '"':
149
+ i += 1
150
+ while i < n and s[i] != '"':
151
+ i += 2 if s[i] == "\\" else 1
152
+ i += 1
153
+ continue
154
+ if c == "$" and i + 1 < n and s[i + 1] == "(" and not s.startswith("$((", i):
155
+ body, end = self._paren_body(i + 2)
156
+ w.subs.append(body)
157
+ i = end
158
+ continue
159
+ if c == "{":
160
+ depth += 1
161
+ elif c == "}":
162
+ depth -= 1
163
+ if depth == 0:
164
+ return i + 1
165
+ i += 1
166
+ return n
167
+
168
+ def _read_dq(self, w: Word, buf: List[str]) -> None:
169
+ s, n = self.s, self.n
170
+ w.quoted = True
171
+ self.i += 1 # opening quote
172
+ while self.i < n:
173
+ c = s[self.i]
174
+ if c == '"':
175
+ self.i += 1
176
+ return
177
+ if c == "\\" and self.i + 1 < n and s[self.i + 1] in '"\\$`\n':
178
+ if s[self.i + 1] != "\n":
179
+ buf.append(s[self.i + 1])
180
+ self.i += 2
181
+ continue
182
+ if c == "$" and self.i + 1 < n:
183
+ nx = s[self.i + 1]
184
+ if nx == "(":
185
+ if s.startswith("$((", self.i):
186
+ end = self._arith_end(self.i + 3)
187
+ buf.append(s[self.i:end])
188
+ w.has_var = True
189
+ self.i = end
190
+ continue
191
+ body, end = self._paren_body(self.i + 2)
192
+ w.subs.append(body)
193
+ buf.append(s[self.i:end])
194
+ w.has_var = True
195
+ self.i = end
196
+ continue
197
+ if nx == "{":
198
+ end = self._brace_end(self.i + 2, w)
199
+ buf.append(s[self.i:end])
200
+ w.has_var = True
201
+ self.i = end
202
+ continue
203
+ if nx.isalnum() or nx in "_@*#?!$-":
204
+ w.has_var = True
205
+ buf.append("$")
206
+ self.i += 1
207
+ continue
208
+ if c == "`":
209
+ body, end = self._backtick_body(self.i + 1)
210
+ w.subs.append(body)
211
+ buf.append(s[self.i:end])
212
+ w.has_var = True
213
+ self.i = end
214
+ continue
215
+ buf.append(c)
216
+ self.i += 1
217
+
218
+ def _read_ansi_c(self, buf: List[str], w: Word) -> None:
219
+ """Handle ``$'...'`` with the common escapes."""
220
+ s, n = self.s, self.n
221
+ w.quoted = True
222
+ self.i += 2
223
+ esc = {"n": "\n", "t": "\t", "r": "\r", "\\": "\\", "'": "'", '"': '"', "a": "\a", "b": "\b", "e": "\x1b", "f": "\f", "v": "\v"}
224
+ while self.i < n:
225
+ c = s[self.i]
226
+ if c == "'":
227
+ self.i += 1
228
+ return
229
+ if c == "\\" and self.i + 1 < n:
230
+ nx = s[self.i + 1]
231
+ if nx in esc:
232
+ buf.append(esc[nx])
233
+ self.i += 2
234
+ continue
235
+ m = re.match(r"x([0-9A-Fa-f]{1,2})", s[self.i + 1:self.i + 4])
236
+ if m:
237
+ buf.append(chr(int(m.group(1), 16)))
238
+ self.i += 1 + len(m.group(0))
239
+ continue
240
+ m = re.match(r"([0-7]{1,3})", s[self.i + 1:self.i + 4])
241
+ if m:
242
+ buf.append(chr(int(m.group(1), 8)))
243
+ self.i += 1 + len(m.group(0))
244
+ continue
245
+ buf.append(nx)
246
+ self.i += 2
247
+ continue
248
+ buf.append(c)
249
+ self.i += 1
250
+
251
+ def _read_word(self) -> Word:
252
+ s, n = self.s, self.n
253
+ buf: List[str] = []
254
+ w = Word(text="")
255
+ start = self.i
256
+ while self.i < n:
257
+ c = s[self.i]
258
+ if c in " \t\n" or c in ";&|()":
259
+ break
260
+ if c in "<>":
261
+ if not buf and self.i + 1 < n and s[self.i + 1] == "(":
262
+ body, end = self._paren_body(self.i + 2)
263
+ w.subs.append(body)
264
+ buf.append(s[self.i:end])
265
+ w.has_var = True
266
+ self.i = end
267
+ continue
268
+ break
269
+ if c == "\\":
270
+ if self.i + 1 < n:
271
+ nx = s[self.i + 1]
272
+ if nx == "\n":
273
+ self.i += 2
274
+ continue
275
+ buf.append(nx)
276
+ w.quoted = True
277
+ self.i += 2
278
+ continue
279
+ self.i += 1
280
+ continue
281
+ if c == "'":
282
+ end = s.find("'", self.i + 1)
283
+ if end == -1:
284
+ end = n
285
+ buf.append(s[self.i + 1:end])
286
+ w.quoted = True
287
+ self.i = min(end + 1, n)
288
+ continue
289
+ if c == '"':
290
+ self._read_dq(w, buf)
291
+ continue
292
+ if c == "$":
293
+ nx = s[self.i + 1] if self.i + 1 < n else ""
294
+ if nx == "'":
295
+ self._read_ansi_c(buf, w)
296
+ continue
297
+ if nx == '"':
298
+ self.i += 1
299
+ continue
300
+ if nx == "(":
301
+ if s.startswith("$((", self.i):
302
+ end = self._arith_end(self.i + 3)
303
+ buf.append(s[self.i:end])
304
+ w.has_var = True
305
+ self.i = end
306
+ continue
307
+ body, end = self._paren_body(self.i + 2)
308
+ w.subs.append(body)
309
+ buf.append(s[self.i:end])
310
+ w.has_var = True
311
+ self.i = end
312
+ continue
313
+ if nx == "{":
314
+ end = self._brace_end(self.i + 2, w)
315
+ buf.append(s[self.i:end])
316
+ w.has_var = True
317
+ self.i = end
318
+ continue
319
+ if nx and (nx.isalnum() or nx in "_@*#?!$-"):
320
+ w.has_var = True
321
+ buf.append("$")
322
+ self.i += 1
323
+ continue
324
+ if c == "`":
325
+ body, end = self._backtick_body(self.i + 1)
326
+ w.subs.append(body)
327
+ buf.append(s[self.i:end])
328
+ w.has_var = True
329
+ self.i = end
330
+ continue
331
+ if c in "*?[":
332
+ w.glob = True
333
+ buf.append(c)
334
+ self.i += 1
335
+ w.text = "".join(buf)
336
+ w.raw = s[start:self.i]
337
+ return w
338
+
339
+ def _read_heredocs(self) -> None:
340
+ s, n = self.s, self.n
341
+ for hd in self.pending:
342
+ lines: List[str] = []
343
+ while self.i < n:
344
+ j = s.find("\n", self.i)
345
+ line = s[self.i:] if j == -1 else s[self.i:j]
346
+ self.i = n if j == -1 else j + 1
347
+ cmp = line.lstrip("\t") if hd.strip_tabs else line
348
+ if cmp == hd.delim:
349
+ break
350
+ lines.append(line)
351
+ hd.body = "\n".join(lines)
352
+ self.pending = []
353
+
354
+ # ---- main loop -----------------------------------------------------
355
+ def run(self) -> List[tuple]:
356
+ s, n = self.s, self.n
357
+ while self.i < n:
358
+ c = s[self.i]
359
+ if c in " \t":
360
+ self.i += 1
361
+ continue
362
+ if c == "\\" and self.i + 1 < n and s[self.i + 1] == "\n":
363
+ self.i += 2
364
+ continue
365
+ if c == "\n":
366
+ self.tokens.append(("op", "\n"))
367
+ self.i += 1
368
+ if self.pending:
369
+ self._read_heredocs()
370
+ continue
371
+ if c == "#":
372
+ j = s.find("\n", self.i)
373
+ self.i = n if j == -1 else j
374
+ continue
375
+ if c in ";&|()":
376
+ self._read_operator()
377
+ continue
378
+ fd_match = None
379
+ if c.isdigit():
380
+ m = re.match(r"\d+(?=[<>])", s[self.i:self.i + 12])
381
+ if m:
382
+ fd_match = m
383
+ if c in "<>" or fd_match or (c == "&" and s.startswith("&>", self.i)):
384
+ if c in "<>" and self.i + 1 < n and s[self.i + 1] == "(":
385
+ self.tokens.append(("word", self._read_word()))
386
+ continue
387
+ if fd_match:
388
+ self.i += len(fd_match.group(0))
389
+ self._read_redirect()
390
+ continue
391
+ self.tokens.append(("word", self._read_word()))
392
+ return self.tokens
393
+
394
+ def _read_operator(self) -> None:
395
+ s = self.s
396
+ c = s[self.i]
397
+ if c == "&" and s.startswith("&>", self.i):
398
+ self._read_redirect()
399
+ return
400
+ two = s[self.i:self.i + 2]
401
+ three = s[self.i:self.i + 3]
402
+ if three in (";;&",):
403
+ op = three
404
+ elif two in ("&&", "||", "|&", ";;", ";&"):
405
+ op = two
406
+ else:
407
+ op = c
408
+ self.i += len(op)
409
+ self.tokens.append(("op", op))
410
+
411
+ def _read_redirect(self) -> None:
412
+ s = self.s
413
+ op = ""
414
+ for cand in _REDIR_OPS:
415
+ if s.startswith(cand, self.i):
416
+ op = cand
417
+ break
418
+ if not op: # defensive: should be unreachable
419
+ self.i += 1
420
+ return
421
+ self.i += len(op)
422
+ if op in ("<<", "<<-"):
423
+ while self.i < self.n and s[self.i] in " \t":
424
+ self.i += 1
425
+ delim_word = self._read_word()
426
+ hd = _Heredoc(delim_word.text, op == "<<-")
427
+ self.pending.append(hd)
428
+ self.tokens.append(("heredoc", hd))
429
+ return
430
+ self.tokens.append(("redir", op))
431
+
432
+
433
+ def parse(src: str) -> List[Cmd]:
434
+ """Parse ``src`` into simple commands. Never raises on malformed input."""
435
+ src = src[:MAX_SRC]
436
+ toks = _Lexer(src).run()
437
+ cmds: List[Cmd] = []
438
+ words: List[Word] = []
439
+ redirs: List[Tuple[str, Word]] = []
440
+ heredocs: List[_Heredoc] = []
441
+ pending_redir: Optional[str] = None
442
+ pipe_in = False
443
+
444
+ def flush(pipe_out: bool = False, bg: bool = False) -> None:
445
+ nonlocal words, redirs, heredocs, pipe_in, pending_redir
446
+ if words or redirs or heredocs:
447
+ raw = " ".join(w.raw for w in words)
448
+ cmds.append(Cmd(words, redirs, [h.body for h in heredocs], raw, pipe_in, pipe_out, bg))
449
+ words, redirs, heredocs = [], [], []
450
+ pending_redir = None
451
+ pipe_in = pipe_out
452
+
453
+ for tok in toks:
454
+ kind = tok[0]
455
+ if kind == "word":
456
+ if pending_redir is not None:
457
+ redirs.append((pending_redir, tok[1]))
458
+ pending_redir = None
459
+ else:
460
+ words.append(tok[1])
461
+ elif kind == "redir":
462
+ pending_redir = tok[1]
463
+ elif kind == "heredoc":
464
+ heredocs.append(tok[1])
465
+ else: # op
466
+ op = tok[1]
467
+ if op in ("|", "|&"):
468
+ flush(pipe_out=True)
469
+ elif op == "&":
470
+ flush(bg=True)
471
+ else:
472
+ flush()
473
+ flush()
474
+ return cmds
475
+
476
+
477
+ def is_assignment(text: str) -> bool:
478
+ return bool(_ASSIGN_RE.match(text))
479
+
480
+
481
+ def iter_nested(cmds: List[Cmd]):
482
+ """Yield every command-substitution body found in ``cmds``."""
483
+ for c in cmds:
484
+ for w in c.argv:
485
+ for sub in w.subs:
486
+ yield sub
487
+ for _op, w in c.redirects:
488
+ for sub in w.subs:
489
+ yield sub