pre-commit-hooks/pre_commit_hooks/check_yaml.py

73 lines
1.9 KiB
Python
Raw Permalink Normal View History

from __future__ import annotations
2014-04-04 12:36:03 +08:00
import argparse
from collections.abc import Generator
from collections.abc import Sequence
from typing import Any
2020-02-06 03:10:42 +08:00
from typing import NamedTuple
2015-01-05 08:05:20 +08:00
2018-12-29 05:09:17 +08:00
import ruamel.yaml
2014-04-04 12:36:03 +08:00
2018-12-29 05:09:17 +08:00
yaml = ruamel.yaml.YAML(typ='safe')
def _exhaust(gen: Generator[str]) -> None:
for _ in gen:
pass
2020-02-06 03:10:42 +08:00
def _parse_unsafe(*args: Any, **kwargs: Any) -> None:
_exhaust(yaml.parse(*args, **kwargs))
2020-02-06 03:10:42 +08:00
def _load_all(*args: Any, **kwargs: Any) -> None:
_exhaust(yaml.load_all(*args, **kwargs))
2020-02-06 03:10:42 +08:00
class Key(NamedTuple):
multi: bool
unsafe: bool
LOAD_FNS = {
Key(multi=False, unsafe=False): yaml.load,
Key(multi=False, unsafe=True): _parse_unsafe,
Key(multi=True, unsafe=False): _load_all,
Key(multi=True, unsafe=True): _parse_unsafe,
}
def main(argv: Sequence[str] | None = None) -> int:
2014-04-04 12:36:03 +08:00
parser = argparse.ArgumentParser()
parser.add_argument(
'-m', '--multi', '--allow-multiple-documents', action='store_true',
)
parser.add_argument(
'--unsafe', action='store_true',
help=(
'Instead of loading the files, simply parse them for syntax. '
2023-07-23 11:28:40 +08:00
'A syntax-only check enables extensions and unsafe constructs '
'which would otherwise be forbidden. Using this option removes '
'all guarantees of portability to other yaml implementations. '
'Implies --allow-multiple-documents'
),
)
2019-02-12 11:56:15 +08:00
parser.add_argument('filenames', nargs='*', help='Filenames to check.')
2014-04-04 12:36:03 +08:00
args = parser.parse_args(argv)
load_fn = LOAD_FNS[Key(multi=args.multi, unsafe=args.unsafe)]
2014-04-04 12:36:03 +08:00
retval = 0
for filename in args.filenames:
try:
2020-02-06 03:10:42 +08:00
with open(filename, encoding='UTF-8') as f:
2018-12-29 05:09:17 +08:00
load_fn(f)
except ruamel.yaml.YAMLError as exc:
print(exc)
2014-04-04 12:36:03 +08:00
retval = 1
return retval
if __name__ == '__main__':
raise SystemExit(main())