Debian Codegraph @

data/scripts/opencc_resources_zip.py

raw symbols SCIP
1 #!/usr/bin/env python3
2
3 import argparse
4 import hashlib
5 import json
6 import os
7 import subprocess
8 import time
9 import zipfile
10 from datetime import datetime, timezone
11
12
13 DEFAULT_SOURCE_URL = "https://github.com/BYVoid/OpenCC"
14 MANIFEST_NAME = "opencc-resource-manifest.json"
15
16
17 def parse_args():
18 parser = argparse.ArgumentParser(
19 description="Build an OpenCC share archive backed by text dictionaries."
20 )
21 parser.add_argument("--output", required=True)
22 parser.add_argument("--configs", nargs="+", required=True)
23 parser.add_argument("--dicts", nargs="+", required=True)
24 parser.add_argument("--source-url", default=DEFAULT_SOURCE_URL)
25 parser.add_argument("--stable-status")
26 parser.add_argument("--volatile-status")
27 return parser.parse_args()
28
29
30 def read_status_file(path):
31 values = {}
32 if not path:
33 return values
34 try:
35 with open(path, encoding="utf-8") as file:
36 for line in file:
37 parts = line.rstrip("\n").split(" ", 1)
38 if len(parts) == 2:
39 values[parts[0]] = parts[1]
40 except FileNotFoundError:
41 pass
42 return values
43
44
45 def git_output(args):
46 try:
47 return subprocess.check_output(
48 ["git", *args],
49 encoding="utf-8",
50 stderr=subprocess.DEVNULL,
51 ).strip()
52 except (FileNotFoundError, subprocess.CalledProcessError):
53 return ""
54
55
56 def first_value(values, keys):
57 for key in keys:
58 value = values.get(key)
59 if value:
60 return value
61 return ""
62
63
64 def build_time_from_status(values):
65 timestamp = values.get("BUILD_TIMESTAMP")
66 if timestamp:
67 try:
68 return datetime.fromtimestamp(int(timestamp), timezone.utc).isoformat()
69 except ValueError:
70 pass
71 return datetime.now(timezone.utc).isoformat()
72
73
74 def git_dirty():
75 try:
76 return (
77 subprocess.call(["git", "diff", "--quiet"], stderr=subprocess.DEVNULL) != 0
78 or subprocess.call(
79 ["git", "diff", "--cached", "--quiet"], stderr=subprocess.DEVNULL
80 )
81 != 0
82 )
83 except FileNotFoundError:
84 return False
85
86
87 def build_manifest(args, entries):
88 stable_status = read_status_file(args.stable_status)
89 volatile_status = read_status_file(args.volatile_status)
90 status = {**stable_status, **volatile_status}
91 source_url = first_value(
92 status,
93 [
94 "STABLE_BUILD_SCM_REMOTE",
95 "STABLE_GIT_REMOTE",
96 "BUILD_SCM_REMOTE",
97 "GIT_REMOTE",
98 ],
99 )
100 if not source_url:
101 source_url = git_output(["config", "--get", "remote.origin.url"])
102 if not source_url:
103 source_url = args.source_url
104
105 commit_id = first_value(
106 status,
107 [
108 "STABLE_BUILD_SCM_REVISION",
109 "STABLE_GIT_COMMIT",
110 "STABLE_BUILD_GIT_COMMIT",
111 "BUILD_SCM_REVISION",
112 "GIT_COMMIT",
113 ],
114 )
115 if not commit_id:
116 commit_id = git_output(["rev-parse", "HEAD"])
117
118 dirty = status.get("STABLE_BUILD_SCM_DIRTY")
119 if dirty not in ("0", "1"):
120 dirty = "1" if git_dirty() else "0"
121
122 return {
123 "manifest_version": 1,
124 "source_url": source_url,
125 "commit_id": commit_id or "unknown",
126 "source_dirty": dirty == "1",
127 "build_time_utc": build_time_from_status(status),
128 "hash_algorithm": "sha256",
129 "entries": entries,
130 }
131
132
133 def convert_dict_references(value):
134 if isinstance(value, dict):
135 converted = {}
136 for key, child in value.items():
137 if key == "type" and child == "ocd2":
138 converted[key] = "text"
139 elif key == "file" and isinstance(child, str) and child.endswith(".ocd2"):
140 converted[key] = child[:-5] + ".txt"
141 else:
142 converted[key] = convert_dict_references(child)
143 return converted
144 if isinstance(value, list):
145 return [convert_dict_references(child) for child in value]
146 return value
147
148
149 def read_text_config(path):
150 with open(path, encoding="utf-8") as file:
151 config = json.load(file)
152 converted = convert_dict_references(config)
153 return json.dumps(converted, ensure_ascii=False, indent=2) + "\n"
154
155
156 def read_clean_dictionary(path):
157 cleaned = []
158 with open(path, encoding="utf-8") as file:
159 for line in file:
160 if not line.strip() or line.lstrip().startswith("#"):
161 continue
162 cleaned.append(line)
163 return "".join(cleaned)
164
165
166 def write_entry(archive, name, content, date_time):
167 info = zipfile.ZipInfo(name)
168 info.date_time = date_time
169 info.compress_type = zipfile.ZIP_STORED
170 info.external_attr = 0o644 << 16
171 archive.writestr(info, content.encode("utf-8"))
172
173
174 def add_entry(archive, entries, name, content, date_time):
175 write_entry(archive, name, content, date_time)
176 entries[name] = {
177 "sha256": hashlib.sha256(content.encode("utf-8")).hexdigest(),
178 "size": len(content.encode("utf-8")),
179 }
180
181
182 def main():
183 args = parse_args()
184 output_dir = os.path.dirname(args.output)
185 if output_dir:
186 os.makedirs(output_dir, exist_ok=True)
187 date_time = time.localtime()[:6]
188 with zipfile.ZipFile(args.output, "w") as archive:
189 entries = {}
190 for path in sorted(args.configs, key=os.path.basename):
191 add_entry(
192 archive,
193 entries,
194 os.path.basename(path),
195 read_text_config(path),
196 date_time,
197 )
198 for path in sorted(args.dicts, key=os.path.basename):
199 add_entry(
200 archive,
201 entries,
202 os.path.basename(path),
203 read_clean_dictionary(path),
204 date_time,
205 )
206 manifest = json.dumps(
207 build_manifest(args, entries),
208 ensure_ascii=False,
209 indent=2,
210 sort_keys=True,
211 ) + "\n"
212 write_entry(archive, MANIFEST_NAME, manifest, date_time)
213
214
215 if __name__ == "__main__":
216 main()