diff --git a/project_validator/ci/__init__.py b/project_validator/ci/__init__.py index 50ec9833..47e9126b 100644 --- a/project_validator/ci/__init__.py +++ b/project_validator/ci/__init__.py @@ -27,6 +27,7 @@ ) from project_validator.facts.expansion import script_facts from project_validator.facts.jobs import Job, Toolchain +from project_validator.facts.shell import CMD, POSIX from project_validator.platforms import ( COMPILING_ECOSYSTEMS, RUNNER_DEFAULT_COMPILERS, @@ -302,7 +303,8 @@ def strings(value: object) -> dict[str, str]: def _heuristic_facts(ci_file: CiFile, text: str, reason: str) -> Iterator[Fact]: - """Configuration that is not parsed: one job per OS it names, running each line that could be a command.""" + """Configuration that is not parsed: one job per OS it names, running each line that could be a command, read as + a Windows job's are most often written, in cmd (`.\\build.bat`), or else in a POSIX shell.""" origin = Origin(path=ci_file.path) operating_systems = detect_operating_systems(text) or ["unknown"] lines = (match["value"].strip("'\"") for line in text.splitlines() if (match := _CONFIGURATION_LINE.match(line))) @@ -312,7 +314,9 @@ def _heuristic_facts(ci_file: CiFile, text: str, reason: str) -> Iterator[Fact]: yield CiJob( origin=origin, id=identity, provider=ci_file.provider.name, name=ci_file.path, os=os, heuristic=True ) - yield from (fact for fact in script_facts(script, job=identity, origin=origin) if isinstance(fact, Command)) + dialect = CMD if os == "windows" else POSIX + found = script_facts(script, job=identity, origin=origin, dialect=dialect) + yield from (fact for fact in found if isinstance(fact, Command)) yield Unknown(origin=origin, subject=_JOBS, reason=reason, hides="jobs") diff --git a/project_validator/ci/github_actions.py b/project_validator/ci/github_actions.py index 430a2e45..7d41e2da 100644 --- a/project_validator/ci/github_actions.py +++ b/project_validator/ci/github_actions.py @@ -14,7 +14,7 @@ from project_validator.facts import NOTHING, ActionStep, CiJob, Command, Fact, Origin, Unknown from project_validator.facts.exit_status import ERREXIT, STRICT, Shell, shell_of from project_validator.facts.expansion import advised, script_facts -from project_validator.facts.shell import ShellSyntaxError, split_words +from project_validator.facts.shell import CMD, POSIX, POWERSHELL, Dialect, ShellSyntaxError, split_words from project_validator.includes import Chain, Refused, follow from project_validator.limits import COMPOSITE_ACTIONS, REUSABLE_WORKFLOWS from project_validator.platforms import detect_operating_systems @@ -52,13 +52,13 @@ def replacement(reference: Reference) -> str | None: # An expression GitHub evaluates before the shell runs the step. EXPRESSION = re.compile(r"\$\{\{.*?\}\}") +# The POSIX shells GitHub runs by name, as it runs them. +_NAMED_SHELLS = {"bash": STRICT, "sh": ERREXIT} +# The shells GitHub knows that are not POSIX shells, and how each reads a script. +_DIALECTS = {"pwsh": POWERSHELL, "powershell": POWERSHELL, "cmd": CMD} # The shells whose scripts are split into commands; another `shell:` names a program that runs the step's script as a # whole (`python {0}`, `Rscript {0}`). -_SHELLS = frozenset({"bash", "sh", "pwsh", "powershell", "cmd"}) - - -# The shells GitHub runs by name, as it runs them. -_NAMED_SHELLS = {"bash": STRICT, "sh": ERREXIT} +_SHELLS = frozenset({*_NAMED_SHELLS, *_DIALECTS}) def custom_shell(shell: str | None) -> tuple[str, ...] | None: @@ -422,7 +422,7 @@ def run_facts( condition=condition, opaque=EXPRESSION, via=via, - powershell=self.powershell(step, known), + dialect=self.dialect(step, known), shell=self.exit_shell(step, known), ) yield from advised(commands, self.advisory) @@ -437,17 +437,18 @@ def custom_command( argv = tuple(script if word == "{0}" else word for word in custom) return Command(origin=at, job=self.identity, argv=argv, line=script, env=env, directory=directory) - def powershell(self, step: Mapping[str, object], known: Known) -> bool: - """Whether a step's script is PowerShell: its `shell`, the job's default, or the runner's (pwsh on Windows).""" + def dialect(self, step: Mapping[str, object], known: Known) -> Dialect: + """How a step's script is read: as its `shell` reads it, the job's default, or the runner's (pwsh on + Windows, else bash).""" shell = step.get("shell") or self.shell if shell is None: - return known.os == "windows" - return str(shell).split()[0] in ("pwsh", "powershell") + return POWERSHELL if known.os == "windows" else POSIX + return _DIALECTS.get(str(shell).split()[0], POSIX) def exit_shell(self, step: Mapping[str, object], known: Known) -> Shell | None: """How a step's shell treats a failing command (see `Shell`): GitHub's default, `bash -e {0}`, has no pipefail, unlike `shell: bash`; None for PowerShell and cmd, and a shell an expression names.""" - if self.powershell(step, known): + if self.dialect(step, known) is not POSIX: return None shell = self.optional(step.get("shell")) or self.shell if shell is None: diff --git a/project_validator/ci/gitlab.py b/project_validator/ci/gitlab.py index 3dce83c1..cb4ba4ae 100644 --- a/project_validator/ci/gitlab.py +++ b/project_validator/ci/gitlab.py @@ -17,7 +17,7 @@ from project_validator.facts import CiJob, Command, Fact, Origin, Unknown from project_validator.facts.exit_status import STRICT, after from project_validator.facts.expansion import advised, script_facts -from project_validator.facts.shell import ShellCommand, split_script +from project_validator.facts.shell import POSIX, POWERSHELL, ShellCommand, split_script from project_validator.includes import Chain, Refused, follow from project_validator.limits import GITLAB_EXTENDS, GITLAB_INCLUDES, GITLAB_REFERENCES from project_validator.platforms import detect_operating_systems @@ -142,13 +142,19 @@ def _lines_facts( for number, (text, origin) in enumerate(script): followed = number < len(script) - 1 yield from script_facts( - text, job=job, origin=origin, env=env, powershell=windows, shell=shell, followed=followed + text, + job=job, + origin=origin, + env=env, + dialect=POWERSHELL if windows else POSIX, + shell=shell, + followed=followed, ) if shell is not None: shell = after([found for found in split_script(text) if isinstance(found, ShellCommand)], shell) for key, text, origin in lines: if key == "after_script": - facts = script_facts(text, job=job, origin=origin, env=env, powershell=windows) + facts = script_facts(text, job=job, origin=origin, env=env, dialect=POWERSHELL if windows else POSIX) yield from advised(facts, _AFTER_SCRIPT) diff --git a/project_validator/facts/expansion.py b/project_validator/facts/expansion.py index 15c7b7c2..3fbeb711 100644 --- a/project_validator/facts/expansion.py +++ b/project_validator/facts/expansion.py @@ -25,7 +25,7 @@ from project_validator.facts.conditions import ALWAYS, DIMENSIONS, Condition, both, only from project_validator.facts.exit_status import Shell, masked from project_validator.facts.placed import Placed -from project_validator.facts.shell import ShellCommand, ShellSyntaxError, Unsplittable, split_script +from project_validator.facts.shell import POSIX, Dialect, ShellCommand, ShellSyntaxError, Unsplittable, split_script from project_validator.templates import SHELL if TYPE_CHECKING: @@ -49,6 +49,8 @@ class Script: shell: Shell | None = None # Why none of the text's commands can fail what runs it (make's `-` before a recipe line), when none can. advisory: str = "" + # How the text is read: as the shell that runs it reads it (a batch file's is cmd's). + dialect: Dialect = POSIX @dataclass(frozen=True, slots=True, kw_only=True) @@ -132,15 +134,15 @@ def script_facts( condition: str | None = None, opaque: re.Pattern[str] | None = None, via: tuple[Origin, ...] = (), - powershell: bool = False, + dialect: Dialect = POSIX, whole: bool = False, shell: Shell | None = None, followed: bool = False, ) -> Iterator[Fact]: """The commands of a shell script a job runs (see `split_script`, `Script.whole`, `masked` for the rest).""" - assigned, constants = _seen_assigned(script, whole or not via, powershell=powershell), _Constants(script) + assigned, constants = _seen_assigned(script, whole or not via, dialect=dialect), _Constants(script) command = partial(Command, job=job, condition=condition, via=via) - yield from _unread(split := list(split_script(script, opaque, powershell=powershell)), origin) + yield from _unread(split := list(split_script(script, opaque, dialect=dialect)), origin) for found, advisory in _judged(split, shell, followed): if isinstance(found, ShellCommand): made = command( @@ -199,10 +201,10 @@ def _assigned(script: str) -> frozenset[str]: return frozenset(name for match in _ASSIGNED.finditer(script) for name in match.groups() if name) -def _seen_assigned(script: str, whole: bool, *, powershell: bool) -> frozenset[str] | None: - """The variables a script sets, when what it sets is all seen: a whole shell script that sources no other file; - None otherwise (a script read in part, PowerShell, a script that reads another into itself).""" - return _assigned(script) if whole and not powershell and not _SOURCES.search(script) else None +def _seen_assigned(script: str, whole: bool, *, dialect: Dialect) -> frozenset[str] | None: + """The variables a POSIX shell script sets, when what it sets is all seen: a whole script that sources no other + file; None otherwise (a script read in part, another shell's, a script that reads another into itself).""" + return _assigned(script) if whole and dialect is POSIX and not _SOURCES.search(script) else None # A script that reads another into itself (`. ./env.sh`, `source ci/vars`) may set what is not seen. @@ -330,6 +332,7 @@ def _script_children(command: Command, script: Script, via: tuple[Origin, ...]) via=via, whole=script.whole, shell=script.shell, + dialect=script.dialect, ) yield from advised(commands, command.advisory or script.advisory) diff --git a/project_validator/facts/shell.py b/project_validator/facts/shell.py index 069f72d7..c1b89aa1 100644 --- a/project_validator/facts/shell.py +++ b/project_validator/facts/shell.py @@ -16,9 +16,13 @@ from dataclasses import dataclass, field, replace from project_validator.facts.shell_syntax import ( + CMD, + POSIX, + POWERSHELL, Assignment, Case, Compounded, + Dialect, For, Function, Group, @@ -92,8 +96,6 @@ def quoted(word: str) -> str: READS_STATUS = re.compile(r"\$\?|\$\{\?\}|PIPESTATUS") # The longest fallback named whole; a longer one is named by its program. _FALLBACK_SHOWN = 24 -_CONTINUATION = re.compile(r"\\\r?\n") -_POWERSHELL_CONTINUATION = re.compile(r"`\r?\n") # PowerShell has no compound commands in the tree: its keywords and braces are words, read as they always were. _KEYWORDS = frozenset({"then", "do", "else", "elif", "if", "while", "until", "!", "{", "}"}) _CLOSING = frozenset({"fi", "done", "esac"}) @@ -126,7 +128,7 @@ class _Level: text: str root: Script - powershell: bool + dialect: Dialect found: list[_Found] = field(default_factory=list) substitutions: list[Word] = field(default_factory=list) # the words that hold them, in order @@ -135,7 +137,7 @@ def line(self, offset: int) -> int: def line_text(self, index: int) -> str: start, end = self.root.lines[index] - continuation = _POWERSHELL_CONTINUATION if self.powershell else _CONTINUATION + continuation = re.compile(re.escape(self.dialect.escape) + r"\r?\n") return continuation.sub(" ", self.text[start:end]).strip() # walking the tree @@ -164,8 +166,10 @@ def pipeline(self, pipeline: Pipeline, after: str, rest: tuple[Pipeline, ...], c def simple(self, command: Simple, operator: str, condition: str, rest: tuple[Pipeline, ...]) -> None: self.substitutions.extend(_words_of(command)) argv = tuple(word.value for word in command.words) - if self.powershell: + if self.dialect is POWERSHELL: argv, condition = self.powershell_words(command, argv, condition) + elif self.dialect is CMD: + argv = _cmd_words(argv) env = tuple((assignment.name, _assigned(assignment)) for assignment in command.assignments) if argv: self.found.append(_Found(command, argv, env, operator, condition, rest)) @@ -259,7 +263,7 @@ def fallback(self, found: _Found) -> str: line = self.line(found.command.start) if self.line(end[1] - 1) != line or READS_STATUS.search(self.text[start[0] : end[1]]): return "" - level = _Level(self.text, self.root, self.powershell) + level = _Level(self.text, self.root, self.dialect) for pipeline in found.rest: level.pipeline(pipeline, "", (), "") commands = level.found @@ -301,7 +305,7 @@ def nested_on(self, line: int) -> Iterator[ShellCommand | Unsplittable]: words = sorted((word for word in self.substitutions if self.line(word.start) == line), key=lambda w: w.start) for word in words: for substitution in word.substitutions(): - yield from map(_nested, _derived(self.text, substitution.script, self.powershell)) + yield from map(_nested, _derived(self.text, substitution.script, self.dialect)) def shell_command(self, found: _Found, line: str) -> ShellCommand: return ShellCommand( @@ -316,6 +320,43 @@ def shell_command(self, found: _Found, line: str) -> ShellCommand: ) +# What, in cmd, comes before the command a line runs: `@` (not echoed), and the words that run it (`else`, `call`). +_CMD_PREFIXES = frozenset({"else", "call"}) +# The tests of cmd's `if` that take one word (`if exist build`), and its comparisons (`if %A% EQU 1`). +_CMD_TESTS = frozenset({"errorlevel", "exist", "defined", "cmdextversion"}) +_CMD_COMPARISONS = frozenset({"==", "equ", "neq", "lss", "leq", "gtr", "geq"}) + + +def _cmd_words(argv: tuple[str, ...]) -> tuple[str, ...]: + """The command a cmd line runs: without `@`, an `if`'s test, a `for`'s loop up to `do`, `else` and `call`; none + for a label (`:build`, and `call :build`).""" + while argv: + head = argv[0].lower() + if head.startswith("@"): + argv = (argv[0][1:], *argv[1:]) if len(argv[0]) > 1 else argv[1:] + elif head == "if": + argv = _after_cmd_test(argv[1:]) + elif head == "for": + lowered = [word.lower() for word in argv] + argv = argv[lowered.index("do") + 1 :] if "do" in lowered else () + elif head in _CMD_PREFIXES: + argv = argv[1:] + else: + break + return () if argv[:1] and argv[0].startswith(":") else argv + + +def _after_cmd_test(words: tuple[str, ...]) -> tuple[str, ...]: + """What follows an `if`'s test (`[/i] [not] exist build`, `"%A%"=="b"`, `%A% EQU 1`): the command it runs.""" + while words[:1] and words[0].lower() in ("/i", "not"): + words = words[1:] + if words[:1] and words[0].lower() in _CMD_TESTS: + return words[2:] + if len(words) > 1 and words[1].lower() in _CMD_COMPARISONS: + return words[3:] + return words[1:] + + # A PowerShell assignment (`$x = …`, `$x += …`), and a command name its value may be the output of (`$r = gh …`). _POWERSHELL_ASSIGNMENT = frozenset({"=", "+=", "-=", "*=", "/=", "%=", "??="}) _POWERSHELL_COMMAND = re.compile(r"[A-Za-z][\w.-]*") @@ -358,27 +399,31 @@ def _nested(found: ShellCommand | Unsplittable) -> ShellCommand | Unsplittable: return replace(found, nested=True) if isinstance(found, ShellCommand) else found -def _derived(text: str, script: Script, powershell: bool) -> Iterator[ShellCommand | Unsplittable]: - level = _Level(text, script, powershell) +def _derived(text: str, script: Script, dialect: Dialect) -> Iterator[ShellCommand | Unsplittable]: + level = _Level(text, script, dialect) level.script(script, "") return level.stream() def split_script( - script: str, opaque: re.Pattern[str] | None = None, *, powershell: bool = False + script: str, opaque: re.Pattern[str] | None = None, *, dialect: Dialect = POSIX ) -> Iterator[ShellCommand | Unsplittable]: """The simple commands of `script`, in order, each with the line it was written on; the commands of a command substitution come before the line they are part of. Text matching `opaque` (such as a CI expression the CI service evaluates before the shell runs) is kept as - written, quotes and all, inside the word it is part of. PowerShell scripts (`powershell=True`) are split with - PowerShell's escape character, the backquote, in place of the backslash (which is text there). + written, quotes and all, inside the word it is part of. The script is read as its shell's `dialect` reads it + (`POWERSHELL`: the backquote escapes, and the backslash is text). """ - yield from _derived(script, parse(script, opaque=opaque, powershell=powershell), powershell) + yield from _derived(script, parse(script, opaque=opaque, dialect=dialect), dialect) __all__ = [ + "CMD", + "POSIX", + "POWERSHELL", "READS_STATUS", + "Dialect", "ShellCommand", "ShellSyntaxError", "Unsplittable", diff --git a/project_validator/facts/shell_syntax.py b/project_validator/facts/shell_syntax.py index df03c7b8..a7349e32 100644 --- a/project_validator/facts/shell_syntax.py +++ b/project_validator/facts/shell_syntax.py @@ -11,8 +11,12 @@ is text; a substitution nested past `SHELL_NESTING` is kept as written, not parsed; a compound command that is never closed ends with the script; and a closing word that closes nothing is skipped. -PowerShell (`powershell=True`) is split with the backquote as its escape character and without the POSIX shell's -compound commands: its lines are lists of pipelines of simple commands, keywords and braces included as words. +How a script is read is its shell's `Dialect`. A POSIX shell's (`POSIX`) is the structure above. PowerShell's +(`POWERSHELL`) has the backquote as its escape character and none of the POSIX shell's compound commands: its lines are +lists of pipelines of simple commands, keywords and braces included as words. Windows's cmd (`CMD`) is read so too, with +its own escape (`^`), quoting (only `"`, in which `^` is text), comments (`REM`, `::`) and operators (no `;`); its +parentheses hold blocks where cmd opens one (where a command starts, after an `if`'s test, `else` or `do`), and each +block's commands are lines of their own. """ from __future__ import annotations @@ -26,6 +30,49 @@ from project_validator.parsing import ParseError, Span +@dataclass(frozen=True, slots=True) +class Dialect: + """How a shell reads a script: + - its `escape` character, which also continues a line, and whether it escapes in double quotes; + - whether it has the POSIX shell's compound commands (`if`, `while`, `for`, `case`, …: `compounds`), its other + quoting (`$'…'` and backquoted command substitution: `posix_quoting`), single quotes, and the substitutions `$` + starts (`$(…)`, `${…}`, `$((…))`, and the process substitutions `<(…)`, `>(…)`); + - the characters that end an unquoted word, where its operators start (`breaks`); + - what starts a comment (`comment`), anywhere a word could start or only where a command does; + - whether parentheses hold blocks of commands (`blocks`, cmd's: see the module's documentation).""" + + name: str + escape: str + compounds: bool = False + posix_quoting: bool = False + escapes_in_quotes: bool = True + single_quotes: bool = True + substitutions: bool = True + breaks: str = ";&|()<>" + comment: re.Pattern[str] = re.compile("#") + comments_start_commands: bool = False + blocks: bool = False + + +POSIX = Dialect("sh", "\\", compounds=True, posix_quoting=True) +POWERSHELL = Dialect("PowerShell", "`") +CMD = Dialect( + "cmd", + "^", + escapes_in_quotes=False, + single_quotes=False, + substitutions=False, + breaks="&|<>", + comment=re.compile(r"(?i:rem)(?=[ \t\r\n]|$)|::"), + comments_start_commands=True, + blocks=True, +) +# What separates commands, so that the next word starts one (as cmd's comments need). +_SEPARATORS = frozenset({"&&", "||", "&", "|", ";"}) +# The words after which, in cmd, a parenthesis opens a block (and an `if`'s, after its test). +_BLOCK_OPENERS = frozenset({"else", "do"}) + + class ShellSyntaxError(ParseError): """What is wrong in a script (an unclosed quote, an `if` without its `fi`), and where: `offset` in the text.""" @@ -296,8 +343,8 @@ def _is(token: _Token | None, *operators: str) -> bool: class _Source: """The whole script, and positions in it as lines and columns.""" - def __init__(self, text: str, opaque: re.Pattern[str] | None, escape: str) -> None: - self.text, self.escape = text, escape + def __init__(self, text: str, opaque: re.Pattern[str] | None, dialect: Dialect) -> None: + self.text, self.dialect, self.escape = text, dialect, dialect.escape self.newlines = [index for index, character in enumerate(text) if character == "\n"] self.opaque = {match.start(): match.end() for match in opaque.finditer(text)} if opaque else {} @@ -341,9 +388,11 @@ def _closing(text: str, start: int, end: int, escape: str = "\\") -> int | None: class _Lexer: """The tokens of `text[start:end]`, one level of substitution deep (`depth`).""" - def __init__(self, source: _Source, start: int, end: int, depth: int, *, powershell: bool) -> None: + def __init__(self, source: _Source, start: int, end: int, depth: int) -> None: self.source, self.text, self.position, self.end = source, source.text, start, end - self.depth, self.powershell = depth, powershell + self.depth = depth + self.dialect = source.dialect + self.blocks_open = 0 self.tokens: list[_Token] = [] self.heredocs: list[tuple[str, _Token]] = [] # delimiters waiting for the next newline, with their token self.bodies: dict[int, str] = {} # a here-document's body by its delimiter word's offset @@ -365,10 +414,12 @@ def run(self) -> None: self.tokens.append(_Token("newline", "\n", self.position, self.position + 1)) self.position += 1 self.read_heredocs() - elif character == "#": + elif self.at_comment(): newline = self.text.find("\n", self.position, self.end) self.position = self.end if newline < 0 else newline - elif self.text.startswith(("<(", ">("), self.position): + elif self.block(character): + self.position += 1 + elif self.dialect.substitutions and self.text.startswith(("<(", ">("), self.position): self.tokens.append(self.word()) elif (operator := self.operator()) is not None: self.tokens.append(_Token("operator", operator, self.position, self.position + len(operator))) @@ -376,7 +427,43 @@ def run(self) -> None: else: self.tokens.append(self.word()) + def at_comment(self) -> bool: + """Whether a comment starts here: where a word could, or, in a dialect whose comments are commands (cmd's + `REM`), where a command could.""" + if not self.dialect.comment.match(self.text, self.position, self.end): + return False + return not self.dialect.comments_start_commands or not self.command_words() + + def command_words(self) -> list[_Token]: + """The tokens of the command being read, since the line, block or operator before it.""" + found: list[_Token] = [] + for token in reversed(self.tokens): + if token.kind == "newline" or (token.kind == "operator" and token.text in _SEPARATORS): + break + found.append(token) + return found[::-1] + + def block(self, character: str) -> bool: + """In a dialect with blocks, whether a parenthesis opens one (where a command starts, after an `if`'s test, + `else` or `do`) or closes the one open; each is a line break, so that a block's commands are lines of their own. + Any other parenthesis is text.""" + if not self.dialect.blocks or character not in "()": + return False + if character == ")": + if not self.blocks_open: + return False + self.blocks_open -= 1 + else: + words = [token.text.lower() for token in self.command_words()] + if words and words[0] != "if" and words[-1] not in _BLOCK_OPENERS: + return False + self.blocks_open += 1 + self.tokens.append(_Token("newline", character, self.position, self.position + 1)) + return True + def operator(self) -> str | None: + if self.text[self.position] not in self.dialect.breaks: + return None return next( (operator for operator in _OPERATORS if self.text.startswith(operator, self.position, self.end)), None ) @@ -439,33 +526,44 @@ def read(self) -> Word: def ends_word(self, position: int) -> bool: character = self.text[position] - if position == self.start and self.text.startswith(("<(", ">("), position): + dialect = self.source.dialect + if position == self.start and dialect.substitutions and self.text.startswith(("<(", ">("), position): return False # a process substitution starts the word if character in " \t\r\n" or self.lexer.at_continuation(position): return True - return character in ";&|()<>" and position not in self.source.opaque + if character == ")" and self.lexer.blocks_open: + return True # it closes a block + return character in dialect.breaks and position not in self.source.opaque def step(self, quote: str) -> None: """Read what starts at the lexer's position, inside `quote` ("", or `"`).""" - lexer, position, escape = self.lexer, self.lexer.position, self.source.escape + lexer, position = self.lexer, self.lexer.position character = self.text[position] if position in self.source.opaque: self.add(Verbatim(self.text[position : self.source.opaque[position]])) lexer.position = self.source.opaque[position] - elif self.expansion(position, quote): + elif self.source.dialect.substitutions and self.expansion(position, quote): return - elif character == escape: + elif character == self.source.escape and (not quote or self.source.dialect.escapes_in_quotes): self.escaped(position, quote) - elif character == "'" and not quote: - self.bounded(self.single_quoted, position) - elif character == "$" and not quote and self.text.startswith("$'", position) and escape == "\\": - self.bounded(self.ansi_c_quoted, position) - elif character == '"' and not quote: - self.bounded(self.double_quoted, position) + elif (reader := self.quoting(character, position, quote)) is not None: + self.bounded(reader, position) else: self.literal.append(character) lexer.position += 1 + def quoting(self, character: str, position: int, quote: str) -> Callable[[int], None] | None: + """The reader of the quoted part that starts at `position`, outside quotes, in the dialect's quoting; None + where none starts.""" + dialect = self.source.dialect + if quote: + return None + if character == "'" and dialect.single_quotes: + return self.single_quoted + if character == "$" and dialect.posix_quoting and self.text.startswith("$'", position): + return self.ansi_c_quoted + return self.double_quoted if character == '"' else None + def bounded(self, reader: Callable[[int], None], position: int) -> None: """Read a quoted part with `reader`; when it is never closed, report it, and read it again to the end of the line it opened on, where it is taken to close.""" @@ -566,7 +664,7 @@ def expansion(self, position: int, quote: str) -> bool: if (end := _closing(text, position, lexer.end, self.source.escape)) is None: return self.unclosed(position) self.substitution(position, end, position + 2, end - 1) - elif text.startswith("`", position) and self.source.escape != "`": + elif text.startswith("`", position) and self.source.dialect.posix_quoting: if (close := text.find("`", position + 1, lexer.end)) < 0: return self.unclosed(position) end = close + 1 @@ -617,7 +715,7 @@ def substitution(self, start: int, end: int, inner_start: int, inner_end: int) - self.add( Substitution( self.text[start:end], - _parse(self.source, inner_start, inner_end, depth, powershell=self.lexer.powershell), + _parse(self.source, inner_start, inner_end, depth), ) ) @@ -638,8 +736,9 @@ def quoted_delimiter_ok(self, word: Word) -> bool: class _Parser: - def __init__(self, source: _Source, tokens: list[_Token], bodies: dict[int, str], *, powershell: bool) -> None: - self.source, self.tokens, self.bodies, self.powershell = source, tokens, bodies, powershell + def __init__(self, source: _Source, tokens: list[_Token], bodies: dict[int, str]) -> None: + self.source, self.tokens, self.bodies = source, tokens, bodies + self.compounds_read = source.dialect.compounds self.index = 0 self.stops: list[frozenset[str]] = [] self.open_subshells = 0 @@ -652,9 +751,9 @@ def __init__(self, source: _Source, tokens: list[_Token], bodies: dict[int, str] self.flat = False def problem(self, message: str, offset: int) -> None: - """Report what is wrong at `offset`; PowerShell, read without compound commands, is not judged by them, nor a + """Report what is wrong at `offset`; a dialect read without compound commands is not judged by them, nor a script read flat past `SHELL_COMPOUNDS`, whose structure is no longer followed (its limit says so once).""" - if not self.powershell and not self.flat: + if self.compounds_read and not self.flat: self.errors.append(self.source.error(message, offset)) # tokens @@ -672,7 +771,7 @@ def reserved(self, *words: str) -> bool: """Whether the next token is one of the reserved `words`, as written (unquoted).""" token = self.peek() return ( - not self.powershell + self.compounds_read and token is not None and token.kind == "word" and token.word is not None @@ -760,7 +859,7 @@ def command(self) -> Simple | Compounded: return Compounded(compound, self.redirections()) def compound(self, start: int) -> Compound | None: - if self.powershell or self.peek() is None: + if not self.compounds_read or self.peek() is None: return None if self.nests() and not self.flat and not SHELL_COMPOUNDS.allows(self.compounds + 1): self.errors.append(self.source.error(SHELL_COMPOUNDS.reason, start)) @@ -1135,18 +1234,17 @@ def _lines(tokens: list[_Token], end: int) -> list[tuple[int, int]]: return lines -def _parse(source: _Source, start: int, end: int, depth: int, *, powershell: bool) -> Script: +def _parse(source: _Source, start: int, end: int, depth: int) -> Script: """The tree of `text[start:end]`, `depth` substitutions deep, with what is wrong in it.""" - lexer = _Lexer(source, start, end, depth, powershell=powershell) + lexer = _Lexer(source, start, end, depth) lexer.run() - parser = _Parser(source, lexer.tokens, lexer.bodies, powershell=powershell) + parser = _Parser(source, lexer.tokens, lexer.bodies) script = parser.script(start) errors = sorted([*lexer.errors, *parser.errors], key=lambda error: error.offset) return Script(script.items, tuple(_lines(lexer.tokens, end)), start, end, tuple(errors)) -def parse(script: str, *, opaque: re.Pattern[str] | None = None, powershell: bool = False) -> Script: +def parse(script: str, *, opaque: re.Pattern[str] | None = None, dialect: Dialect = POSIX) -> Script: """The tree of `script`. Text matching `opaque` (a CI expression the CI service evaluates first) is kept as written, quotes and all, inside the word it is part of.""" - source = _Source(script, opaque, "`" if powershell else "\\") - return _parse(source, 0, len(script), 0, powershell=powershell) + return _parse(_Source(script, opaque, dialect), 0, len(script), 0) diff --git a/project_validator/tools/shell_scripts.py b/project_validator/tools/shell_scripts.py index 1562c88b..1158e3e9 100644 --- a/project_validator/tools/shell_scripts.py +++ b/project_validator/tools/shell_scripts.py @@ -1,7 +1,9 @@ -"""Shell scripts of the project that CI runs (`ci/lint.sh`, `bash scripts/check.sh`): the commands they run in turn. +"""Shell scripts of the project that CI runs (`ci/lint.sh`, `bash scripts/check.sh`, `scripts\\build.bat`, +`pwsh -File ci/test.ps1`): the commands they run in turn, each read in the dialect of the shell that runs it (see +`project_validator.facts.shell`). -A script runs where the command that runs it does; its arguments (`$1`) are not known. Shell functions it defines -are not followed: their bodies are split like any other lines. +A script runs where the command that runs it does; its arguments (`$1`, `%1`) are not known. Shell functions it +defines are not followed: their bodies are split like any other lines. """ from __future__ import annotations @@ -14,6 +16,7 @@ from project_validator.facts.arguments import positional, program from project_validator.facts.exit_status import Shell, shell_of from project_validator.facts.expansion import CommandExpander, Expansion, Script, joined +from project_validator.facts.shell import CMD, POSIX, POWERSHELL, Dialect SHELLS = frozenset({"sh", "bash", "zsh", "dash", "ksh"}) # Shell options that take a value (`bash -o pipefail script.sh`). @@ -28,16 +31,53 @@ def interpreter(text: str) -> str | None: return match["name"] if match else None -def _script(command: Command) -> str | None: - """The script file a command runs: `sh script.sh` (not `sh -c '…'`), `./script.sh` run directly, or a script - the shell sources (`. ci/env.sh`, `source ci/env.sh`).""" +# The suffixes of the scripts other shells run, and how each is read. +_SUFFIXES = {".bat": CMD, ".cmd": CMD, ".ps1": POWERSHELL} +# PowerShell's options that take a value, and the one that names a script file to run. +_POWERSHELL_VALUES = frozenset({"-File", "-f", "-ExecutionPolicy", "-ep", "-Command", "-c"}) + + +def _script(command: Command) -> tuple[str, Dialect] | None: + """The script file a command runs, and how it is read: `sh script.sh` (not `sh -c '…'`), `./script.sh` run + directly, or a script the shell sources (`. ci/env.sh`, `source ci/env.sh`); a batch file (`scripts\\build.bat`, + `cmd /c build.bat`), or a PowerShell script (`./ci/test.ps1`, `pwsh -File ci/test.ps1`).""" argv = resolved(command) if argv[:1] in ((".",), ("source",)): - return argv[1] if len(argv) > 1 else None - if program(argv) in SHELLS: - words, _ = positional(argv, _SHELL_VALUES) - return None if "-c" in argv[1:] or not words else words[0] - return argv[0] if argv and ("/" in argv[0] or argv[0].endswith(".sh")) else None + return (argv[1], POSIX) if len(argv) > 1 else None + if program(argv) in (*SHELLS, "cmd", "pwsh", "powershell"): + return _run_by_shell(argv) + if argv and (suffixed := _suffixed(argv[0])) is not None: + return suffixed + return (argv[0], POSIX) if argv and ("/" in argv[0] or argv[0].endswith(".sh")) else None + + +def _run_by_shell(argv: tuple[str, ...]) -> tuple[str, Dialect] | None: + """The script a shell runs: `bash script.sh` (not `bash -c '…'`), `cmd /c build.bat`, `pwsh -File test.ps1`.""" + name = program(argv) + if name == "cmd": + rest = [word for word in argv[1:] if word.lower() not in ("/c", "/k", "/d", "/q", "/s")] + return _suffixed(rest[0]) if rest and any(word.lower() in ("/c", "/k") for word in argv[1:]) else None + if name in ("pwsh", "powershell"): + found = _powershell_file(argv) + return None if found is None else (found, POWERSHELL) + words, _ = positional(argv, _SHELL_VALUES) + return None if "-c" in argv[1:] or not words else (words[0], POSIX) + + +def _suffixed(word: str) -> tuple[str, Dialect] | None: + """A batch file or a PowerShell script by its suffix, its path written with slashes (`scripts\\build.bat`).""" + dialect = next((found for suffix, found in _SUFFIXES.items() if word.lower().endswith(suffix)), None) + return None if dialect is None else (word.replace("\\", "/"), dialect) + + +def _powershell_file(argv: tuple[str, ...]) -> str | None: + """The script `pwsh -File script.ps1` (or `pwsh script.ps1`) runs; None for `pwsh -Command …`.""" + for index, word in enumerate(argv[1:], start=1): + if word in ("-File", "-f") and index + 1 < len(argv): + return argv[index + 1].replace("\\", "/") + words, _ = positional(argv, _POWERSHELL_VALUES) + command = any(word in ("-Command", "-c") for word in argv[1:]) + return words[0].replace("\\", "/") if words and not command and words[0].lower().endswith(".ps1") else None # Scripts that are not shell to read: a launcher with an archive after its shebang (scalafmt's, metals'), and the @@ -45,23 +85,29 @@ def _script(command: Command) -> str | None: _GENERATED = re.compile(r"^#[^\n]*Generated by GNU Autoconf", re.MULTILINE) -def _is_shell_script(text: str, path: str) -> bool: +def _is_shell_script(text: str, path: str, dialect: Dialect) -> bool: readable = "\0" not in text[:65536] and not _GENERATED.search(text[:4096]) - return readable and (path.endswith(".sh") or interpreter(text) in SHELLS) + return readable and (dialect is not POSIX or path.endswith(".sh") or interpreter(text) in SHELLS) def _shell_script(command: Command, context: Context) -> list[Expansion] | None: - path = _script(command) - if path is None or path.startswith(("/", "$", "~", ":")) or any(character in path for character in " \t\n*?["): - return None # elsewhere, a pattern, or a whole command line quoted as one word (`"bash -x ./ci/test.sh"`) + if (found_script := _script(command)) is None: + return None + path, dialect = found_script + if path.startswith(("/", "$", "~")) or any(character in path for character in " \t\n*?[%:"): + # Elsewhere (`C:/BuildTools/vcvars64.bat` too), a pattern, or a whole command line quoted as one word + # (`"bash -x ./ci/test.sh"`). + return None found = joined(command.directory, path.removeprefix("./")) if not context.project.exists(found): # A program the build makes (`./build/app`) is not in the repository either; a shell script is written by CI. - return [_missing(command, found)] if found.endswith((".sh", ".bash")) else None - if not _is_shell_script(text := context.project.read_text(found), found): + # A batch file or PowerShell script most often is a program (`npm.cmd`) or generated (`vendor/bin/x.bat`). + return [_missing(command, found)] if dialect is POSIX and found.endswith((".sh", ".bash")) else None + if not _is_shell_script(text := context.project.read_text(found), found, dialect): return None origin = Origin(path=str(PurePosixPath(found))) - return [Script(text=text, origin=origin, whole=True, shell=_shell(resolved(command), text))] + shell = _shell(resolved(command), text) if dialect is POSIX else None + return [Script(text=text, origin=origin, whole=True, shell=shell, dialect=dialect)] def _shell(argv: tuple[str, ...], text: str) -> Shell | None: diff --git a/tests/fuzz/fuzz_shell.py b/tests/fuzz/fuzz_shell.py index ec1d2002..2515bab6 100755 --- a/tests/fuzz/fuzz_shell.py +++ b/tests/fuzz/fuzz_shell.py @@ -8,13 +8,13 @@ import atheris with atheris.instrument_imports(): - from project_validator.facts.shell import split_script + from project_validator.facts.shell import POWERSHELL, split_script def TestOneInput(data: bytes) -> None: text = data.decode("utf-8", "surrogateescape") list(split_script(text)) - list(split_script(text, powershell=True)) + list(split_script(text, dialect=POWERSHELL)) if __name__ == "__main__": diff --git a/tests/test_expansion.py b/tests/test_expansion.py index 724c480d..40c8da89 100644 --- a/tests/test_expansion.py +++ b/tests/test_expansion.py @@ -653,6 +653,41 @@ def test_a_scripts_commands_are_placed_where_the_file_has_them_and_a_steps_are_n self.assertEqual(placed[("make", "all")], "ci/build.sh:4:3") self.assertEqual(placed[("echo", "done")], f"{GITHUB_WORKFLOW}:1:60 (jobs.build.steps[0].run)") + def test_batch_and_powershell_script_files_are_read_in_their_shells_dialect(self) -> None: + files = { + "scripts/build.bat": "@echo off\r\ncmake --build build --config %1\r\nif errorlevel 1 exit /b 1\r\n", + "ci/test.ps1": "Invoke-Pester -Path tests `\n -CI\n", + } + for shell, line, expected in ( + ("cmd", "call scripts\\build.bat Release", ("cmake", "--build", "build", "--config", "%1")), + ("bash", "cmd /c scripts/build.bat", ("cmake", "--build", "build", "--config", "%1")), + ("pwsh", "pwsh -File ci/test.ps1", ("Invoke-Pester", "-Path", "tests", "-CI")), + ("pwsh", "./ci/test.ps1", ("Invoke-Pester", "-Path", "tests", "-CI")), + ): + with self.subTest(line=line): + job = {"runs-on": "windows-latest", "steps": [{"run": line, "shell": shell}]} + facts = _facts({**files, GITHUB_WORKFLOW: json.dumps({"jobs": {"test": job}})}) + self.assertIn(expected, _expanded(facts)) + + def test_a_batch_file_the_project_does_not_hold_is_not_followed_nor_unknown(self) -> None: + """Most are generated (Composer's `vendor/bin/phpunit.bat`) or programs (`npm.cmd`), not the project's.""" + steps = [ + {"run": "call vendor\\bin\\phpunit.bat\nnpm.cmd ci\ncall C:\\BuildTools\\vcvars64.bat", "shell": "cmd"} + ] + job = {"runs-on": "windows-latest", "steps": steps} + facts = _facts({GITHUB_WORKFLOW: json.dumps({"jobs": {"test": job}})}) + self.assertEqual([fact.subject for fact in facts.of(Unknown)], []) + + def test_a_ci_file_scanned_heuristically_is_read_as_cmd_on_windows(self) -> None: + """Catch2's AppVeyor runs `.\\tools\\misc\\appveyorBuildConfigurationScript.bat`.""" + files = { + "appveyor.yml": "image: Visual Studio 2019\nbuild_script:\n - cmd: .\\tools\\build.bat\n", + "tools/build.bat": "cmake --build build\r\n", + } + facts = _facts(files) + self.assertIn(("cmake", "--build", "build"), _expanded(facts)) + self.assertEqual([fact.subject for fact in facts.of(Unknown) if fact.subject.startswith("the script")], []) + def test_other_files_and_inline_scripts_are_not_followed(self) -> None: files = {**self.SCRIPT, "tools/run.py": "print('x')\n", "ci/notes": "ruff check .\n"} for line in ( diff --git a/tests/test_facts.py b/tests/test_facts.py index c02615dd..43a36b37 100644 --- a/tests/test_facts.py +++ b/tests/test_facts.py @@ -343,6 +343,23 @@ def test_windows_runners_run_powershell(self) -> None: self.assertEqual(facts.of(Unknown), ()) self.assertIn(("cmake", "--build", "build", "--config", "Release"), [c.argv for c in facts.of(Command)]) + def test_a_cmd_step_is_read_as_cmd(self) -> None: + """fmt's `ctest … -j %NUMBER_OF_PROCESSORS%` and a path written with backslashes, as cmd reads them.""" + steps = [ + {"run": "if not exist build mkdir build\nbuild\\Release\\test.exe ^\n --x", "shell": "cmd"}, + {"run": "ctest -C Release -j %NUMBER_OF_PROCESSORS%"}, + ] + job = {"runs-on": "windows-latest", "defaults": {"run": {"shell": "cmd"}}, "steps": steps} + facts = _facts({GITHUB_WORKFLOW: json.dumps({"jobs": {"test": job}})}) + self.assertEqual( + [command.argv for command in facts.of(Command)], + [ + ("mkdir", "build"), + ("build\\Release\\test.exe", "--x"), + ("ctest", "-C", "Release", "-j", "%NUMBER_OF_PROCESSORS%"), + ], + ) + def test_a_custom_shell_runs_the_script_as_one_command(self) -> None: script = "cov <- covr::package_coverage(quiet = FALSE)\ncovr::to_cobertura(cov)\n" job = { diff --git a/tests/test_shell_commands.py b/tests/test_shell_commands.py index 330f6859..a265e9d5 100644 --- a/tests/test_shell_commands.py +++ b/tests/test_shell_commands.py @@ -5,7 +5,7 @@ import re import unittest -from project_validator.facts.shell import ShellCommand, Unsplittable, split_script +from project_validator.facts.shell import CMD, POWERSHELL, ShellCommand, Unsplittable, split_script from project_validator.limits import SHELL_NESTING from project_validator.parsing import Span @@ -103,10 +103,66 @@ def test_a_fallback_names_opaque_text_as_written(self) -> None: class PowerShellTests(unittest.TestCase): def test_an_assignment_is_no_command_but_a_command_it_assigns_runs(self) -> None: script = '$workspace = "C:\\" + (Split-Path $env:X -Leaf)\n$n = 3\n$r = gh issue create -t x\n$a += "b"\n' - found = [found.argv for found in split_script(script, powershell=True) if isinstance(found, ShellCommand)] + found = [found.argv for found in split_script(script, dialect=POWERSHELL) if isinstance(found, ShellCommand)] self.assertEqual(found, [("gh", "issue", "create", "-t", "x")]) +class CmdTests(unittest.TestCase): + """Windows's cmd, as GitHub's `shell: cmd` and a batch file run a script.""" + + @staticmethod + def _split(script: str) -> list[tuple[str, ...]]: + return [found.argv for found in split_script(script, dialect=CMD) if isinstance(found, ShellCommand)] + + def test_a_backslash_is_a_path_separator_and_the_caret_escapes_and_continues(self) -> None: + script = "build\\Release\\app.exe --x ^\n --y\necho a^&b\n" + self.assertEqual(self._split(script), [("build\\Release\\app.exe", "--x", "--y"), ("echo", "a&b")]) + + def test_double_quotes_quote_and_keep_carets_but_single_quotes_and_dollars_are_text(self) -> None: + script = 'cmake -G "NMake Makefiles" "-DX=a^b" ..\necho \'a b\' $HOME #1\n' + self.assertEqual( + self._split(script), + [("cmake", "-G", "NMake Makefiles", "-DX=a^b", ".."), ("echo", "'a", "b'", "$HOME", "#1")], + ) + + def test_rem_and_double_colons_start_comments_only_where_a_command_starts(self) -> None: + self.assertEqual(self._split("REM build it\n:: and test it\nrem\necho rem ::\n"), [("echo", "rem", "::")]) + + def test_operators_separate_commands(self) -> None: + script = "cmake --build . && ctest || exit /b 1 & echo done ; x\n" + self.assertEqual( + self._split(script), + [("cmake", "--build", "."), ("ctest",), ("exit", "/b", "1"), ("echo", "done", ";", "x")], + ) + + def test_an_if_or_for_runs_its_command_and_a_block_holds_commands(self) -> None: + script = ( + "@echo off\n" + "if errorlevel 1 exit /b 1\n" + 'if not exist "build" (\n mkdir build\n) else (\n echo ok\n)\n' + 'if /i "%CC%"=="cl" call vcvars.bat x64\n' + "if %A% EQU 1 (ctest) else (ctest -V)\n" + "for %%f in (*.c) do cl /c %%f\n" + "%ProgramFiles(x86)%\\tool.exe /x\n" + "call :label\n" + ":label\n" + ) + self.assertEqual( + self._split(script), + [ + ("echo", "off"), + ("exit", "/b", "1"), + ("mkdir", "build"), + ("echo", "ok"), + ("vcvars.bat", "x64"), + ("ctest",), + ("ctest", "-V"), + ("cl", "/c", "%%f"), + ("%ProgramFiles(x86)%\\tool.exe", "/x"), + ], + ) + + class ErrorTests(unittest.TestCase): """A script with an error yields the error, where it is, and every command that can still be read.""" diff --git a/tests/test_shell_syntax.py b/tests/test_shell_syntax.py index 4c4cad88..a9a2ea8b 100644 --- a/tests/test_shell_syntax.py +++ b/tests/test_shell_syntax.py @@ -6,7 +6,7 @@ import time import unittest -from project_validator.facts.shell import ShellCommand, split_script +from project_validator.facts.shell import POWERSHELL, ShellCommand, split_script from project_validator.facts.shell_syntax import ( Arithmetic, Case, @@ -326,7 +326,7 @@ def test_what_closes_nothing_says_so(self) -> None: self.assertEqual(_errors("make )"), [(") closes nothing", 1, 6)]) def test_powershell_has_no_compound_commands_to_be_wrong_about(self) -> None: - self.assertEqual([error.message for error in parse("if ($x) { a }", powershell=True).errors], []) + self.assertEqual([error.message for error in parse("if ($x) { a }", dialect=POWERSHELL).errors], []) if __name__ == "__main__":