Answer stability round 1: 1 🔴, 2 🟡; end the command at a glued &< and pin each redirect form

This commit is contained in:
2026-10-22 02:40:13 +02:00
parent 18c284c1fe
commit 6b23808127
3 changed files with 14 additions and 6 deletions
+5 -3
View File
@@ -7,8 +7,8 @@ import shlex
HEREDOC = re.compile(r"<<-?[ \t]*([\"']?)([A-Za-z_]\w*)\1[^\n]*\n.*?^[ \t]*\2[ \t]*$", re.DOTALL | re.MULTILINE)
ASSIGNMENT = re.compile(r"[A-Za-z_][A-Za-z0-9_]*=")
OPERATOR = set("\n();&|<>")
# A redirect operator on its own: a command goes on around it.
REDIRECT = re.compile(r"&?[<>]+[&|]?")
# A redirect operator on its own: a command goes on around it. `&<` is no redirect: it is a `&` that ends the command, then a `<`.
REDIRECT = re.compile(r"&>>?|[<>]+[&|]?")
# A quoted string or an escape is taken whole, so a # inside one starts no comment; a comment starts a word.
PIECE = re.compile(r"""'[^']*'|"(?:\\.|[^"\\])*"|\\.|(?<![^\s;&|()])#[^\n]*""", re.DOTALL)
@@ -35,7 +35,8 @@ def segments(command: str) -> list[list[str]]:
- a quoted string is one word, so `bash -c "git commit"` and `echo "$(git commit)"` hide the inner command;
- a backtick substitution stays inside its words, while `$(git commit)` outside quotes splits into the `$` and a command of its own;
- a keyword or a brace opens its command's words, so `then git commit` reads as the command `then`;
- `<(...)` and `<<<` read as redirects, so the word after them is dropped as the target;
- `<(...)` and `>(...)` end the command, and the word after them is dropped as a redirect target, so `tee >(git commit)` hides the commit;
- `<<<` reads as a redirect, so the word after it is dropped as the target;
- a file descriptor before a redirect, as in `2>&1`, stays a word;
- a heredoc's body is dropped;
- variables, aliases and functions are not expanded;
@@ -54,6 +55,7 @@ def segments(command: str) -> list[list[str]]:
# A redirect's target is not an operand.
target = True
elif set(token) <= OPERATOR and token:
# A separator, or a redirect glued to one as in `;>f`, `&<f` or `<(`: the word after the redirect is its target.
target = "<" in token or ">" in token
found.append([])
elif found[-1] or not ASSIGNMENT.match(token):