diff --git a/.pre-commit-hooks.yaml b/.pre-commit-hooks.yaml index 66955d0..f0cf023 100644 --- a/.pre-commit-hooks.yaml +++ b/.pre-commit-hooks.yaml @@ -5,6 +5,22 @@ language: python types: [text] +- id: check-pixi-lock + name: check Pixi lock package sources + description: check locked Conda and PyPI sources against Pixi workspace features + entry: check_pixi_lock + language: python + pass_filenames: false + files: ^(pixi\.toml|pixi\.lock|\.pre-commit-config\.yaml|prek\.toml)$ + +- id: check-recipe + name: check recipe constraints + description: check recipe security constraints and optional PyTorch backend policy + entry: check_recipe + language: python + pass_filenames: false + files: ^(recipe\.yaml|pixi\.toml|pyproject\.toml|\.pre-commit-config\.yaml|prek\.toml)$ + - id: prepare-commit-msg name: prepare commit message description: add the JIRA ID found in the branch name in case it is missing from the commit message diff --git a/README.md b/README.md new file mode 100644 index 0000000..9c1d794 --- /dev/null +++ b/README.md @@ -0,0 +1,135 @@ +# MiraGeoscience.Pre-Commit Hooks + +This repository provides a collection of pre-commit hooks to automate essential +checks and streamline your development workflow. By utilizing these hooks, you +can maintain code quality and consistency across your projects, fostering a more +efficient and collaborative development environment. + +## Included Hooks + +### `check-copyright` +Checks for valid copyright statements in files. + +### `check-pixi-lock` +Checks locked Conda and PyPI sources against Pixi workspace features. +`--strict-pypi` requires the lock to contain exactly the packages declared by +the selected PyPI features; otherwise transitive PyPI dependencies are allowed +while the feature packages are still checked. + +By default, this hook reads `pixi.toml` and `pixi.lock` from the repository root. +Use `--pypi-feature` for each feature that declares packages under +`[feature..pypi-dependencies]`; the default is `mira-pypi`. Repeat the +option when PyPI dependencies are split across features, for example +`--pypi-feature=mira-pypi --pypi-feature=vendor-pypi`. + +Repeat the optional `--conda-feature` for each feature whose packages under +`[feature..dependencies]` must stay Conda-sourced, for example +`--conda-feature=conda-base --conda-feature=conda-runtime`. This enables a +source-separation check: in environments where the selected features are +enabled, those packages must be present in the Conda lock and not the PyPI +lock, while packages from the selected PyPI features must be present in the +PyPI lock and not the Conda lock. Do not select the same package in both +categories; this check rejects that overlap, even though Pixi itself resolves +such a conflict in favour of Conda. If omitted, the hook does not check the +source of feature-declared Conda dependencies. + +By default, the hook checks expected package membership and Conda-versus-PyPI +lock placement, but does not validate PyPI index URLs or package download +origins. Enable `--validate-pypi-sources` for those checks. The repeatable +`--artifact-source-root` option is only used with this flag to permit download +locations outside an index's URL. For example, if a locked wheel is downloaded from +`https://artifacts.example.com/python-wheels/package-1.0.whl`, allow that artifact +location with: + +```yaml +args: + - --validate-pypi-sources + - --artifact-source-root=https://artifacts.example.com/python-wheels +``` + +The root is the allowed artifact URL prefix, not the PyPI index URL; repeat the option +for additional artifact locations. + +PyPI's standard artifact host is allowed automatically. +If index configuration lives in a separate feature, `--pypi-index-feature` selects that +feature's `pypi-options`; the feature must be enabled in the environment to apply its +indexes. Otherwise, workspace-level options or the default PyPI index are used. Git +sources from `git+https://github.com/MiraGeoscience/` are allowed by default; repeat +`--git-url-prefix` to configure allowed Git URL prefixes. + +### `check-recipe` +Checks recipe `run_constraints` against Pixi constraints, discovers matching +feature constraints from `pixi.toml`, verifies constrained packages are not +also direct dependencies in recipe `run`, and optionally checks that the recipe +leaves PyTorch backend selection to the installer. + +By default, this hook reads `recipe.yaml` and `pixi.toml` from the repository root. + +Dependency consistency is checked by `pip check` during recipe builds; this hook +focuses on ensuring recipe and Pixi constraints agree. + +Conditional `run_constraints` are not supported by the recipe validation; use +unconditional constraints or pass `--ignore-constraints` to skip this specific +constraint comparison. + +Recipe security floors and their Pixi source are inferred from `recipe.yaml` and +`pixi.toml`. + +Only enable the optional PyTorch check with `--check-pytorch` when required. + +**Known limitation:** both branches of conditional runtime dependencies are checked, +which can reject recipes whose constraints apply to a different platform. + +### `prepare-commit-msg` +Adds the JIRA ID found in the branch name in case it is missing from the commit message. + +### `check-commit-message` +Checks that the branch name or the commit message starts with a reference to JIRA, +and if the message meets the minimum required length for the summary line. Also checks +that the JIRA ID in the commit message is consistent with the one extracted from the +branch name (if any). + +## Usage + +Example of `.pre-commit-config.yamnl`: + +```yaml +repos: +- repo: http://github.com/MiraGeoscience/pre-commit-hooks + rev: + hooks: + - id: check-copyright + types: [text] + files: (^LICENSE|^README(|-dev).rst|\.py|\.pyi)$ + exclude: (^\.|^docs/) + - id: check-pixi-lock + args: [--pypi-feature=mira-pypi, --strict-pypi] + - id: check-recipe + args: [--check-pytorch] + - id: prepare-commit-msg + - id: check-commit-msg +``` + +## License + +MIT License + +Copyright (c) 2024-2026 Mira Geoscience Ltd. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.rst b/README.rst deleted file mode 100644 index 5a323f2..0000000 --- a/README.rst +++ /dev/null @@ -1,67 +0,0 @@ -MiraGeoscience.Pre-Commit Hooks -=============================== - -This repository provides a collection of pre-commit hooks to automate -essential checks and streamline your development workflow. By utilizing -these hooks, you can maintain code quality and consistency across your -projects, fostering a more efficient and collaborative development -environment. - -Included Hooks -^^^^^^^^^^^^^^ - -- ``check-copyright``: Checks for valid copyright statements in files. -- ``prepare-commit-msg``: Adds the JIRA ID found in the branch name - in case it is missing from the commit message. -- ``check-commit-message``: Checks that the branch name or the commit - message starts with a reference to JIRA, and if the message meets the - minimum required length for the summary line. Also checks that the JIRA ID in - the commit message is consistEnt with the one extracted from the - branch name (if any). - -Usage -^^^^^ - -Example of ``.pre-commit-config.yamnl``: - -.. code:: yaml - - repos: - - repo: http://github.com/MiraGeoscience/pre-commit-hooks - rev: - hooks: - - id: check-copyright - types: [text] - files: (^LICENSE|^README(|-dev).rst|\.py|\.pyi)$ - exclude: (^\.|^docs/) - - id: prepare-commit-msg - - id: check-commit-msg - -License -^^^^^^^ - -MIT License - -Copyright (c) 2024-2026 Mira Geoscience Ltd. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - -Copyright -^^^^^^^^^ -Copyright (c) 2024-2026 Mira Geoscience Ltd. diff --git a/mirageoscience/hooks/_cli_utils.py b/mirageoscience/hooks/_cli_utils.py new file mode 100644 index 0000000..8ab5790 --- /dev/null +++ b/mirageoscience/hooks/_cli_utils.py @@ -0,0 +1,51 @@ +# ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Copyright (c) 2024-2026 Mira Geoscience Ltd. ' +# ' +# This file is part of mirageoscience.pre-commit-hooks package. ' +# ' +# mirageoscience.pre-commit-hooks is distributed under the terms and conditions ' +# of the MIT License (see LICENSE file at the root of this source code package). ' +# ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' + +from __future__ import annotations + +import sys +from collections.abc import Iterator +from contextlib import contextmanager + +import tomlkit +import yaml + + +def print_invalid_configuration(kind: str, error: Exception) -> None: + """Print a consistent CLI error for invalid hook configuration.""" + print(f"Invalid {kind} configuration: {error}", file=sys.stderr) + + +def report_validation_result(errors: list[str] | None, success_message: str) -> int: + """Report manifest validation results and return the CLI status.""" + if errors is None: + # Manifest parsing/validation raised an expected error inside manifest_error. + return 1 + if errors: + print("\n".join(errors), file=sys.stderr) + return 1 + print(success_message) + return 0 + + +@contextmanager +def manifest_error(kind: str) -> Iterator[list[Exception]]: + """Report expected errors while parsing or validating a manifest.""" + errors: list[Exception] = [] + try: + yield errors + except ( + ValueError, + KeyError, + TypeError, + tomlkit.exceptions.ParseError, + yaml.YAMLError, + ) as error: + errors.append(error) + print_invalid_configuration(kind, error) diff --git a/mirageoscience/hooks/check_pixi_lock.py b/mirageoscience/hooks/check_pixi_lock.py new file mode 100644 index 0000000..d72a116 --- /dev/null +++ b/mirageoscience/hooks/check_pixi_lock.py @@ -0,0 +1,461 @@ +# ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Copyright (c) 2024-2026 Mira Geoscience Ltd. ' +# ' +# This file is part of mirageoscience.pre-commit-hooks package. ' +# ' +# mirageoscience.pre-commit-hooks is distributed under the terms and conditions ' +# of the MIT License (see LICENSE file at the root of this source code package). ' +# ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' + +from __future__ import annotations + +import argparse +import re +from dataclasses import dataclass +from pathlib import Path +from urllib.parse import unquote, urlsplit + +import tomlkit +import yaml +from packaging.utils import canonicalize_name + +from mirageoscience.hooks._cli_utils import manifest_error, report_validation_result + + +DEFAULT_GIT_URL_PREFIXES = ("git+https://github.com/MiraGeoscience/",) +PYPI_INDEX = "https://pypi.org/simple" + + +@dataclass(frozen=True) +class LockOptions: + pypi_feature: str | tuple[str, ...] + conda_feature: str | tuple[str, ...] | None = None + strict_pypi: bool = False + pypi_index_feature: str | None = None + validate_pypi_sources: bool = False + git_url_prefixes: tuple[str, ...] = DEFAULT_GIT_URL_PREFIXES + artifact_source_roots: tuple[str, ...] = () + + +@dataclass(frozen=True) +class LockExpectations: + pypi_packages: set[str] + conda_packages: set[str] + index_urls: set[str] + source_roots: set[str] + + +@dataclass(frozen=True) +class LockContext: + options: LockOptions + expectations: LockExpectations + packages_by_url: dict[str, str] + + +def _feature_dependencies( + pixi: dict, feature_name: str, dependency_type: str, platform: str +) -> set[str]: + """Resolve feature dependencies, including matching platform-target overrides.""" + try: + feature = pixi["feature"][feature_name] + except KeyError as error: + raise ValueError(f"Pixi feature {feature_name!r} is not defined") from error + targets = feature.get("target", {}) + if dependency_type not in feature and not any( + dependency_type in target for target in targets.values() + ): + raise ValueError( + f"Pixi feature {feature_name!r} has no {dependency_type!r} table" + ) + dependencies = dict(feature.get(dependency_type, {})) + subdir = platform + for candidate in pixi.get("workspace", {}).get("platforms", []): + if isinstance(candidate, dict) and candidate.get("name") == platform: + subdir = candidate.get("platform", platform) + break + family = subdir.split("-", 1)[0] + for selector, target in targets.items(): + pattern = re.escape(selector).replace(r"\*", ".*") + if ( + re.fullmatch(pattern, platform) + or selector == family + or (selector == "unix" and family in {"linux", "osx"}) + ): + dependencies.update(target.get(dependency_type, {})) + return {canonicalize_name(name) for name in dependencies} + + +def _pypi_features(options: LockOptions) -> tuple[str, ...]: + """Normalize configured PyPI features to a tuple.""" + if isinstance(options.pypi_feature, str): + return (options.pypi_feature,) + return options.pypi_feature + + +def _conda_features(options: LockOptions) -> tuple[str, ...]: + """Normalize configured Conda features to a tuple.""" + if options.conda_feature is None: + return () + if isinstance(options.conda_feature, str): + return (options.conda_feature,) + return options.conda_feature + + +def _environment_features(environment: object) -> set[str]: + """Normalize a Pixi environment definition to its feature-name set.""" + if isinstance(environment, dict): + features = environment.get("features", []) + else: + features = environment + if not isinstance(features, list): + raise ValueError(f"Invalid Pixi environment feature list: {features!r}") + return set(features) + + +def _locked_names( + entries: list[dict], packages_by_url: dict[str, str], source: str +) -> set[str]: + """Extract canonical package names from PyPI or Conda lock entries.""" + names = set() + for entry in entries: + url = entry.get(source) + if url is None: + continue + if source == "pypi": + name = packages_by_url.get(url) + if name is None: + raise ValueError(f"Pixi lock package URL is not defined: {url}") + else: + filename = unquote(urlsplit(url).path.rsplit("/", 1)[-1]) + for suffix in (".tar.bz2", ".conda"): + if filename.endswith(suffix): + filename = filename[: -len(suffix)] + break + package_parts = filename.rsplit("-", 2) + if len(package_parts) != 3: + raise ValueError(f"Cannot determine Conda package name from {url}") + name = package_parts[0] + names.add(canonicalize_name(name)) + return names + + +def _pypi_options(pixi: dict, feature_name: str | None) -> dict: + """Merge PyPI options in top-level, workspace, then feature precedence.""" + options = dict(pixi.get("pypi-options", {})) + options.update(pixi.get("workspace", {}).get("pypi-options", {})) + if feature_name is not None: + options.update( + pixi.get("feature", {}).get(feature_name, {}).get("pypi-options", {}) + ) + return options + + +def _index_urls(pixi: dict, feature_name: str | None) -> set[str]: + """Return configured PyPI index URLs without trailing slashes.""" + options = _pypi_options(pixi, feature_name) + urls = set() + if url := options.get("index-url"): + urls.add(url.rstrip("/")) + urls.update(url.rstrip("/") for url in options.get("extra-index-urls", [])) + return urls + + +def _expectations( + pixi: dict, options: LockOptions, platform: str, features: set[str] +) -> LockExpectations: + """Build platform-specific package and artifact-source expectations.""" + pypi_features = _pypi_features(options) + pypi_packages = set() + for feature_name in pypi_features: + feature_packages = _feature_dependencies( + pixi, feature_name, "pypi-dependencies", platform + ) + if feature_name in features: + pypi_packages.update(feature_packages) + conda_packages = set() + for feature_name in _conda_features(options): + feature_packages = _feature_dependencies( + pixi, feature_name, "dependencies", platform + ) + if feature_name in features: + conda_packages.update(feature_packages) + index_features = ( + ( + (options.pypi_index_feature,) + if options.pypi_index_feature in features + else () + ) + if options.pypi_index_feature + else tuple( + feature_name for feature_name in pypi_features if feature_name in features + ) + ) + index_urls = set() + if options.validate_pypi_sources: + if index_features: + for feature_name in index_features: + index_urls.update(_index_urls(pixi, feature_name)) + else: + index_urls = _index_urls(pixi, None) + source_indexes = set(index_urls) + has_default_index = ( + not index_features and not _pypi_options(pixi, None).get("index-url") + ) or any( + not _pypi_options(pixi, feature_name).get("index-url") + for feature_name in index_features + ) + if options.validate_pypi_sources and has_default_index: + source_indexes.add(PYPI_INDEX) + source_roots = { + f"{url.removesuffix('/simple').rstrip('/')}/" for url in source_indexes + } + if PYPI_INDEX in source_indexes: + source_roots.add("https://files.pythonhosted.org/") + source_roots.update( + f"{root.rstrip('/')}/" for root in options.artifact_source_roots + ) + return LockExpectations(pypi_packages, conda_packages, index_urls, source_roots) + + +def _allowed_git_source(url: str, prefixes: tuple[str, ...]) -> bool: + """Check an allowed Git URL prefix and reject unsafe path segments.""" + if any(ord(char) < 32 or ord(char) == 127 for char in url): + return False + try: + parsed = urlsplit(url) + path = parsed.path + while True: + decoded = unquote(path) + if decoded == path: + break + if decoded.count("/") != path.count("/"): + return False + path = decoded + if ( + "\\" in path + or any(ord(char) < 32 or ord(char) == 127 for char in path) + or any(segment in {".", ".."} for segment in path.split("/")) + ): + return False + return any( + url.startswith(prefix) + and parsed.scheme == urlsplit(prefix).scheme + and parsed.netloc == urlsplit(prefix).netloc + for prefix in prefixes + ) + except ValueError: + return False + + +def _source_errors( + label: str, + entries: list[dict], + environment_lock: dict, + pypi_feature_enabled: bool, + context: LockContext, +) -> list[str]: + """Report missing indexes and PyPI or Git sources outside allowed roots.""" + options = context.options + expectations = context.expectations + if not options.validate_pypi_sources or not pypi_feature_enabled: + return [] + + errors = [] + missing_indexes = expectations.index_urls - set(environment_lock.get("indexes", [])) + if missing_indexes: + errors.append( + f"{label}: missing configured PyPI indexes {sorted(missing_indexes)}" + ) + for entry in entries: + url = entry.get("pypi") + if url is None: + continue + if url.startswith("git+"): + if not _allowed_git_source(url, options.git_url_prefixes): + errors.append(f"{label}: unexpected Git source {url}") + elif not any(url.startswith(root) for root in expectations.source_roots): + errors.append(f"{label}: unexpected PyPI source {url}") + return errors + + +def _pypi_errors( + label: str, + entries: list[dict], + environment_lock: dict, + features: set[str], + context: LockContext, +) -> list[str]: + """Check locked PyPI packages, using exact or minimum membership policy.""" + options = context.options + expectations = context.expectations + pypi_features = _pypi_features(options) + pypi_feature_enabled = any(feature in features for feature in pypi_features) + pypi_names = _locked_names(entries, context.packages_by_url, "pypi") + expected_pypi = expectations.pypi_packages + errors = [] + if options.strict_pypi: + if pypi_names != expected_pypi: + errors.append( + f"{label}: expected exactly PyPI packages {sorted(expected_pypi)}, " + f"found {sorted(pypi_names)}" + ) + else: + missing_pypi = expected_pypi - pypi_names + if missing_pypi: + errors.append(f"{label}: missing PyPI packages {sorted(missing_pypi)}") + if not pypi_feature_enabled and pypi_names: + feature_label = ( + f"the {pypi_features[0]!r} feature" + if len(pypi_features) == 1 + else f"any of the {pypi_features!r} features" + ) + errors.append( + f"{label}: PyPI packages are locked without {feature_label}: " + f"{sorted(pypi_names)}" + ) + errors.extend( + _source_errors(label, entries, environment_lock, pypi_feature_enabled, context) + ) + return errors + + +def _conda_errors( + label: str, + pypi_names: set[str], + conda_names: set[str], + context: LockContext, +) -> list[str]: + """Check expected packages are locked from their configured package source.""" + expected_conda = context.expectations.conda_packages + expected_pypi = context.expectations.pypi_packages + errors = [] + missing_conda = expected_conda - conda_names + if missing_conda: + errors.append(f"{label}: missing Conda packages {sorted(missing_conda)}") + wrong_pypi_source = expected_conda & pypi_names + if wrong_pypi_source: + errors.append( + f"{label}: Conda feature packages locked from PyPI " + f"{sorted(wrong_pypi_source)}" + ) + wrong_conda_source = expected_pypi & conda_names + if wrong_conda_source: + errors.append( + f"{label}: PyPI feature packages locked from Conda " + f"{sorted(wrong_conda_source)}" + ) + return errors + + +def _validate_platform( + label: str, + entries: list[dict], + environment_lock: dict, + features: set[str], + context: LockContext, +) -> list[str]: + """Validate locked package names and sources for one platform.""" + pypi_names = _locked_names(entries, context.packages_by_url, "pypi") + conda_names = _locked_names(entries, context.packages_by_url, "conda") + return _pypi_errors( + label, entries, environment_lock, features, context + ) + _conda_errors(label, pypi_names, conda_names, context) + + +def _validate_environment( + pixi: dict, + environment_name: str, + environment_lock: dict, + options: LockOptions, + packages_by_url: dict[str, str], +) -> list[str]: + """Validate every locked platform for one Pixi environment.""" + environment_config = pixi.get("environments", {}).get(environment_name) + if environment_config is None: + if environment_name != "default": + return [f"{environment_name}: missing Pixi environment definition"] + environment_config = [] + features = _environment_features(environment_config) + errors = [] + for platform, entries in environment_lock["packages"].items(): + label = f"{environment_name}/{platform}" + platform_context = LockContext( + options, _expectations(pixi, options, platform, features), packages_by_url + ) + errors.extend( + _validate_platform( + label, + entries, + environment_lock, + features, + platform_context, + ) + ) + return errors + + +def validate_lock(pixi: dict, lock: dict, options: LockOptions) -> list[str]: + """Validate all lock environments against the Pixi feature configuration.""" + packages_by_url = { + package["pypi"]: package["name"] + for package in lock["packages"] + if "pypi" in package + } + errors = [] + for environment_name, environment_lock in lock["environments"].items(): + errors.extend( + _validate_environment( + pixi, + environment_name, + environment_lock, + options, + packages_by_url, + ) + ) + return errors + + +def main() -> int: + """Load CLI inputs, validate the lock, and return the process status.""" + parser = argparse.ArgumentParser() + parser.add_argument("--pixi-file", type=Path, default=Path("pixi.toml")) + parser.add_argument("--lock-file", type=Path, default=Path("pixi.lock")) + parser.add_argument("--pypi-feature", action="append") + parser.add_argument("--conda-feature", action="append") + parser.add_argument("--strict-pypi", action="store_true") + parser.add_argument("--pypi-index-feature") + parser.add_argument("--validate-pypi-sources", action="store_true") + parser.add_argument("--git-url-prefix", action="append") + parser.add_argument("--artifact-source-root", action="append", default=[]) + args = parser.parse_args() + + errors: list[str] | None = None + with manifest_error("Pixi lock"): + with args.pixi_file.open("rb") as file: + pixi = tomlkit.load(file).unwrap() + with args.lock_file.open(encoding="utf-8") as file: + lock = yaml.safe_load(file) + errors = validate_lock( + pixi, + lock, + LockOptions( + pypi_feature=tuple(args.pypi_feature or ["mira-pypi"]), + conda_feature=tuple(args.conda_feature or []), + strict_pypi=args.strict_pypi, + pypi_index_feature=args.pypi_index_feature, + validate_pypi_sources=args.validate_pypi_sources, + artifact_source_roots=tuple(args.artifact_source_root), + git_url_prefixes=( + tuple(args.git_url_prefix) + if args.git_url_prefix is not None + else DEFAULT_GIT_URL_PREFIXES + ), + ), + ) + return report_validation_result( + errors, "Pixi lock package sources match the configured features." + ) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/mirageoscience/hooks/check_recipe.py b/mirageoscience/hooks/check_recipe.py new file mode 100644 index 0000000..50b1420 --- /dev/null +++ b/mirageoscience/hooks/check_recipe.py @@ -0,0 +1,335 @@ +# ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Copyright (c) 2024-2026 Mira Geoscience Ltd. ' +# ' +# This file is part of mirageoscience.pre-commit-hooks package. ' +# ' +# mirageoscience.pre-commit-hooks is distributed under the terms and conditions ' +# of the MIT License (see LICENSE file at the root of this source code package). ' +# ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' + +"""Validate conda recipe constraints against the Pixi workspace. + +**Known limitation:** both branches of conditional runtime dependencies are checked, +which can reject recipes whose constraints apply to a different platform. + +Conditional ``run_constraints`` entries are not supported by the Conda recipe +comparison because they are flattened to a single effective constraint rather than +one unconditional value. Use unconditional constraints or pass +``--ignore-constraints`` to skip this specific comparison. +""" + +from __future__ import annotations + +import argparse +import re +from dataclasses import dataclass +from pathlib import Path + +import tomlkit +import yaml +from packaging.specifiers import SpecifierSet +from packaging.utils import canonicalize_name +from packaging.version import Version + +from mirageoscience.hooks._cli_utils import manifest_error, report_validation_result + + +@dataclass(frozen=True) +class RecipeOptions: + package_aliases: tuple[str, ...] = () + check_pytorch: bool = False + ignore_constraints: bool = False + + +def _parse_constraint(value: str) -> tuple[str, str]: + """Split a Conda requirement into its canonical package name and specifier.""" + match = re.match(r"^\s*([^\s<>=!~]+)\s*(.*?)\s*$", value) + if not match or not match.group(2): + raise ValueError(f"Invalid recipe run constraint: {value!r}") + name = match.group(1).rsplit("::", 1)[-1] + return canonicalize_name(name), match.group(2) + + +def _as_specifier_set(value: str) -> SpecifierSet: + """Convert Conda-style version syntax to a packaging specifier set.""" + if value in ("", "*"): + return SpecifierSet() + specifiers = [] + for specifier in value.split(","): + specifier = specifier.strip() + conda_equality = re.fullmatch(r"=(\d[0-9A-Za-z.!+_-]*)", specifier) + if conda_equality: + version = conda_equality.group(1) + specifier = f"=={version if version.endswith('.*') else f'{version}.*'}" + if not any(operator in specifier for operator in "<>=!~"): + specifier = f"=={specifier}" + specifiers.append(specifier) + return SpecifierSet(",".join(specifiers)) + + +def _requirement_strings(values: object): + """Yield unconditional requirement strings; reject conditional entries.""" + if values is None: + return + if isinstance(values, str): + yield values + return + if isinstance(values, list): + for value in values: + yield from _requirement_strings(value) + return + if isinstance(values, dict): + if "if" in values or "then" in values or "else" in values: + raise ValueError( + "Conditional run_constraints are not supported by check-recipe; " + "pass --ignore-constraints to skip this check for conditional " + "constraints, or use unconditional constraints." + ) + raise ValueError(f"Invalid recipe requirement entry: {values!r}") + raise ValueError(f"Invalid recipe requirement entry: {values!r}") + + +def _flatten_requirement_strings(values: object): + """Yield requirement strings, including both branches of conditional entries.""" + if values is None: + return + if isinstance(values, str): + yield values + return + if isinstance(values, list): + for value in values: + yield from _flatten_requirement_strings(value) + return + if isinstance(values, dict): + if any(key in values for key in ("if", "then", "else")): + for branch in ("then", "else"): + yield from _flatten_requirement_strings(values.get(branch)) + return + raise ValueError(f"Invalid recipe requirement entry: {values!r}") + raise ValueError(f"Invalid recipe requirement entry: {values!r}") + + +def _requirement_package(value: str) -> str: + """Return a canonical package name, ignoring any Conda channel prefix.""" + match = re.match(r"^(?:[^\s:]+::)?([a-zA-Z0-9_.-]+)", value.strip()) + if not match: + raise ValueError(f"Invalid recipe run requirement: {value!r}") + return canonicalize_name(match.group(1)) + + +def _package_aliases(values: tuple[str, ...]) -> dict[str, str]: + """Parse package alias mappings and canonicalize both sides.""" + aliases = {} + for value in values: + alias, separator, package = value.partition("=") + if not separator or not alias or not package: + raise ValueError(f"Invalid package alias {value!r}; expected alias=package") + aliases[canonicalize_name(alias)] = canonicalize_name(package) + return aliases + + +def _pixi_constraint_sources(pixi: dict, constrained_packages: set[str]) -> dict: + """Collect Pixi constraint and feature sources for recipe-constrained packages.""" + sources: dict[str, list[tuple[str, str]]] = {} + for package, specifier in pixi.get("constraints", {}).items(): + sources.setdefault(canonicalize_name(package), []).append( + (_pixi_version(specifier), "workspace constraint") + ) + + top_level_packages = set(sources) + for feature_name, feature in pixi.get("feature", {}).items(): + for section in ("dependencies", "pypi-dependencies", "constraints"): + for package, specifier in feature.get(section, {}).items(): + normalized = canonicalize_name(package) + if ( + normalized in constrained_packages + and normalized not in top_level_packages + ): + sources.setdefault(normalized, []).append( + ( + _pixi_version(specifier), + f"feature {feature_name!r} {section}", + ) + ) + return sources + + +def _pixi_version(specifier: object) -> str: + """Extract the version from a Pixi inline dependency table or scalar.""" + if isinstance(specifier, dict): + return str(specifier.get("version", "")) + return str(specifier) + + +def _minimum_version(specifier: str) -> Version | None: + """Return the strongest lower bound represented by a specifier.""" + versions = [] + for item in _as_specifier_set(specifier): + if item.operator in (">=", ">", "~="): + versions.append(Version(item.version)) + elif item.operator == "==": + versions.append(Version(item.version.removesuffix(".*"))) + return max(versions, default=None) + + +def _constraint_matches(recipe_specifier: str, pixi_specifier: str) -> bool: + """Match exact specifiers or lower bounds with the same effective floor.""" + recipe_set = _as_specifier_set(recipe_specifier) + pixi_set = _as_specifier_set(pixi_specifier) + if recipe_set == pixi_set: + return True + if any(item.operator not in (">=", ">") for item in recipe_set): + return False + recipe_floor = _minimum_version(recipe_specifier) + pixi_floor = _minimum_version(pixi_specifier) + return ( + recipe_floor is not None + and recipe_floor == pixi_floor + and recipe_floor in pixi_set + ) + + +def _constraint_errors( + recipe_constraints: dict[str, str], pixi_sources: dict[str, list[tuple[str, str]]] +) -> list[str]: + """Report package-set differences and incompatible Pixi constraint sources.""" + errors = [] + if recipe_constraints.keys() != pixi_sources.keys(): + errors.append( + "recipe.yaml run_constraints must match Pixi constraints; " + f"recipe={sorted(recipe_constraints)}, Pixi={sorted(pixi_sources)}" + ) + for package, recipe_specifier in recipe_constraints.items(): + sources = pixi_sources.get(package) + if not sources: + continue + for pixi_specifier, source in sources: + if _constraint_matches(recipe_specifier, pixi_specifier): + continue + errors.append( + f"{package}: recipe constraint {recipe_specifier!r} is not " + f"consistent with {source} {pixi_specifier!r}" + ) + return errors + + +def _recipe_transitivity_errors( + run_requirement_entries: object, + constrained_packages: set[str], + options: RecipeOptions, +) -> list[str]: + """Report constrained packages declared directly in the recipe's run section.""" + aliases = _package_aliases(options.package_aliases) + security_packages = { + aliases.get(package, package) for package in constrained_packages + } + dependencies = { + _requirement_package(value) + for value in _flatten_requirement_strings(run_requirement_entries) + } + dependencies = {aliases.get(package, package) for package in dependencies} + direct_dependencies = security_packages & dependencies + if not direct_dependencies: + return [] + return [ + "Security-floor packages must remain transitive in recipe requirements: " + f"{sorted(direct_dependencies)}" + ] + + +def _pytorch_errors(requirements: dict) -> list[str]: + """Report explicit PyTorch backend selection in run or run_constraints entries.""" + backend_specs = [] + for section in ("run", "run_constraints"): + for value in _flatten_requirement_strings(requirements.get(section, [])): + match = re.match(r"^(?:[^\s:]+::)?([a-zA-Z0-9_.-]+)(.*)$", value.strip()) + if not match: + continue + package = canonicalize_name(match.group(1)) + specifier = match.group(2) + if package in {"pytorch-cpu", "pytorch-gpu", "pytorch-cuda", "cpuonly"} or ( + package in {"pytorch", "pytorch-mutex"} + and re.search(r"cpu|cuda|gpu", specifier, re.IGNORECASE) + ): + backend_specs.append(f"{section}: {value}") + if not backend_specs: + return [] + return [ + "recipe.yaml requirements must leave PyTorch backend selection " + f"to the installer; found: {backend_specs}" + ] + + +def validate_recipe(pixi: dict, recipe: dict, options: RecipeOptions) -> list[str]: + """Validate recipe constraints, transitivity, and optional PyTorch policy.""" + errors = [] + if not isinstance(recipe, dict): + raise ValueError("recipe.yaml must contain a mapping") + requirements = recipe.get("requirements", {}) + if not isinstance(requirements, dict): + raise ValueError("recipe.yaml 'requirements' must be a mapping") + run_requirement_entries = requirements.get("run", []) + run_constraint_requirement_entries = requirements.get("run_constraints", []) + has_conditional_constraints = any( + isinstance(value, dict) and any(key in value for key in ("if", "then", "else")) + for value in run_constraint_requirement_entries + ) + if has_conditional_constraints and not options.ignore_constraints: + errors.append( + "Conditional run_constraints are not supported by check-recipe; " + "use unconditional constraints or exclude this validation. Pass " + "--ignore-constraints to skip this check for conditional constraints." + ) + + constrained_packages = { + _requirement_package(value) + for value in _flatten_requirement_strings(run_constraint_requirement_entries) + } + if not has_conditional_constraints: + recipe_constraints = dict( + _parse_constraint(value) + for value in _requirement_strings(run_constraint_requirement_entries) + ) + pixi_sources = _pixi_constraint_sources(pixi, set(recipe_constraints)) + errors.extend(_constraint_errors(recipe_constraints, pixi_sources)) + errors.extend( + _recipe_transitivity_errors( + run_requirement_entries, constrained_packages, options + ) + ) + if options.check_pytorch: + errors.extend(_pytorch_errors(requirements)) + return errors + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--pixi-file", type=Path, default=Path("pixi.toml")) + parser.add_argument("--recipe-file", type=Path, default=Path("recipe.yaml")) + parser.add_argument("--package-alias", action="append", default=[]) + parser.add_argument("--check-pytorch", action="store_true") + parser.add_argument("--ignore-constraints", action="store_true") + args = parser.parse_args() + + errors: list[str] | None = None + with manifest_error("recipe"): + with args.pixi_file.open("rb") as file: + pixi = tomlkit.load(file).unwrap() + with args.recipe_file.open(encoding="utf-8") as file: + recipe = yaml.safe_load(file) + errors = validate_recipe( + pixi, + recipe, + RecipeOptions( + package_aliases=tuple(args.package_alias), + check_pytorch=args.check_pytorch, + ignore_constraints=args.ignore_constraints, + ), + ) + return report_validation_result( + errors, "Recipe constraints match Pixi constraints and remain transitive." + ) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/poetry.lock b/poetry.lock index fc77b16..a9710f3 100644 --- a/poetry.lock +++ b/poetry.lock @@ -265,7 +265,7 @@ version = "26.3" description = "Core utilities for Python packages" optional = false python-versions = ">=3.9" -groups = ["dev"] +groups = ["main", "dev"] files = [ {file = "packaging-26.3-py3-none-any.whl", hash = "sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c"}, {file = "packaging-26.3.tar.gz", hash = "sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79"}, @@ -396,78 +396,88 @@ pytest = ">=6.2.5" dev = ["pre-commit", "pytest-asyncio", "tox"] [[package]] -name = "tomli" -version = "2.5.0" -description = "A lil' TOML parser" +name = "pyyaml" +version = "6.0.4" +description = "YAML parser and emitter for Python" optional = false -python-versions = ">=3.8" -groups = ["dev"] +python-versions = ">=3.10" +groups = ["main"] files = [ - {file = "tomli-2.5.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:c4dc1c1781f2f716de763d1e9a7b34c6a894e167e291c7c5d16c72f7a9538545"}, - {file = "tomli-2.5.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:eff8babca5a7999bc137acbc7482a8b7e17ffca5075ab41f5d770ab408c7bfef"}, - {file = "tomli-2.5.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:86665cee9c4835b7a7f1e8ec2c719b5258d4dc782887aded5a8ae7352a96843b"}, - {file = "tomli-2.5.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d7e369fd63331746182360977b1892bfc215476a30d61612d732425311639f56"}, - {file = "tomli-2.5.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:7ad1ea345759240d6463efa0ed1c704402752e49aa21476620738d74d72d8aa1"}, - {file = "tomli-2.5.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:96243987194634bd411066ce40c952e108f86af04db533ecd8ac3ff2a85b1885"}, - {file = "tomli-2.5.0-cp311-cp311-win32.whl", hash = "sha256:610b27d99f28ec5f191c7064a48f3ddb179a1fe6ca73d571483ae859f57b605e"}, - {file = "tomli-2.5.0-cp311-cp311-win_amd64.whl", hash = "sha256:c804ae44fe7b4bab5da295e4f980a1ff04670bca9d23fe0a4e887e08ebd741a8"}, - {file = "tomli-2.5.0-cp311-cp311-win_arm64.whl", hash = "sha256:cfac177ebd6236003846ea339981f71457cb6eb748f23381eb257e45092e3980"}, - {file = "tomli-2.5.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:1f4a40d03fb9f63424f0979855bdeaf44dd7696b8d59501822c10ed30ba532df"}, - {file = "tomli-2.5.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:9ebf8d19b17bd0daeb7b7dec81a946a439b753942fd0210d6e96c532249eea6b"}, - {file = "tomli-2.5.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:bf0b5e8e0f68ebb494356e577c06c139161efd8d3b9050f93b39b7c26cc54ff0"}, - {file = "tomli-2.5.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6cf74416bdc94ae458b14e37286c1073081850ac8459a00d0c5efef5d44294c6"}, - {file = "tomli-2.5.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:61ea1ebe1e55a34ea8199cc8dbff398d35027b82271c8ac4802fd3a1fd5b1bcc"}, - {file = "tomli-2.5.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:ed53f7e89bb04f6d9e8e7799112360b0c4d5cbff067de0814c98c37c39b920f7"}, - {file = "tomli-2.5.0-cp312-cp312-win32.whl", hash = "sha256:e7ad033e27a516a233bea839cdb77b80146facb3b4f40bf02cd0cac165cdd5c2"}, - {file = "tomli-2.5.0-cp312-cp312-win_amd64.whl", hash = "sha256:bd05de8c1698f8413dd7d869492693a0bf2211543b787ac78cd5e7536af1a6d7"}, - {file = "tomli-2.5.0-cp312-cp312-win_arm64.whl", hash = "sha256:069435bd5480429b98c5e5afb02ab21c219b6f0064680671c6dc0d46817346ea"}, - {file = "tomli-2.5.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:943276cf269e0071948d9ff697159c1735e623c1151d88abb09b74659ef0cbea"}, - {file = "tomli-2.5.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:463b16086865b97facd8d0b3fb4cb7c544e3f58d2a69dc3113d6db9653fdb043"}, - {file = "tomli-2.5.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1245a6638fc4bb0a60af38a7d45413db34a13842027c77597c712c998c62fdf0"}, - {file = "tomli-2.5.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5d8bac3d603c97e6854424e5b2b5b741bdbde387e09f162fb0446812b4a8362b"}, - {file = "tomli-2.5.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:21e4cae4114aba25aa0d4f85cdf486d290fb35c0954d7bba536248da64d43066"}, - {file = "tomli-2.5.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:bbaefc84548d754be821bba7c4141c4787dda182f9e77f2f87b71213529efa7b"}, - {file = "tomli-2.5.0-cp313-cp313-win32.whl", hash = "sha256:abdbf6313b8d9efe157edeb7ab6eae4de064b1300ad31abf73755154b30abe68"}, - {file = "tomli-2.5.0-cp313-cp313-win_amd64.whl", hash = "sha256:fd4dc129784e0c5335bd4e61dfcc4487499a013419e655cf2da1d091b7e0efdc"}, - {file = "tomli-2.5.0-cp313-cp313-win_arm64.whl", hash = "sha256:69491c143d2fe063046e0301e62a810bed338fa4d1ce0fd870c27dc1e09b0d84"}, - {file = "tomli-2.5.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:d3182ee2d887e507bd67319a0a61105d1dd33facc111329559a233b772c1a105"}, - {file = "tomli-2.5.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:521345fd1f19d45b8df87657aaa38b6f2ca3800059fadf428e7ebf479a383646"}, - {file = "tomli-2.5.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6e95c7614e705bfe2b04b27aa124adec59752d15813df37e2156747cab3a006b"}, - {file = "tomli-2.5.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7ac2027d37c3afbdf4bdd377f2676f6f1d2122a5be1f1137b49dced590b37e75"}, - {file = "tomli-2.5.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:c414be4ed9d3cac80c42e348fa5a956117d1a48227f48026e31f59cb4a7671eb"}, - {file = "tomli-2.5.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:9b03d7dc168353b4132965bde20feceabaa470e570c6f59660dfae59b1f9eeb3"}, - {file = "tomli-2.5.0-cp314-cp314-win32.whl", hash = "sha256:6f041843c4d3a37245c0c056fd955b186bf8b1fb85690cbe40b81230891dc34b"}, - {file = "tomli-2.5.0-cp314-cp314-win_amd64.whl", hash = "sha256:f4b653094e18f9031102d3a1da5c729c8f222d85225b18037dac621695e46e1a"}, - {file = "tomli-2.5.0-cp314-cp314-win_arm64.whl", hash = "sha256:3f89d10c1ff6a38d992c27fc8a4816af71a909e08a40ec66934240b1e74347c3"}, - {file = "tomli-2.5.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:e9e15b4a6c7dd6b85b5fbab29488a73f1f70de516942308daa266bf0e0aeb0d4"}, - {file = "tomli-2.5.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:e12bbcd32897272fb05929110362ae9ff4c1b9bb26bd9e971e71dcd3275b4c3d"}, - {file = "tomli-2.5.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:20aa36de8f2cf87237143bc1fa1aae8d6612c09118f4da21c6a684db5dd1f6f9"}, - {file = "tomli-2.5.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:22185fad8a1e622f064e78008018a0dd3323550dcb479cb7a1d296888d74024f"}, - {file = "tomli-2.5.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:984012f71908165449a951de2050d52f276bfe3aa5d5f570f63ddad814370374"}, - {file = "tomli-2.5.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:f79203b3965b4000e91808aaa7c040206093f2b8bf86f455982f2274c9ccf442"}, - {file = "tomli-2.5.0-cp314-cp314t-win32.whl", hash = "sha256:91294a9fb94a75542f6e46e4a2ae709bd8d9b51134098cae5cf3bea5478b6d03"}, - {file = "tomli-2.5.0-cp314-cp314t-win_amd64.whl", hash = "sha256:f15e3e0b835a6d68b10c86bf80a3149780498d6911c93c3ffd1861d19f9200f1"}, - {file = "tomli-2.5.0-cp314-cp314t-win_arm64.whl", hash = "sha256:6664b7ae7af7294256c53960a6103077f4914cec8ff98479c352f622c6f6b2f0"}, - {file = "tomli-2.5.0-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:a525685c2f97da40762b8695eb7aa0af4c8344ca1905c73e4e29cb04d34607dc"}, - {file = "tomli-2.5.0-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:9dbb18c1cfb2f6517942fc9314437f66aa06d94436ffb1f06102ef3572f35276"}, - {file = "tomli-2.5.0-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:752e8b1aa6a4367ef8bf6a1a1e005540f7ed055ba36d7193796812ca5404eb52"}, - {file = "tomli-2.5.0-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c47300f9bf791808f77d82747691c4bb09cb14bdf3060cca99b42cdc4361d5a7"}, - {file = "tomli-2.5.0-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:19b0dd8749f4ea2f112c5fcfb3c5248390c899d7e2e173f1d91abee1fa0ff391"}, - {file = "tomli-2.5.0-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:57b1c3b01fab802e2899bc3d168dca320e14165e2fd9fd584760fb4ca5826859"}, - {file = "tomli-2.5.0-cp315-cp315-win32.whl", hash = "sha256:667e521b37a6c5ccaa044202c235b530f90177ffe2cd4a64ecc213c7dd535feb"}, - {file = "tomli-2.5.0-cp315-cp315-win_amd64.whl", hash = "sha256:d747252933c8a65ef6bd8da0fbb7ce28a90eb6119d8cd00772cd528aa07b68d5"}, - {file = "tomli-2.5.0-cp315-cp315-win_arm64.whl", hash = "sha256:75dbcde8751b0a960aa3de173aa5e894d590755c6d7758b7e774c06f1dc3cbdd"}, - {file = "tomli-2.5.0-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:2419c2a189551987b59d80e63ec355671283336f41c6b9b89462df679c7d0c57"}, - {file = "tomli-2.5.0-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:0dc598040da8d42cf20f0be588ed7004f46db12a0ac6c32e03a59dccedaaadcd"}, - {file = "tomli-2.5.0-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:49096930c8d886c9bbdab62d2d0d17ce823ddeea522309a190b36245d5b49e01"}, - {file = "tomli-2.5.0-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b8ade5023067f99fe72b88accd30d0ea05a158e9e32a11f124e731ea9695313f"}, - {file = "tomli-2.5.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:b69564772b5c8f22ea5f498dff08cfa825045b4d4c4400529000bdf818aa3b2a"}, - {file = "tomli-2.5.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:8ff3a2ca028c7eee0c777f9a092038d0a594a9fa04e215f929a22c329e2cb142"}, - {file = "tomli-2.5.0-cp315-cp315t-win32.whl", hash = "sha256:62fc1bc8eb03e3a9cadfca713d65614ed8e09d974a283295ffe3a831976b4dc5"}, - {file = "tomli-2.5.0-cp315-cp315t-win_amd64.whl", hash = "sha256:f3fcbc57b1791fa6cbe5d8434179d51de12be1a4811469529f47f6e7487a2571"}, - {file = "tomli-2.5.0-cp315-cp315t-win_arm64.whl", hash = "sha256:d2ba24db8a9376921b5e87b4762b9adb0f3f1deaea68f2b8b0bb2c11efb9c3e7"}, - {file = "tomli-2.5.0-py3-none-any.whl", hash = "sha256:32a7b79ac57a2e83670ce329ccf675798bc5a2094783a63676866b70503f2e2b"}, - {file = "tomli-2.5.0.tar.gz", hash = "sha256:264507556cd8b8c8e7c6ee037cdf443a463f03f4c958e57195e3d369711b8ff6"}, + {file = "pyyaml-6.0.4-cp310-cp310-macosx_10_15_x86_64.whl", hash = "sha256:78be5a1b05a5d1fd46d0290393e5deeb581fa617585462c1b84f7c6b0cb1e489"}, + {file = "pyyaml-6.0.4-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:e39017e1cef43d03b2ba427f60213e4b36dbc6fb092235fa3de3a510ce064d3c"}, + {file = "pyyaml-6.0.4-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:54c23934cf166bb2090d73d82b1388aadb1cead5e73885223dcfa4a459a22d43"}, + {file = "pyyaml-6.0.4-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:d58fe9fa2056fed24f055b74d5dc808fa1f5d084c22e4118f0a08253fe677ffd"}, + {file = "pyyaml-6.0.4-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:88a089e6424a8a256321270620d5a4328ad5227fb2061b07d33f596894336914"}, + {file = "pyyaml-6.0.4-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:52460c6dd874b22d49fda228fac59da74d7a7b06175ffcc80bfa3ba5389d7f73"}, + {file = "pyyaml-6.0.4-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:c24097c0462f66358c99dc83d3e1850e005f6293cfa1df1edb243428da1668bf"}, + {file = "pyyaml-6.0.4-cp310-cp310-win32.whl", hash = "sha256:34edca7ab64b705ee7c80bf3f9ac609240677db11e83d9317191f483a4b5a433"}, + {file = "pyyaml-6.0.4-cp310-cp310-win_amd64.whl", hash = "sha256:5246a0feaaac497b09c9462aa926280ae02fc8791b0099c0a925ebd7c7f249a6"}, + {file = "pyyaml-6.0.4-cp311-cp311-macosx_10_15_x86_64.whl", hash = "sha256:180ac792c958c2173f6e4467c55ae5f73ab1a9a624ee29fc7095c56d5e3a4055"}, + {file = "pyyaml-6.0.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:730788375056c43d3ac15bd894c9cd2fb7a931a38b302f408620c64b3ef176ed"}, + {file = "pyyaml-6.0.4-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:71bb5b87465d88d1dfc577115af6d435bff9b26f2512936f610c26aa55966028"}, + {file = "pyyaml-6.0.4-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b9fe0b8c65a1611053eb7fcaa7c022f655b7eebeb0ea034572615453cae6b843"}, + {file = "pyyaml-6.0.4-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:622aa875fa6533f25fedcffe23079357d65a690d462200afed5d8e9d0e01ebee"}, + {file = "pyyaml-6.0.4-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:49e38a95e24738908ea852e61df0abc58d1e4d4f974ccdb2386eaee412bedc67"}, + {file = "pyyaml-6.0.4-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:4d3bbc5e8a84a5a6775adecac786f489510a7159b1c343d6f31426d888cfdd6e"}, + {file = "pyyaml-6.0.4-cp311-cp311-win32.whl", hash = "sha256:c0d68d972f6f6417b4e85e9522f3d57bb4fbc924379766ccd87254a31009c1cd"}, + {file = "pyyaml-6.0.4-cp311-cp311-win_amd64.whl", hash = "sha256:0db75f402e99c25239003a499c214a61947b4ef5312af34711d4c63e5c179318"}, + {file = "pyyaml-6.0.4-cp312-cp312-macosx_10_15_x86_64.whl", hash = "sha256:1088ad740f50c13178dad16fbc2fa1f634c791d42c7009fdb390e38e5b90b788"}, + {file = "pyyaml-6.0.4-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:4d30c2f186612bd2f9f07c08a4c96721af59cfc8da3ec7cb27dfa2834e8bb019"}, + {file = "pyyaml-6.0.4-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:45e37dd647db9d67b757444c74060c064ace5fdaa08f42bf4fda3812275d423e"}, + {file = "pyyaml-6.0.4-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:9e7ec9dc75cadd392fd687cc9b8ccf7dd59ada0a991e0d14ae0fad9ecdba00c3"}, + {file = "pyyaml-6.0.4-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:93bfb2459195406a518e2f487a9bbf01df240175f31e06f5a252ac6734c7bbf0"}, + {file = "pyyaml-6.0.4-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:84e97378010f3da8daf673b82d39ed638098d236a1b760d61c0c1348a642bd70"}, + {file = "pyyaml-6.0.4-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:f5c410f9e2ffc9286279a46f2e8c107edaf3b1123510af59c828a9c15b23c9db"}, + {file = "pyyaml-6.0.4-cp312-cp312-win32.whl", hash = "sha256:60e9da2772e259307650e03c24f50e3bc2d9fa5ed1ba44c47582e13b0e7708d1"}, + {file = "pyyaml-6.0.4-cp312-cp312-win_amd64.whl", hash = "sha256:131d11bd9b60d705a6388366d77ed67850995a4d2be85fe149785a257c17e531"}, + {file = "pyyaml-6.0.4-cp312-cp312-win_arm64.whl", hash = "sha256:69380d4bae12aab2a2c9532deff6a2841bc9fda47c333691bd2368b696301768"}, + {file = "pyyaml-6.0.4-cp313-cp313-macosx_10_15_x86_64.whl", hash = "sha256:61eef2f08e977b725f37a8d1663f5a222c6f09207ac0794030d5fca062e7c96e"}, + {file = "pyyaml-6.0.4-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:9d4211f080920629a90c9e31c51e326fb70cfae38f18d4128b9913c23642bace"}, + {file = "pyyaml-6.0.4-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:41b4669c3a8fd5750e594dff59d3e62d40e321fec467b50449603710ed0a68f3"}, + {file = "pyyaml-6.0.4-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:efe68ed09903cca9ab4117c2b9ea6ee8d369818808945bb5a7fa8009b5630b45"}, + {file = "pyyaml-6.0.4-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:50588147ab2c6a59b5f990a4905db80899a6c2bd197e046a6201f1e67587e794"}, + {file = "pyyaml-6.0.4-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:4d1e8d6e345b4b4424a05a11e699e999e65a88f422f73636f8a0b354bf219ffa"}, + {file = "pyyaml-6.0.4-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:a56491babf0d976625807953bd192dd9de973fccb3270e77b1a795b152a26175"}, + {file = "pyyaml-6.0.4-cp313-cp313-win32.whl", hash = "sha256:1631d566655f3af7d6c4a4485267830f6b680d3dc9704b659b3c3f4541b5a3fe"}, + {file = "pyyaml-6.0.4-cp313-cp313-win_amd64.whl", hash = "sha256:0a3a351f04dc124f9357512bdb80ac37cd1750cf1371da33e7cbb96d80ac865f"}, + {file = "pyyaml-6.0.4-cp313-cp313-win_arm64.whl", hash = "sha256:f617e4e5c619fef5284335b24e3af3a77ce08dc5c389ff4b25033bb2749032b7"}, + {file = "pyyaml-6.0.4-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:4a329472db6c8858ebd94f2214a54c8bff8f035a6cc7af1ab39cc1b33a5f0e56"}, + {file = "pyyaml-6.0.4-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:7335809813ec838d9cd334b1744cda33deb141c9ef23a9c0df371c37980d3851"}, + {file = "pyyaml-6.0.4-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ed9b957abb12f6ffcd92d5db32fa3ffd4e4a8423d80ddd51b4efa63b42f6a76b"}, + {file = "pyyaml-6.0.4-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b525488d5addf5d59ff4610cd8b1deab9dc97fe0fb3fb74533d7f65e9792bd92"}, + {file = "pyyaml-6.0.4-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c604dc2613c417130479cdd6e55c2faa691b6365aa82b3dafddfcecc2eaf1ac7"}, + {file = "pyyaml-6.0.4-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:f1a4a85b419f5cb6470dd4be5f766bc59532f11b9c22c076b58a0348f05dca5f"}, + {file = "pyyaml-6.0.4-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:132c3c7c37a8e6f334921b05cfea5d26e241d792dcbb4db0462129d25ca53b43"}, + {file = "pyyaml-6.0.4-cp314-cp314-win_amd64.whl", hash = "sha256:1d2f08c122727c86f8303bb1dd45159ca1de1f2d68798e671ec46974e321008e"}, + {file = "pyyaml-6.0.4-cp314-cp314-win_arm64.whl", hash = "sha256:33506a2620f0e7c49858f09cb44e99f144878d03af3d9c10aa136e9a1d103bcd"}, + {file = "pyyaml-6.0.4-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:1db4d51d3c2c9545dd44c614febc4594240754f74b30d8e501415b118347f0d1"}, + {file = "pyyaml-6.0.4-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:93da48af92c84c4236578e330a514ca324362c0bb62894d8d2343363ed57ff03"}, + {file = "pyyaml-6.0.4-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3c7129bcee5c88c1450802cc6a95b690ee7c51bfcc7a9b60bbd9549a7a4fcbe6"}, + {file = "pyyaml-6.0.4-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2018fda285d1289527a389e1b4ace1e2d3af410930f949136b55ecb0747744d1"}, + {file = "pyyaml-6.0.4-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:15c52bb238a15bb4fd7e6342a5ac71d594507667c7fe0e5a5abbc0f6875d1e91"}, + {file = "pyyaml-6.0.4-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:ab874ebcc5c12c31c859a9e9fe159d688df1f7a099818ef8a35906264a8f5d6b"}, + {file = "pyyaml-6.0.4-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:62c5b5669b05dabf991a705f3a3601f57b65e95121a1d3e3a4ae4446c8632865"}, + {file = "pyyaml-6.0.4-cp314-cp314t-win_amd64.whl", hash = "sha256:609e8efaffa5662da16b7d53eef76fc4eedbbe56fce5829b67ba808a6e35d399"}, + {file = "pyyaml-6.0.4-cp314-cp314t-win_arm64.whl", hash = "sha256:a266cf55ee5cf63c1803432a61c6386e750e0012ca49d12d26ccb0ffd80b343a"}, + {file = "pyyaml-6.0.4-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:12a155bc41509d71a2eb73e2191d9e400c1345ea99ac3d9946c31f40a4c840f8"}, + {file = "pyyaml-6.0.4-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:070c22b6f490d6cc30912be9fb9ab1af9c752769b39b53616f6510c3f038ee6a"}, + {file = "pyyaml-6.0.4-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:872d2a592289061c1b987e335b3568a2616b474be02bd0608d8f551a385441cd"}, + {file = "pyyaml-6.0.4-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:914b19e17814315fbcca52031bf79b68237f3d87a948c584a667b18b468e4df7"}, + {file = "pyyaml-6.0.4-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c57e40928738c4a202852759f9e1ee2c7063429a9469ee1ac15651bbf7d69963"}, + {file = "pyyaml-6.0.4-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:8e0cd755ce5e9009fd95f9c553e5942478feb8f7dffa19435641fcdc3c20e8ca"}, + {file = "pyyaml-6.0.4-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:2c11be5ab4d9f603a598b5ce93a2064ae38087bdf1b384c5397170054cda4e36"}, + {file = "pyyaml-6.0.4-cp315-cp315-win_amd64.whl", hash = "sha256:67da066ca12eb60114ea87f2ecbcca622fff0c205c743cc900437127564fabf6"}, + {file = "pyyaml-6.0.4-cp315-cp315-win_arm64.whl", hash = "sha256:573debb9fe3075423d4f823795a678580e597218c25baef178d532b124a25a25"}, + {file = "pyyaml-6.0.4-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:c680622f85979f2ff59b4ae44c1ecb5566b2f0f0ffe5d0dc8b4bb6a0e916dabb"}, + {file = "pyyaml-6.0.4-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:18ea9bda247857fc0de05181675dc116b54c1b04ca3db71de5d2108c882823b7"}, + {file = "pyyaml-6.0.4-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6ac167ebebc0c387290406a337b9b5c8c343fa5f7928d5941e45a94b8ba3aa39"}, + {file = "pyyaml-6.0.4-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:4a2a8f27d24d4cdc05aa11df5f4c08e13f30d9e6674809b6a5ddcfcba49a653a"}, + {file = "pyyaml-6.0.4-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e956541cc7a3fff2bb5b17aeb6c5bb42c86c8e6dafb5ebdd41a05e72e702076b"}, + {file = "pyyaml-6.0.4-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:8708f6ab9c2581ffa05f66dae3206bb0385949650537d7295fc7ab0d6454dd70"}, + {file = "pyyaml-6.0.4-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:a65339c24f2fb8d4419e06ceec1bda98bdcff727b3b533a81d5af6bb2dd34520"}, + {file = "pyyaml-6.0.4-cp315-cp315t-win_amd64.whl", hash = "sha256:a3cc63af3d639d1609143711837b926183418260aae89ed95193c07b25b99d33"}, + {file = "pyyaml-6.0.4-cp315-cp315t-win_arm64.whl", hash = "sha256:d276f23e2371deb5ee68dd252cc9c2402b806b54d8d2cc7efbb6c34c3a78d886"}, + {file = "pyyaml-6.0.4.tar.gz", hash = "sha256:e24bf71af8a432d7808fabff134d38dfe16d3cbb41f2873bb4b1e42422de0a1a"}, ] [[package]] @@ -476,7 +486,7 @@ version = "0.15.2" description = "Style preserving TOML library" optional = false python-versions = ">=3.9" -groups = ["dev"] +groups = ["main", "dev"] files = [ {file = "tomlkit-0.15.2-py3-none-any.whl", hash = "sha256:05562412163a3037b94497385fb7f9204c637bc605af7a48199e41cf2272f437"}, {file = "tomlkit-0.15.2.tar.gz", hash = "sha256:83e32755ba1d20d9340bd069ee97e9f6232ba2346b63ffcba425de01f7e327a6"}, @@ -485,4 +495,4 @@ files = [ [metadata] lock-version = "2.1" python-versions = ">=3.12,<4.0" -content-hash = "28a91daf92bd41969e2786767d8820b6d0db39f6f852db16f523fe5689a56e8c" +content-hash = "041646e4eb66e16fb812e3cc5b87d582a4cac76f7c9d5ca75a363813cdb41e21" diff --git a/pyproject.toml b/pyproject.toml index a51e01f..aedea55 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -9,9 +9,10 @@ build-backend = "poetry_dynamic_versioning.backend" name = "mirageoscience.pre-commit-hooks" requires-python = ">=3.12,<4.0" dynamic = ["version"] +dependencies = ["packaging>=25", "PyYAML>=6", "tomlkit>=0.15.2"] description = "" -readme = "README.rst" +readme = "README.md" license = "MIT" authors = [{ name = "Mira Geoscience", email = "support@mirageoscience.com" }] @@ -21,6 +22,8 @@ Repository = "https://github.com/MiraGeoscience/pre-commit-hooks" [project.scripts] check_copyright = "mirageoscience.hooks.check_copyright:main" git_message_hook = "mirageoscience.hooks.git_message_hook:main" +check_pixi_lock = "mirageoscience.hooks.check_pixi_lock:main" +check_recipe = "mirageoscience.hooks.check_recipe:main" [dependency-groups] dev = [ @@ -29,7 +32,6 @@ dev = [ "pytest", "pytest-mock", "pytest-cov", - "tomli", ] [tool.poetry] @@ -37,7 +39,6 @@ requires-poetry = ">=2.2.0" include = [ "LICENSE", - "README.rst", { path = "mirageoscience/hooks/_version.py", format = ["sdist", "wheel"] }, ] diff --git a/tests/pixi_hooks_test.py b/tests/pixi_hooks_test.py new file mode 100644 index 0000000..58d2f71 --- /dev/null +++ b/tests/pixi_hooks_test.py @@ -0,0 +1,730 @@ +# ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +# Copyright (c) 2024-2026 Mira Geoscience Ltd. ' +# ' +# This file is part of mirageoscience.pre-commit-hooks package. ' +# ' +# mirageoscience.pre-commit-hooks is distributed under the terms and conditions ' +# of the MIT License (see LICENSE file at the root of this source code package). ' +# ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' + +from __future__ import annotations + +import sys + +import pytest + +from mirageoscience.hooks.check_pixi_lock import ( + LockOptions, + validate_lock, +) +from mirageoscience.hooks.check_pixi_lock import ( + main as check_pixi_lock_main, +) +from mirageoscience.hooks.check_recipe import ( + RecipeOptions, + validate_recipe, +) +from mirageoscience.hooks.check_recipe import ( + main as check_recipe_main, +) + + +def _lock_fixture( + *, + features: list[str], + pypi_names: tuple[str, ...] = (), +) -> tuple[dict, dict]: + pixi = { + "feature": { + "mira-pypi": { + "pypi-dependencies": {"mira-package": "*"}, + }, + }, + "environments": {"default": {"features": features}}, + } + packages = [ + {"pypi": f"https://pypi.org/simple/{name}/", "name": name} + for name in pypi_names + ] + entries = [{"pypi": package["pypi"]} for package in packages] + lock = { + "packages": packages, + "environments": {"default": {"packages": {"win-64": entries}}}, + } + return pixi, lock + + +def _multiline_pixi_manifest() -> str: + return """\ +[workspace.conda-pypi-map] +"https://example.org/conda" = { + mapping-mode = "overlay", + mapping = { + gempy = "gempy", + gempy-engine = "gempy-engine", + }, +} + +[constraints] +filelock = ">=4.2.1" + +[feature.mira-pypi] +pypi-dependencies = {} + +[feature.vendor-pypi] +pypi-dependencies = {} + +[feature.conda-base] +dependencies = {} + +[feature.conda-extra] +dependencies = {} +""" + + +def test_recipe_main_parses_toml_11_inline_tables(tmp_path, monkeypatch, capsys): + pixi_file = tmp_path / "pixi.toml" + recipe_file = tmp_path / "recipe.yaml" + pixi_file.write_text(_multiline_pixi_manifest(), encoding="utf-8") + recipe_file.write_text( + "requirements:\n run_constraints:\n - filelock >=4.2.1\n", + encoding="utf-8", + ) + monkeypatch.setattr( + sys, + "argv", + [ + "check-recipe", + "--pixi-file", + str(pixi_file), + "--recipe-file", + str(recipe_file), + ], + ) + + assert check_recipe_main() == 0 + assert "Recipe constraints match" in capsys.readouterr().out + + +@pytest.mark.parametrize( + "case", + [ + ("invalid = [", "requirements: {}", []), + ("", "requirements: [", []), + ("", "requirements: {}", ["--package-alias", "invalid"]), + ], +) +def test_recipe_main_reports_invalid_configuration(tmp_path, monkeypatch, capsys, case): + pixi_content, recipe_content, extra_args = case + pixi_file = tmp_path / "pixi.toml" + recipe_file = tmp_path / "recipe.yaml" + pixi_file.write_text(pixi_content, encoding="utf-8") + recipe_file.write_text(recipe_content, encoding="utf-8") + monkeypatch.setattr( + sys, + "argv", + [ + "check-recipe", + "--pixi-file", + str(pixi_file), + "--recipe-file", + str(recipe_file), + *extra_args, + ], + ) + + assert check_recipe_main() == 1 + assert "Invalid recipe configuration:" in capsys.readouterr().err + + +def test_pixi_lock_main_parses_toml_11_inline_tables(tmp_path, monkeypatch, capsys): + pixi_file = tmp_path / "pixi.toml" + lock_file = tmp_path / "pixi.lock" + pixi_file.write_text(_multiline_pixi_manifest(), encoding="utf-8") + lock_file.write_text( + "packages: []\nenvironments:\n default:\n packages:\n win-64: []\n", + encoding="utf-8", + ) + monkeypatch.setattr( + sys, + "argv", + [ + "check-pixi-lock", + "--pixi-file", + str(pixi_file), + "--lock-file", + str(lock_file), + "--pypi-feature", + "mira-pypi", + "--pypi-feature", + "vendor-pypi", + "--conda-feature", + "conda-base", + "--conda-feature", + "conda-extra", + ], + ) + + assert check_pixi_lock_main() == 0 + assert "Pixi lock package sources match" in capsys.readouterr().out + + +def test_pypi_packages_are_forbidden_without_feature(): + pixi, lock = _lock_fixture(features=[], pypi_names=("mira-package",)) + + errors = validate_lock(pixi, lock, LockOptions(pypi_feature="mira-pypi")) + + assert any("without the 'mira-pypi' feature" in error for error in errors) + + +def test_strict_pypi_rejects_transitive_packages_for_standalone_packages(): + pixi, lock = _lock_fixture( + features=["mira-pypi"], + pypi_names=("mira-package", "transitive-dependency"), + ) + + errors = validate_lock( + pixi, + lock, + LockOptions(pypi_feature="mira-pypi", strict_pypi=True), + ) + + assert any("expected exactly PyPI packages" in error for error in errors) + + +def test_non_strict_pypi_allows_transitive_packages_for_meta_packages(): + pixi, lock = _lock_fixture( + features=["mira-pypi"], + pypi_names=("mira-package", "transitive-dependency"), + ) + + errors = validate_lock(pixi, lock, LockOptions(pypi_feature="mira-pypi")) + + assert not errors + + +def test_multiple_pypi_features_check_packages_and_indexes_together(): + pixi, lock = _lock_fixture( + features=["mira-pypi", "vendor-pypi"], + pypi_names=("mira-package", "vendor-package"), + ) + pixi["feature"]["mira-pypi"]["pypi-options"] = { + "extra-index-urls": ["https://packages.example.org/simple"] + } + pixi["feature"]["vendor-pypi"] = {"pypi-dependencies": {"vendor-package": "*"}} + lock["packages"][1]["pypi"] = ( + "https://files.pythonhosted.org/packages/vendor-package.whl" + ) + lock["environments"]["default"]["indexes"] = ["https://packages.example.org/simple"] + lock["environments"]["default"]["packages"]["win-64"] = [ + {"pypi": package["pypi"]} for package in lock["packages"] + ] + + errors = validate_lock( + pixi, + lock, + LockOptions( + pypi_feature=("mira-pypi", "vendor-pypi"), + strict_pypi=True, + validate_pypi_sources=True, + ), + ) + + assert not errors + + +def test_multiple_conda_features_check_packages_together(): + pixi, lock = _lock_fixture( + features=["mira-pypi", "conda-base", "conda-extra"], + pypi_names=("mira-package",), + ) + pixi["feature"]["conda-base"] = {"dependencies": {"base-package": "*"}} + pixi["feature"]["conda-extra"] = {"dependencies": {"extra-package": "*"}} + base_url = "https://example.org/base-package-1-0.conda" + extra_url = "https://example.org/extra-package-1-0.conda" + entries = lock["environments"]["default"]["packages"]["win-64"] + entries.extend([{"conda": base_url}, {"conda": extra_url}]) + options = LockOptions( + pypi_feature="mira-pypi", + conda_feature=("conda-base", "conda-extra"), + ) + + assert not validate_lock(pixi, lock, options) + entries.remove({"conda": extra_url}) + errors = validate_lock(pixi, lock, options) + assert any("missing Conda packages ['extra-package']" in error for error in errors) + + +def test_pypi_source_validation_defaults_to_mira_git_urls(): + index = "https://packages.example.org/simple" + git_url = "git+https://github.com/MiraGeoscience/mira-package.git" + pixi, lock = _lock_fixture( + features=["mira-pypi"], + pypi_names=("mira-package", "mira-git-package"), + ) + pixi["feature"]["mira-pypi"]["pypi-options"] = {"index-url": index} + pixi["feature"]["mira-pypi"]["pypi-dependencies"]["mira-git-package"] = "*" + lock["packages"][0]["pypi"] = f"{index.removesuffix('/simple')}/mira-package.whl" + lock["packages"][1]["pypi"] = git_url + lock["environments"]["default"]["indexes"] = [index] + lock["environments"]["default"]["packages"]["win-64"] = [ + {"pypi": package["pypi"]} for package in lock["packages"] + ] + + errors = validate_lock( + pixi, + lock, + LockOptions( + pypi_feature="mira-pypi", + strict_pypi=True, + validate_pypi_sources=True, + ), + ) + + assert not errors + + +@pytest.mark.parametrize( + "git_url", + [ + "git+https://github.com/MiraGeoscience/../attacker/package.git", + "git+https://github.com/MiraGeoscience/%2e%2e/attacker/package.git", + "git+https://github.com/MiraGeoscience/%252e%252e/attacker/package.git", + "git+https://github.com/MiraGeoscience/%2f..%2fattacker/package.git", + "git+https://github.com/MiraGeoscience/%252f..%252fattacker/package.git", + "git+https://github.com/MiraGeoscience/%5c..%5cattacker/package.git", + "git+https://github.com/MiraGeoscience/package%0a.git", + "git+https://github.com/MiraGeoscience/..\\attacker/package.git", + ], +) +def test_pypi_source_validation_rejects_git_path_traversal(git_url): + pixi, lock = _lock_fixture(features=["mira-pypi"], pypi_names=("mira-package",)) + lock["packages"][0]["pypi"] = git_url + lock["environments"]["default"]["packages"]["win-64"] = [{"pypi": git_url}] + + errors = validate_lock( + pixi, lock, LockOptions("mira-pypi", validate_pypi_sources=True) + ) + + assert any("unexpected Git source" in error for error in errors) + + +def test_pypi_source_validation_matches_git_host_for_custom_prefix(): + pixi, lock = _lock_fixture(features=["mira-pypi"], pypi_names=("mira-package",)) + url = "git+https://github.com.evil.example/MiraGeoscience/package.git" + lock["packages"][0]["pypi"] = url + lock["environments"]["default"]["packages"]["win-64"] = [{"pypi": url}] + options = LockOptions( + "mira-pypi", + validate_pypi_sources=True, + git_url_prefixes=("git+https://github.com",), + ) + assert any( + "unexpected Git source" in error for error in validate_lock(pixi, lock, options) + ) + + url = "git+https://github.com/other/package%2dname.git@v1.0#subdirectory=python" + lock["packages"][0]["pypi"] = url + lock["environments"]["default"]["packages"]["win-64"] = [{"pypi": url}] + assert not validate_lock(pixi, lock, options) + + +def test_target_specific_feature_dependencies_are_checked_per_platform(): + pixi, lock = _lock_fixture(features=["mira-pypi", "conda-rt"]) + pixi["feature"]["mira-pypi"] = { + "target": { + "win-64": {"pypi-dependencies": {"win-package": "*"}}, + "linux": {"pypi-dependencies": {"linux-package": "*"}}, + } + } + pixi["feature"]["conda-rt"] = { + "dependencies": {"base-package": "*"}, + "target": {"win-64": {"dependencies": {"win-conda": "*"}}}, + } + win_url = "https://example.org/win.whl" + linux_url = "https://example.org/linux.whl" + lock["packages"] = [ + {"pypi": win_url, "name": "win-package"}, + {"pypi": linux_url, "name": "linux-package"}, + ] + base = {"conda": "https://example.org/base-package-1-0.conda"} + win = {"conda": "https://example.org/win-conda-1-0.conda"} + lock["environments"]["default"]["packages"] = { + "win-64": [{"pypi": win_url}, base, win], + "linux-64": [{"pypi": linux_url}, base], + } + options = LockOptions("mira-pypi", conda_feature="conda-rt", strict_pypi=True) + + assert not validate_lock(pixi, lock, options) + lock["environments"]["default"]["packages"]["win-64"].remove(win) + assert any("win-conda" in error for error in validate_lock(pixi, lock, options)) + + +@pytest.mark.parametrize("configured", [True, False]) +def test_pypi_source_validation_accepts_public_pypi_artifact_host(configured): + pixi, lock = _lock_fixture(features=["mira-pypi"], pypi_names=("mira-package",)) + if configured: + pixi["feature"]["mira-pypi"]["pypi-options"] = { + "index-url": "https://pypi.org/simple" + } + url = "https://files.pythonhosted.org/packages/mira-package.whl" + lock["packages"][0]["pypi"] = url + if configured: + lock["environments"]["default"]["indexes"] = ["https://pypi.org/simple"] + lock["environments"]["default"]["packages"]["win-64"] = [{"pypi": url}] + options = LockOptions("mira-pypi", validate_pypi_sources=True) + + assert not validate_lock(pixi, lock, options) + url = "https://files.pythonhosted.org.evil.example/package.whl" + lock["packages"][0]["pypi"] = url + lock["environments"]["default"]["packages"]["win-64"] = [{"pypi": url}] + assert any( + "unexpected PyPI source" in error + for error in validate_lock(pixi, lock, options) + ) + + +def test_pypi_source_validation_inherits_workspace_index_options(): + pixi, lock = _lock_fixture(features=["mira-pypi"], pypi_names=("mira-package",)) + index = "https://packages.example.org/simple" + url = "https://packages.example.org/packages/mira-package.whl" + pixi["pypi-options"] = {"index-url": index} + lock["packages"][0]["pypi"] = url + lock["environments"]["default"]["indexes"] = [index] + lock["environments"]["default"]["packages"]["win-64"] = [{"pypi": url}] + options = LockOptions("mira-pypi", validate_pypi_sources=True) + + assert not validate_lock(pixi, lock, options) + url = "https://files.pythonhosted.org/packages/mira-package.whl" + lock["packages"][0]["pypi"] = url + lock["environments"]["default"]["packages"]["win-64"] = [{"pypi": url}] + assert any( + "unexpected PyPI source" in error + for error in validate_lock(pixi, lock, options) + ) + + +def test_pypi_source_validation_ignores_inactive_index_feature(): + pixi, lock = _lock_fixture(features=["mira-pypi"], pypi_names=("mira-package",)) + pixi["feature"]["mira-pypi-index"] = { + "pypi-options": {"index-url": "https://packages.example.org/simple"} + } + url = "https://files.pythonhosted.org/packages/mira-package.whl" + lock["packages"][0]["pypi"] = url + lock["environments"]["default"]["packages"]["win-64"] = [{"pypi": url}] + options = LockOptions( + "mira-pypi", + pypi_index_feature="mira-pypi-index", + validate_pypi_sources=True, + ) + + assert not validate_lock(pixi, lock, options) + + +def test_pypi_source_validation_accepts_configured_artifact_root(): + pixi, lock = _lock_fixture(features=["mira-pypi"], pypi_names=("mira-package",)) + pixi["feature"]["mira-pypi"]["pypi-options"] = { + "index-url": "https://index.example/simple" + } + url = "https://artifacts.example/packages/mira-package.whl" + lock["packages"][0]["pypi"] = url + lock["environments"]["default"]["indexes"] = ["https://index.example/simple"] + lock["environments"]["default"]["packages"]["win-64"] = [{"pypi": url}] + options = LockOptions("mira-pypi", validate_pypi_sources=True) + assert any( + "unexpected PyPI source" in error + for error in validate_lock(pixi, lock, options) + ) + options = LockOptions( + "mira-pypi", + validate_pypi_sources=True, + artifact_source_roots=("https://artifacts.example/packages",), + ) + assert not validate_lock(pixi, lock, options) + + +@pytest.mark.parametrize("environments", [None, {"other": []}]) +def test_implicit_default_environment_and_unknown_named_environment(environments): + pixi, lock = _lock_fixture(features=[]) + if environments is None: + del pixi["environments"] + else: + pixi["environments"] = environments + assert not validate_lock(pixi, lock, LockOptions("mira-pypi")) + lock["environments"]["unknown"] = lock["environments"]["default"] + assert any( + "unknown: missing" in error + for error in validate_lock(pixi, lock, LockOptions("mira-pypi")) + ) + + +def test_pixi_lock_main_reports_validation_errors(tmp_path, monkeypatch, capsys): + pixi_file = tmp_path / "pixi.toml" + lock_file = tmp_path / "pixi.lock" + pixi_file.write_text(_multiline_pixi_manifest(), encoding="utf-8") + lock_file.write_text( + "packages: []\nenvironments:\n default:\n packages:\n win-64: []\n", + encoding="utf-8", + ) + monkeypatch.setattr( + sys, + "argv", + [ + "check-pixi-lock", + "--pixi-file", + str(pixi_file), + "--lock-file", + str(lock_file), + "--pypi-feature", + "missing-feature", + ], + ) + + assert check_pixi_lock_main() == 1 + assert "Pixi feature 'missing-feature' is not defined" in capsys.readouterr().err + + +def test_recipe_checks_constraints_and_optional_pytorch(): + pixi = { + "constraints": {"filelock": ">=4.2.1"}, + "feature": {}, + } + recipe = { + "requirements": { + "run": ["python >=3.12"], + "run_constraints": ["filelock >=4.2.1"], + } + } + + options = RecipeOptions(check_pytorch=True) + errors = validate_recipe(pixi, recipe, options) + + assert not errors + recipe["requirements"]["run"].append("pytorch-cpu >=2.0") + errors = validate_recipe(pixi, recipe, options) + assert any("PyTorch backend selection" in error for error in errors) + assert not validate_recipe(pixi, recipe, RecipeOptions()) + + +@pytest.mark.parametrize( + "dependency", + [ + "pytorch", + "pytorch >=2.13.0,<2.15.0", + "conda-forge::pytorch >=2.13.0, <2.15.0", + "pytorch=2.14", + "pytorch-lightning >=2.0", + ], +) +def test_recipe_allows_backend_neutral_pytorch(dependency): + recipe = {"requirements": {"run": [dependency]}} + assert not validate_recipe({}, recipe, RecipeOptions(check_pytorch=True)) + + +@pytest.mark.parametrize( + "dependency", + [ + "pytorch-cpu >=2.0", + "conda-forge::pytorch_gpu >=2.0", + "pytorch-cuda >=12", + "cpuonly", + "pytorch >=2.0 cpu*", + "pytorch=2.14=*cuda*", + "pytorch[version='>=2.0',build='cuda*']", + "pytorch-mutex 1.0 cuda", + ], +) +def test_recipe_rejects_pytorch_backend_selection(dependency): + recipe = {"requirements": {"run": [dependency]}} + errors = validate_recipe({}, recipe, RecipeOptions(check_pytorch=True)) + assert any("PyTorch backend selection" in error for error in errors) + assert not validate_recipe({}, recipe, RecipeOptions()) + + +def test_recipe_rejects_pytorch_backend_run_constraint(): + recipe = {"requirements": {"run_constraints": ["pytorch >=2.0 cpu*"]}} + errors = validate_recipe({}, recipe, RecipeOptions(check_pytorch=True)) + assert any("PyTorch backend selection" in error for error in errors) + + +def test_recipe_infers_feature_constraint_source_and_floor(): + pixi: dict = { + "constraints": {"filelock": ">=4.2.1", "setuptools": ">=84.1.0"}, + "feature": { + "conda-rt": { + "dependencies": { + "pillow": "13.*", + } + } + }, + } + recipe = { + "requirements": { + "run": ["python >=3.12"], + "run_constraints": [ + "filelock >=4.2.1", + "pillow >=13.0.0", + "setuptools >=84.1.0", + ], + } + } + + errors = validate_recipe(pixi, recipe, RecipeOptions()) + + assert not errors + + pixi["feature"]["conda-rt"]["dependencies"]["pillow"] = "12.*" + errors = validate_recipe(pixi, recipe, RecipeOptions()) + assert any("pillow" in error for error in errors) + + +@pytest.mark.parametrize( + ("recipe_constraint", "pixi_constraint"), + [("urllib3>=2.5", ">=2.5"), ("urllib3=2.5", "=2.5")], +) +def test_recipe_parses_conda_constraints_without_spaces( + recipe_constraint, pixi_constraint +): + pixi = {"constraints": {"urllib3": pixi_constraint}} + recipe = {"requirements": {"run_constraints": [recipe_constraint]}} + + assert not validate_recipe(pixi, recipe, RecipeOptions()) + + +@pytest.mark.parametrize("branch", ["then", "else"]) +def test_recipe_checks_conditional_run_requirements_for_transitivity(branch): + recipe = { + "requirements": { + "run": [{"if": "win", branch: ["python", "urllib3 >=2.5"]}], + "run_constraints": ["urllib3 >=2.5"], + } + } + + errors = validate_recipe( + {"constraints": {"urllib3": ">=2.5"}}, recipe, RecipeOptions() + ) + + assert len(errors) == 1 + assert "must remain transitive" in errors[0] + assert "urllib3" in errors[0] + + +def test_recipe_accepts_unconstrained_conditional_run_requirements(): + recipe = { + "requirements": { + "run": ["numpy", {"if": "win", "then": "pywin32", "else": "posix"}], + "run_constraints": ["urllib3 >=2.5"], + } + } + + assert not validate_recipe( + {"constraints": {"urllib3": ">=2.5"}}, recipe, RecipeOptions() + ) + + +def test_recipe_rejects_conditional_run_constraints(): + pixi = {"constraints": {"filelock": ">=4.2.1"}} + recipe = { + "requirements": { + "run": ["python >=3.12"], + "run_constraints": [{"if": "win", "then": "filelock >=4.2.1"}], + } + } + + errors = validate_recipe(pixi, recipe, RecipeOptions()) + assert any( + "Conditional run_constraints are not supported by check-recipe" in error + for error in errors + ) + assert any("--ignore-constraints" in error for error in errors) + + +def test_recipe_checks_pytorch_in_run_and_conditional_run_constraints(): + recipe = { + "requirements": { + "run": ["pytorch-cpu >=2.0"], + "run_constraints": [ + {"if": "win", "then": "pytorch-cuda >=12"}, + "pytorch-mutex 1.0 cuda", + ], + } + } + + errors = validate_recipe({}, recipe, RecipeOptions(check_pytorch=True)) + + assert any( + "Conditional run_constraints are not supported" in error for error in errors + ) + pytorch_errors = [error for error in errors if "PyTorch backend selection" in error] + assert len(pytorch_errors) == 1 + assert "run: pytorch-cpu" in pytorch_errors[0] + assert "run_constraints: pytorch-cuda" in pytorch_errors[0] + assert "run_constraints: pytorch-mutex 1.0 cuda" in pytorch_errors[0] + + +def test_recipe_ignores_conditional_constraint_validation_when_requested(): + pixi = {"constraints": {"filelock": ">=4.2.1"}} + recipe = { + "requirements": { + "run": ["python >=3.12"], + "run_constraints": [{"if": "win", "then": "filelock >=4.2.1"}], + } + } + + errors = validate_recipe(pixi, recipe, RecipeOptions(ignore_constraints=True)) + assert not errors + + +def test_recipe_checks_transitivity_for_ignored_conditional_constraints(): + pixi = { + "constraints": { + "filelock": ">=4.2.1", + "setuptools": ">=84.1.0", + } + } + recipe = { + "requirements": { + "run": ["filelock >=4.2.1", "setuptools >=84.1.0"], + "run_constraints": [ + {"if": "win", "then": "filelock >=4.2.1"}, + "setuptools >=84.1.0", + ], + } + } + + errors = validate_recipe(pixi, recipe, RecipeOptions(ignore_constraints=True)) + transitivity_errors = [error for error in errors if "must remain" in error] + assert len(transitivity_errors) == 1 + assert "['filelock', 'setuptools']" in transitivity_errors[0] + + +def test_recipe_checks_pytorch_in_ignored_conditional_constraints(): + recipe = { + "requirements": { + "run_constraints": [{"if": "win", "then": "pytorch-cpu >=2.0"}] + } + } + + errors = validate_recipe( + {}, recipe, RecipeOptions(check_pytorch=True, ignore_constraints=True) + ) + + assert any("PyTorch backend selection" in error for error in errors) + + +def test_recipe_accepts_inline_versions_but_rejects_versionless_dependencies(): + pixi = { + "feature": { + "conda-rt": { + "dependencies": { + "pillow": {"version": "13.*", "channel": "conda-forge"} + } + } + } + } + recipe = {"requirements": {"run_constraints": ["pillow >=13.0.0"]}} + assert not validate_recipe(pixi, recipe, RecipeOptions()) + pixi["feature"]["conda-rt"]["dependencies"]["pillow"] = {"path": "../pillow"} + assert any( + "pillow" in error for error in validate_recipe(pixi, recipe, RecipeOptions()) + )