Debian Codegraph @

data/scripts/convert_config_dict_format.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3
4 # Rewrite an OpenCC config JSON so that its dictionary references point at
5 # a different dictionary format (text or ocd) instead of ocd2. Used to build
6 # the OPENCC_DICT_FORMAT=text/ocd CMake outputs, mirroring the ocd2<->text
7 # config conversion already used by the Bazel opencc_resources_zip /
8 # convert_resource_zip tools.
9
10 import json
11 import sys
12
13 TARGET_EXTENSIONS = {
14 "text": ".txt",
15 "ocd": ".ocd",
16 }
17
18
19 def convert_dict_references(value, target_format, target_extension):
20 if isinstance(value, dict):
21 converted = {}
22 for key, child in value.items():
23 if key == "type" and child == "ocd2":
24 converted[key] = target_format
25 elif key == "file" and isinstance(child, str) and child.endswith(".ocd2"):
26 converted[key] = child[:-len(".ocd2")] + target_extension
27 else:
28 converted[key] = convert_dict_references(
29 child, target_format, target_extension
30 )
31 return converted
32 if isinstance(value, list):
33 return [
34 convert_dict_references(child, target_format, target_extension)
35 for child in value
36 ]
37 return value
38
39
40 if len(sys.argv) != 4 or sys.argv[3] not in TARGET_EXTENSIONS:
41 print("Rewrite ocd2 dictionary references in a config JSON to another format")
42 print(f"Usage: {sys.argv[0]} [input] [output] [text|ocd]")
43 sys.exit(1)
44
45 target_format = sys.argv[3]
46 with open(sys.argv[1], encoding="utf-8") as f:
47 config = json.load(f)
48
49 converted = convert_dict_references(config, target_format, TARGET_EXTENSIONS[target_format])
50 with open(sys.argv[2], "w", encoding="utf-8") as f:
51 f.write(json.dumps(converted, ensure_ascii=False, indent=2) + "\n")