diff --git a/.github/scripts/check-yaml.py b/.github/scripts/check-yaml.py new file mode 100644 index 0000000..bbc170e --- /dev/null +++ b/.github/scripts/check-yaml.py @@ -0,0 +1,52 @@ +"""Fail on any YAML file that is empty, does not parse, or repeats a key in one mapping.""" +import pathlib +import sys + +import yaml + + +class StrictLoader(yaml.SafeLoader): + def construct_mapping(self, node, deep=False): + seen = set() + for key_node, _ in node.value: + key = self.construct_object(key_node, deep=True) + if key in seen: + raise yaml.constructor.ConstructorError( + None, None, f"duplicate key {key!r}", key_node.start_mark + ) + seen.add(key) + return super().construct_mapping(node, deep) + + +def check(path: pathlib.Path) -> str | None: + text = path.read_text() + try: + documents = [document for document in yaml.load_all(text, Loader=StrictLoader)] + except yaml.YAMLError as error: + return str(error).replace("\n", " ") + if not any(document is not None for document in documents): + return "empty file" + return None + + +def main(roots: list[str]) -> int: + files = sorted({ + path + for root in roots + for path in ( + pathlib.Path(root).rglob("*.y*ml") if pathlib.Path(root).is_dir() else [pathlib.Path(root)] + ) + if ".git" not in path.parts + }) + failed = False + for path in files: + problem = check(path) + if problem: + failed = True + print(f"{path}: {problem}") + print(f"checked {len(files)} files") + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:] or ["."])) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..aace383 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,30 @@ +name: CI + +# One job on every pull request, with no path filter, so the required `check` is emitted for every change, docs-only +# ones included. It fails on any YAML file that is empty, does not parse or repeats a key. +on: + push: + branches: [main] + pull_request: + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.sha }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + check: + name: check + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Install PyYAML + run: python3 -m pip install --user 'PyYAML==6.0.2' + - name: Every YAML file parses, is not empty and repeats no key + run: python3 .github/scripts/check-yaml.py .