|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import argparse |
| 4 | +from collections.abc import Generator |
| 5 | +from collections.abc import Sequence |
| 6 | +from typing import Any |
| 7 | +from typing import NamedTuple |
| 8 | + |
| 9 | +import ruamel.yaml |
| 10 | + |
| 11 | +yaml = ruamel.yaml.YAML(typ='safe') |
| 12 | + |
| 13 | + |
| 14 | +def _exhaust(gen: Generator[str]) -> None: |
| 15 | + for _ in gen: |
| 16 | + pass |
| 17 | + |
| 18 | + |
| 19 | +def _parse_unsafe(*args: Any, **kwargs: Any) -> None: |
| 20 | + _exhaust(yaml.parse(*args, **kwargs)) |
| 21 | + |
| 22 | + |
| 23 | +def _load_all(*args: Any, **kwargs: Any) -> None: |
| 24 | + _exhaust(yaml.load_all(*args, **kwargs)) |
| 25 | + |
| 26 | + |
| 27 | +class Key(NamedTuple): |
| 28 | + multi: bool |
| 29 | + unsafe: bool |
| 30 | + |
| 31 | + |
| 32 | +LOAD_FNS = { |
| 33 | + Key(multi=False, unsafe=False): yaml.load, |
| 34 | + Key(multi=False, unsafe=True): _parse_unsafe, |
| 35 | + Key(multi=True, unsafe=False): _load_all, |
| 36 | + Key(multi=True, unsafe=True): _parse_unsafe, |
| 37 | +} |
| 38 | + |
| 39 | + |
| 40 | +def main(argv: Sequence[str] | None = None) -> int: |
| 41 | + parser = argparse.ArgumentParser() |
| 42 | + parser.add_argument( |
| 43 | + '-m', '--multi', '--allow-multiple-documents', action='store_true', |
| 44 | + ) |
| 45 | + parser.add_argument( |
| 46 | + '--unsafe', action='store_true', |
| 47 | + help=( |
| 48 | + 'Instead of loading the files, simply parse them for syntax. ' |
| 49 | + 'A syntax-only check enables extensions and unsafe constructs ' |
| 50 | + 'which would otherwise be forbidden. Using this option removes ' |
| 51 | + 'all guarantees of portability to other yaml implementations. ' |
| 52 | + 'Implies --allow-multiple-documents' |
| 53 | + ), |
| 54 | + ) |
| 55 | + parser.add_argument('filenames', nargs='*', help='Filenames to check.') |
| 56 | + args = parser.parse_args(argv) |
| 57 | + |
| 58 | + load_fn = LOAD_FNS[Key(multi=args.multi, unsafe=args.unsafe)] |
| 59 | + |
| 60 | + retval = 0 |
| 61 | + println("add_license_header.py") |
| 62 | + return retval |
| 63 | + |
| 64 | + |
| 65 | +if __name__ == '__main__': |
| 66 | + raise SystemExit(main()) |
0 commit comments