|
| 1 | +"""Validate manifests using StrictYAML.""" |
| 2 | + |
| 3 | +import os |
| 4 | +import pathlib |
| 5 | +from typing import Any, Optional, cast |
| 6 | + |
| 7 | +from strictyaml import StrictYAMLError, YAMLValidationError, load |
| 8 | + |
| 9 | +from dfetch import DEFAULT_MANIFEST_NAME |
| 10 | +from dfetch.log import get_logger |
| 11 | +from dfetch.manifest.manifest import Manifest, ManifestDict |
| 12 | +from dfetch.manifest.schema import MANIFEST_SCHEMA |
| 13 | +from dfetch.util.util import find_file, prefix_runtime_exceptions |
| 14 | + |
| 15 | +logger = get_logger(__name__) |
| 16 | + |
| 17 | + |
| 18 | +def _ensure_unique(seq: list[dict[str, Any]], key: str, context: str) -> None: |
| 19 | + """Ensure values for `key` are unique within a sequence of dicts.""" |
| 20 | + values = [item.get(key) for item in seq if key in item] |
| 21 | + seen: set[Any] = set() |
| 22 | + dups: set[Any] = set() |
| 23 | + for val in values: |
| 24 | + if val in seen: |
| 25 | + dups.add(val) |
| 26 | + else: |
| 27 | + seen.add(val) |
| 28 | + |
| 29 | + if dups: |
| 30 | + dup_list = ", ".join(sorted(map(str, dups))) |
| 31 | + raise RuntimeError( |
| 32 | + f"Schema validation failed:\nDuplicate {context}.{key} value(s): {dup_list}" |
| 33 | + ) |
| 34 | + |
| 35 | + |
| 36 | +def parse(path: str) -> Manifest: |
| 37 | + """Parse & validate the given manifest file against the StrictYAML schema. |
| 38 | +
|
| 39 | + Raises: |
| 40 | + RuntimeError: if the file is not valid YAML or violates the schema/uniqueness constraints. |
| 41 | + """ |
| 42 | + try: |
| 43 | + manifest_text = pathlib.Path(path).read_text(encoding="UTF-8") |
| 44 | + loaded_manifest = load(manifest_text, schema=MANIFEST_SCHEMA) |
| 45 | + except (YAMLValidationError, StrictYAMLError) as err: |
| 46 | + raise RuntimeError( |
| 47 | + "\n".join( |
| 48 | + [ |
| 49 | + "Schema validation failed:", |
| 50 | + "", |
| 51 | + err.context_mark.get_snippet(), |
| 52 | + "", |
| 53 | + err.problem, |
| 54 | + ] |
| 55 | + ) |
| 56 | + ) from err |
| 57 | + |
| 58 | + data: dict[str, Any] = cast(dict[str, Any], loaded_manifest.data) |
| 59 | + manifest: ManifestDict = data["manifest"] # required |
| 60 | + |
| 61 | + remotes = manifest.get("remotes", []) or [] # optional |
| 62 | + projects = manifest["projects"] # required |
| 63 | + |
| 64 | + _ensure_unique(remotes, "name", "manifest.remotes") # type: ignore |
| 65 | + _ensure_unique(projects, "name", "manifest.projects") # type: ignore |
| 66 | + _ensure_unique(projects, "dst", "manifest.projects") # type: ignore |
| 67 | + |
| 68 | + return Manifest(manifest, text=manifest_text, path=path) |
| 69 | + |
| 70 | + |
| 71 | +def find_manifest() -> str: |
| 72 | + """Find a manifest.""" |
| 73 | + paths = find_file(DEFAULT_MANIFEST_NAME, ".") |
| 74 | + |
| 75 | + if len(paths) == 0: |
| 76 | + raise RuntimeError("No manifests were found!") |
| 77 | + if len(paths) != 1: |
| 78 | + logger.warning( |
| 79 | + f"Multiple manifests found, using {pathlib.Path(paths[0]).as_posix()}" |
| 80 | + ) |
| 81 | + |
| 82 | + return os.path.realpath(paths[0]) |
| 83 | + |
| 84 | + |
| 85 | +def get_childmanifests(skip: Optional[list[str]] = None) -> list[Manifest]: |
| 86 | + """Get manifest and its path.""" |
| 87 | + skip = skip or [] |
| 88 | + logger.debug("Looking for sub-manifests") |
| 89 | + |
| 90 | + childmanifests: list[Manifest] = [] |
| 91 | + for path in find_file(DEFAULT_MANIFEST_NAME, "."): |
| 92 | + path = os.path.realpath(path) |
| 93 | + if path not in skip: |
| 94 | + logger.debug(f"Found sub-manifests {path}") |
| 95 | + with prefix_runtime_exceptions( |
| 96 | + pathlib.Path(path).relative_to(os.path.dirname(os.getcwd())).as_posix() |
| 97 | + ): |
| 98 | + childmanifests += [parse(path)] |
| 99 | + |
| 100 | + return childmanifests |
0 commit comments