blob: 6a679feefda4b088b2c48383569c30b90938361a [file] [log] [blame]
Anthony Sottile8f615292022-01-15 19:24:05 -05001from __future__ import annotations
2
Anthony Sottile243fe502014-08-19 16:03:48 -07003import argparse
Anthony Sottiledc50b7f2017-03-20 10:42:48 -07004import json
Aditya Khursalefe374512021-02-17 02:08:57 +05305from typing import Any
Anthony Sottile030bfac2019-01-31 19:19:10 -08006from typing import Sequence
Aditya Khursalefe374512021-02-17 02:08:57 +05307
8
9def raise_duplicate_keys(
Anthony Sottile8f615292022-01-15 19:24:05 -050010 ordered_pairs: list[tuple[str, Any]],
11) -> dict[str, Any]:
Aditya Khursalefe374512021-02-17 02:08:57 +053012 d = {}
13 for key, val in ordered_pairs:
14 if key in d:
15 raise ValueError(f'Duplicate key: {key}')
16 else:
17 d[key] = val
18 return d
Anthony Sottileb08f8342015-01-04 16:05:20 -080019
Anthony Sottile243fe502014-08-19 16:03:48 -070020
Anthony Sottile8f615292022-01-15 19:24:05 -050021def main(argv: Sequence[str] | None = None) -> int:
Anthony Sottile243fe502014-08-19 16:03:48 -070022 parser = argparse.ArgumentParser()
Anthony Sottile45756522019-02-11 19:56:15 -080023 parser.add_argument('filenames', nargs='*', help='Filenames to check.')
Anthony Sottile243fe502014-08-19 16:03:48 -070024 args = parser.parse_args(argv)
25
26 retval = 0
27 for filename in args.filenames:
Anthony Sottilef5c42a02020-02-05 11:10:42 -080028 with open(filename, 'rb') as f:
29 try:
Aditya Khursalefe374512021-02-17 02:08:57 +053030 json.load(f, object_pairs_hook=raise_duplicate_keys)
Anthony Sottilec11c5482020-05-14 16:29:55 -070031 except ValueError as exc:
Anthony Sottilef5c42a02020-02-05 11:10:42 -080032 print(f'{filename}: Failed to json decode ({exc})')
33 retval = 1
Anthony Sottile243fe502014-08-19 16:03:48 -070034 return retval
35
36
37if __name__ == '__main__':
Anthony Sottile39ab2ed2021-10-23 13:23:50 -040038 raise SystemExit(main())