-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson_merge.py
executable file
·53 lines (42 loc) · 1.66 KB
/
json_merge.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#!/bin/env python3
# Merge localization JSON files generated with gotext with possible new strings
from json import load, dump
from pathlib import Path
from shutil import move
from sys import argv, stderr
from tempfile import NamedTemporaryFile
from typing import List
if __name__ == "__main__":
if len(argv) != 3:
print("too few args", file=stderr)
print("", file=stderr)
print(f"{argv[0]} <target file> <source file>", file=stderr)
print(f"{argv[0]} messages.json out.json", file=stderr)
exit(1)
messages_file = Path(argv[1])
if not messages_file.exists():
print(f"no file? {messages_file}", file=stderr)
exit(1)
out_file = Path(argv[2])
if not out_file.exists():
print(f"no file? {out_file}", file=stderr)
exit(1)
with messages_file.open(encoding="utf-8") as bf:
merged = load(bf)
merged_ids: List[str] = []
for x in merged['messages']:
if x['id'] not in merged_ids:
merged_ids.append(x['id'])
with out_file.open(encoding="utf-8") as mf:
updated = load(mf)
for x in updated['messages']:
if x['id'] not in merged_ids:
print(f" Adding: '{x['id']}'")
merged['messages'].append(x)
# Write to temporary file
tmpf = NamedTemporaryFile("w", prefix="merged", suffix=".json", encoding="utf-8", delete=False)
with tmpf as f:
dump(merged, f, indent=' ' * 8, ensure_ascii=False)
# Move temp file
newpath = move(tmpf.name, messages_file)
print(tmpf.name, "->", newpath)