pre-commit-hooks/pre_commit_hooks/check_json.py

39 lines
983 B
Python
Raw Normal View History

from __future__ import annotations
import argparse
import json
from collections.abc import Sequence
from typing import Any
def raise_duplicate_keys(
ordered_pairs: list[tuple[str, Any]],
) -> dict[str, Any]:
d = {}
for key, val in ordered_pairs:
if key in d:
raise ValueError(f'Duplicate key: {key}')
else:
d[key] = val
return d
2015-01-05 08:05:20 +08:00
def main(argv: Sequence[str] | None = None) -> int:
parser = argparse.ArgumentParser()
2019-02-12 11:56:15 +08:00
parser.add_argument('filenames', nargs='*', help='Filenames to check.')
args = parser.parse_args(argv)
retval = 0
for filename in args.filenames:
2020-02-06 03:10:42 +08:00
with open(filename, 'rb') as f:
try:
json.load(f, object_pairs_hook=raise_duplicate_keys)
2020-05-15 07:29:55 +08:00
except ValueError as exc:
2020-02-06 03:10:42 +08:00
print(f'{filename}: Failed to json decode ({exc})')
retval = 1
return retval
if __name__ == '__main__':
raise SystemExit(main())