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
19 changes: 7 additions & 12 deletions project_validator/build_systems/cmake/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from pathlib import PurePosixPath

from project_validator.build_systems.cmake.build import CMAKE as CMAKE_BUILD_SYSTEM
from project_validator.build_systems.cmake.build import CMAKE_PACKAGE_MANAGERS
from project_validator.build_systems.cmake.build import CMAKE_PACKAGE_MANAGERS, definitions
from project_validator.build_systems.cmake.commands import Collector, CustomTarget
from project_validator.build_systems.cmake.ctest import BUILT_TESTS, CTEST
from project_validator.build_systems.cmake.evaluation import Evaluation
Expand Down Expand Up @@ -148,17 +148,12 @@ def _custom_targets(command: Command, context: Context) -> list[Expansion] | Non


def _script_arguments(argv: tuple[str, ...]) -> tuple[dict[str, str], str | None]:
"""`cmake [-D name[:type]=value]... -P script`: the variables it defines, and the script (None: not `-P`)."""
defines: dict[str, str] = {}
words = iter(argv[1:])
for word in words:
if word == "-P":
return defines, next(words, None)
if word.startswith("-D"):
definition = word[2:] or next(words, "")
name, _, value = definition.partition("=")
defines[name.partition(":")[0]] = value
return defines, None
"""`cmake [-D name[:type]=value]... -P script`: the variables it defines before the script, and the script (None:
not `-P`)."""
if "-P" not in argv[1:]:
return definitions(argv), None
at = argv.index("-P", 1)
return definitions(argv[:at]), argv[at + 1] if at + 1 < len(argv) else None


def _scripts_run(command: Command, context: Context) -> list[Expansion] | None:
Expand Down
30 changes: 30 additions & 0 deletions project_validator/build_systems/cmake/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,35 @@ def cmake_build_types(command: Command) -> frozenset[str]:
return build_type_kinds(*defined, *option_values(argv, "--config"))


def definitions(argv: tuple[str, ...]) -> dict[str, str]:
"""The variables a cmake command defines (`-D name[:type]=value`, or `-D` then `name=value`), by name."""
found: dict[str, str] = {}
words = iter(argv[1:])
for word in words:
if word.startswith("-D"):
name, _, value = (word[2:] or next(words, "")).partition("=")
found[name.partition(":")[0]] = value
return found


def cmake_compiler_evidence(argv: tuple[str, ...]) -> tuple[str, ...]:
"""The words of a cmake command that show the compiler it builds with. Its generator picks the compiler unless
the command names one (MinGW Makefiles builds with gcc, Visual Studio with MSVC); where it names one, by a
compiler variable (`-DCMAKE_CXX_COMPILER=icx`) or a toolset (`-T ClangCL`), the generator shows nothing:
llama.cpp's MinGW Makefiles build is Intel's `icx`."""
names = any(name.endswith("_COMPILER") for name in definitions(argv)) or option_values(argv, "-T", "--toolset")
if program(argv) != "cmake" or not names:
return argv
shown: list[str] = []
words = iter(argv)
for word in words:
if word == "-G":
next(words, None) # `-G "MinGW Makefiles"`
elif not word.startswith("-G"): # `-GNinja`
shown.append(word)
return tuple(shown)


def cmake_configures(argv: tuple[str, ...]) -> bool:
"""Whether a cmake command configures a build tree, and so reads the CMake files."""
excluded = ("--build", "--install", "-E", "-P", "--open", "--help", "--version")
Expand Down Expand Up @@ -99,6 +128,7 @@ def cmake_declared_languages(path: str, text: str) -> frozenset[str]:
declared_languages=cmake_declared_languages,
is_build_tree=is_cmake_build_tree,
build_types=cmake_build_types,
compiler_evidence=cmake_compiler_evidence,
)


Expand Down
2 changes: 2 additions & 0 deletions project_validator/build_systems/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ class BuildSystem:
`configured_build_types` those its build files decide.
`members` reads, from a build file, the directories (globs relative to it) of the workspace it declares; each
member is a unit of the project of its own (see `project_validator.facts.structure.Unit`).
`compiler_evidence` gives the words of one of its commands that show the compiler it builds with.
"""

name: str
Expand All @@ -38,6 +39,7 @@ class BuildSystem:
# given a reader of the project's files (None for a file it does not have).
configured_build_types: Callable[[Command, Callable[[str], str | None]], frozenset[str]] | None = None
members: Callable[[str], tuple[str, ...]] | None = None
compiler_evidence: Callable[[tuple[str, ...]], tuple[str, ...]] | None = None


__all__ = ["C_FAMILY", "BuildSystem"]
52 changes: 50 additions & 2 deletions project_validator/ci/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,10 +157,18 @@ def _evidence(job: CiJob, facts: Iterable[Command | ActionStep]) -> str:
lines += [f"{name}: {value}" for name, value in fact.inputs.items() if _enables(value)]
else:
assignments = (f"{name}={value}" for name, value in fact.env.items() if job.env.get(name) != value)
lines.append(" ".join((*assignments, *resolved(fact))))
lines.append(" ".join((*assignments, *_compiler_evidence(resolved(fact)))))
return "\n".join(lines)


def _compiler_evidence(argv: tuple[str, ...]) -> tuple[str, ...]:
"""The words of a command that show the compiler it builds with, as each build system reads its own commands."""
for system in build_systems():
if system.compiler_evidence is not None:
argv = system.compiler_evidence(argv)
return argv


def _configurations(commands: Iterable[Command], evidence: str, project: Project) -> set[BuildConfiguration]:
"""The build configurations a job's commands build, as each build system reads its own commands (and, where its
build files decide, those)."""
Expand Down Expand Up @@ -301,10 +309,50 @@ def strings(value: object) -> dict[str, str]:
_CONFIGURATION_LINE = re.compile(r"^\s*(?:-\s+)?(?:[\w.-]+:\s*)?(?P<value>.*?)\s*$")


# A key that configures where a job runs, in some provider's words (`vmImage`, `image`, `os`, `platform`, `agent`,
# `label`, `machine`, `executor`, `resource_class`, `pool`, `queue`, `runs-on`, CircleCI's `macos`, Cirrus's
# `windows_container`), at the start of a line: `key:` or `key =` (YAML, a Jenkinsfile's environment), or a
# Jenkinsfile's `agent { label '…' }` and `node('…')`.
_RUNNER_KEY = re.compile(
r"^\s*(?:-\s*)?(?:[\w.-]*?(?:image|os|platform|agents?|labels?|machine|executor|resource_class|pool|queue|"
r"runs-on|node|dist|instance|container|vm|macos|osx|windows|linux|freebsd)[\w.-]*\s*[:=]|agent\b|node\s*\()",
re.IGNORECASE,
)


def _runner_lines(text: str) -> str:
"""The lines of a configuration not parsed that configure where its jobs run (see `_RUNNER_KEY`): an OS a
description, a comment or a command names (docker-code-server's image label: "… on your Mac, Windows") names no
runner, nor a comment after a key's value (`image: vs2022 # ported from linux`). A key whose value is on the
lines under it holds those lines too: indented (`os:`, then ` - linux`), a sequence at the key's own indentation
(`image:`, then `- Visual Studio 2017`), or after an anchor (`build-image: &image`, then the image)."""
found: list[str] = []
under: int | None = None # the indentation of the runner key whose value is the lines under it
for line in text.splitlines():
line = _TRAILING_COMMENT.sub("", line)
indent = len(line) - len(line.lstrip())
if under is not None and line.strip() and (indent > under or (indent == under and line.lstrip()[:2] == "- ")):
found.append(line)
continue
under = None
if (key := _RUNNER_KEY.match(line)) is not None:
found.append(line)
under = indent if _VALUE_BELOW.fullmatch(line[key.end() :]) else None
return "\n".join(found)


# A key's value that is on the lines below it: none, or only an anchor (`&image`).
_VALUE_BELOW = re.compile(r"\s*(?:&\S+\s*)?")


# A comment after what a line says: YAML's ` # …`, Groovy's ` // …`.
_TRAILING_COMMENT = re.compile(r"\s(?:#|//).*$")


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."""
origin = Origin(path=ci_file.path)
operating_systems = detect_operating_systems(text) or ["unknown"]
operating_systems = detect_operating_systems(_runner_lines(text)) or ["unknown"]
lines = (match["value"].strip("'\"") for line in text.splitlines() if (match := _CONFIGURATION_LINE.match(line)))
script = "\n".join(line for line in lines if line and line not in ("|", ">", "|-", ">-"))
for os in operating_systems:
Expand Down
3 changes: 2 additions & 1 deletion project_validator/platforms.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@
r"|\bemsdk\b|\bemcmake\b|\bemcc\b|(?<![\w-])em\+\+",
),
pattern("appleclang", r"\bapple-?clang\b"),
pattern("msvc", r"\bmsvc|visual studio|\bvs20\d\d\b|\bcl\.exe\b|\bvcvars"),
# MSVC's compiler is `cl` where a build names its compiler (`-DCMAKE_C_COMPILER=cl`, `CC=cl`).
pattern("msvc", r"\bmsvc|visual studio|\bvs20\d\d\b|\bcl\.exe\b|\bvcvars|(?:_COMPILER|\bCC|\bCXX)(?::\w+)?=cl\b"),
# fortran-lang/setup-fortran names Intel's compilers `intel` and `intel-classic`.
pattern("intel", r"\bicp?x\b|\bicp?c\b|\bifx\b|\bifort\b|intel-oneapi|\bcompiler\W+intel\b"),
pattern("flang", r"\b(?:llvm-)?flang(?:-new)?\b"),
Expand Down
38 changes: 37 additions & 1 deletion tests/test_ci.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from project_validator.ci import CiAnalysis, _matrix_text, find_ci_files
from project_validator.core import Project
from project_validator.plugins import discover
from tests.support import CI_FILES, PROJECT_LAYOUTS, ci_jobs, layout_project, make_context, temp_project
from tests.support import CI_FILES, PROJECT_LAYOUTS, ci_jobs, github_job, layout_project, make_context, temp_project


class FindCiFilesTests(unittest.TestCase):
Expand Down Expand Up @@ -48,6 +48,27 @@ def test_one_job_per_operating_system(self) -> None:
self.assertEqual([job.os for job in jobs], ["linux", "windows"])
self.assertTrue(all(job.compilers == {"gcc", "clang"} and job.heuristic for job in jobs))

def test_the_operating_systems_are_those_the_runners_are_configured_with(self) -> None:
"""A description, a comment or a command that names an OS (docker-code-server's image label: "VS Code … on
your Mac, Windows") names no runner; the keys that configure one do, whatever the provider calls them."""
for path, text, expected in (
(
"Jenkinsfile",
"environment {\n DIST_IMAGE = 'ubuntu'\n}\nsh 'docker build --label \"desc=on Windows\"'\n",
["linux"],
),
("azure-pipelines.yml", "pool:\n vmImage: 'windows-latest'\nsteps:\n- script: echo linux\n", ["windows"]),
(".circleci/config.yml", "jobs:\n b:\n macos:\n xcode: 15.0\n steps: [run: make]\n", ["macos"]),
("appveyor.yml", "image: Visual Studio 2022 # ported from linux\n# os: linux\n", ["windows"]),
("Jenkinsfile", "pipeline {\n agent { label 'windows' }\n}\n", ["windows"]),
(".travis.yml", "matrix:\n include:\n - os: osx\n - os: linux\n", ["macos", "linux"]),
# A sequence written at its key's indentation (scalafmt's AppVeyor), and an image behind an anchor (envoy).
("appveyor.yml", "image:\n- Visual Studio 2017\nbuild: off\n", ["windows"]),
(".circleci/config.yml", "build-image: &image\n envoyproxy/build-ubuntu:f4a8\njobs: {}\n", ["linux"]),
):
with self.subTest(path=path, text=text.splitlines()[0]):
self.assertEqual(sorted(job.os for job in ci_jobs({path: text})), sorted(expected))

def test_runner_default_when_no_compiler_is_named(self) -> None:
[job] = ci_jobs({".travis.yml": "os: osx\n"})
self.assertEqual((job.compilers, job.default_compiler), (frozenset({"appleclang"}), True))
Expand All @@ -63,6 +84,21 @@ def test_build_types_come_from_the_lines_that_could_be_commands(self) -> None:
self.assertEqual({configuration.build_type for configuration in job.configurations}, {"debug", "release"})


class CompilerTests(unittest.TestCase):
def test_a_cmake_generator_names_the_compiler_only_when_the_command_names_none(self) -> None:
"""MinGW Makefiles builds with gcc and Visual Studio with MSVC by default; llama.cpp's SYCL build names its
compilers (`cl` and Intel's `icx`) with the MinGW Makefiles generator, and a `-T ClangCL` toolset is clang."""
for line, expected in (
('cmake -G "MinGW Makefiles" -DCMAKE_C_COMPILER=cl -DCMAKE_CXX_COMPILER=icx ..', {"msvc", "intel"}),
('cmake -G "MinGW Makefiles" ..', {"gcc"}),
('cmake -G "Visual Studio 17 2022" -T ClangCL ..', {"clang"}),
("cmake -GNinja -DCMAKE_CXX_COMPILER:FILEPATH=icpx ..", {"intel"}),
):
with self.subTest(line=line):
[job] = ci_jobs(github_job("windows-latest", line))
self.assertEqual(set(job.compilers), expected)


WORKFLOW = {".github/workflows/ci.yml": "jobs:\n a:\n runs-on: ubuntu-latest\n steps: []\n"}


Expand Down
Loading