Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions project_validator/ci/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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)))
Expand All @@ -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")


Expand Down
25 changes: 13 additions & 12 deletions project_validator/ci/github_actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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)
Expand All @@ -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:
Expand Down
12 changes: 9 additions & 3 deletions project_validator/ci/gitlab.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)


Expand Down
19 changes: 11 additions & 8 deletions project_validator/facts/expansion.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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)
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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)

Expand Down
71 changes: 58 additions & 13 deletions project_validator/facts/shell.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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"})
Expand Down Expand Up @@ -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

Expand All @@ -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
Expand Down Expand Up @@ -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))
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand All @@ -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.-]*")
Expand Down Expand Up @@ -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",
Expand Down
Loading
Loading