69 lines
2.4 KiB
Python
69 lines
2.4 KiB
Python
"""A shell command's simple commands, each as its words and the directory it runs in."""
|
|
import dataclasses
|
|
import posixpath
|
|
import re
|
|
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 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)
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class Simple:
|
|
words: list[str]
|
|
directory: str
|
|
|
|
|
|
def simple_commands(command: str, cwd: str, home: str) -> list[Simple]:
|
|
"""Each simple command, without leading variable assignments or redirect targets, in the directory `cd` left it in."""
|
|
directory = cwd
|
|
found = []
|
|
for words in segments(command):
|
|
if words[0] == "cd" and len(words) == 2:
|
|
directory = resolved(directory, words[1], home)
|
|
found.append(Simple(words, directory))
|
|
return found
|
|
|
|
|
|
def segments(command: str) -> list[list[str]]:
|
|
text = uncommented(HEREDOC.sub(lambda heredoc: heredoc.group(0).split("\n", 1)[0], command))
|
|
tokens = lexed(text)
|
|
if tokens is None:
|
|
# One unbalanced quote should not hide the other lines.
|
|
tokens = [token for line in text.splitlines() for token in (lexed(line) or []) + ["\n"]]
|
|
found: list[list[str]] = [[]]
|
|
target = False
|
|
for token in tokens:
|
|
if target:
|
|
target = False
|
|
elif set(token) <= OPERATOR and token:
|
|
# A redirect's target is not an operand.
|
|
target = "<" in token or ">" in token
|
|
found.append([])
|
|
elif found[-1] or not ASSIGNMENT.match(token):
|
|
found[-1].append(token)
|
|
return [words for words in found if words]
|
|
|
|
|
|
def lexed(text: str) -> list[str] | None:
|
|
lexer = shlex.shlex(text, posix=True, punctuation_chars="();<>|&\n")
|
|
lexer.commenters = ""
|
|
lexer.whitespace = " \t\r"
|
|
lexer.whitespace_split = True
|
|
try:
|
|
return list(lexer)
|
|
except ValueError:
|
|
return None
|
|
|
|
|
|
def uncommented(text: str) -> str:
|
|
"""The text without its comments; shlex's own would also swallow the line break that ends one, joining two commands."""
|
|
return PIECE.sub(lambda piece: "" if piece.group(0).startswith("#") else piece.group(0), text)
|
|
|
|
|
|
def resolved(base: str, path: str, home: str) -> str:
|
|
return posixpath.normpath(posixpath.join(base, home + path[1:] if path == "~" or path.startswith("~/") else path))
|