Debian Codegraph @

scripts/add_testcase.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 import argparse
3 import json
4 import re
5 import subprocess
6 import sys
7 from pathlib import Path
8 from typing import Optional
9
10
11 CONFIGS = [
12 "s2t",
13 "s2tw",
14 "s2twp",
15 "s2hk",
16 "t2s",
17 "t2tw",
18 "t2hk",
19 "tw2s",
20 "tw2sp",
21 "tw2t",
22 "hk2s",
23 "hk2t",
24 ]
25
26
27 def repo_root() -> Path:
28 return Path(__file__).resolve().parents[1]
29
30
31 def prompt_if_missing(value: Optional[str], prompt: str) -> str:
32 if value:
33 return value
34 return input(prompt).strip()
35
36
37 def normalize_kind(value: str) -> str:
38 value = value.strip().lower()
39 if value in {"pr", "pull request", "pull-request"}:
40 return "PR"
41 if value in {"issue", "i"}:
42 return "Issue"
43 raise ValueError("PR or Issue must be either 'PR' or 'Issue'")
44
45
46 def sanitize_description(value: str) -> str:
47 value = value.strip()
48 if not value:
49 return ""
50 value = re.sub(r"[^0-9A-Za-z]+", "_", value)
51 return value.strip("_")
52
53
54 def testcase_id(kind: str, number: str, description: str) -> str:
55 suffix = sanitize_description(description)
56 base = f"BYVoid_OpenCC_{kind}_{number}"
57 if suffix:
58 return f"{base}_{suffix}"
59 return base
60
61
62 def default_opencc_path(root: Path) -> Path:
63 candidates = [
64 root / "bazel-bin/src/tools/command_line",
65 root / "bazel-bin/src/tools/command_line.exe",
66 root / "build/python/src/tools/opencc",
67 root / "build/Release/opencc",
68 root / "build/Release/opencc.exe",
69 ]
70 for path in candidates:
71 if path.exists():
72 return path
73 return candidates[0]
74
75
76 def default_dict_dir(root: Path) -> Path:
77 candidates = [
78 root / "bazel-bin/data/config/config_dict_validation_t2tw.runfiles/_main/data/dictionary",
79 root / "build/python/data",
80 root / "build/Release",
81 ]
82 for path in candidates:
83 if path.is_dir():
84 return path
85 return candidates[0]
86
87
88 def build_current_artifacts(root: Path) -> None:
89 subprocess.run(
90 [
91 "bazel",
92 "build",
93 "//src/tools:command_line",
94 "//data/config:config_dict_validation_t2tw",
95 ],
96 cwd=root,
97 check=True,
98 )
99
100
101 def convert(opencc: Path, config: Path, dict_dir: Path, text: str) -> str:
102 result = subprocess.run(
103 [str(opencc), "-c", str(config), "--path", str(dict_dir) + "/"],
104 input=text,
105 text=True,
106 stdout=subprocess.PIPE,
107 stderr=subprocess.PIPE,
108 check=False,
109 )
110 if result.returncode != 0:
111 raise RuntimeError(
112 f"{config.stem} conversion failed:\n{result.stderr.strip()}"
113 )
114 return result.stdout.rstrip("\n")
115
116
117 def load_testcases(path: Path) -> dict:
118 import re
119 with path.open(encoding="utf-8") as stream:
120 content = stream.read()
121 # Strip comments and trailing commas
122 pattern = re.compile(r'"(?:[^"\\]|\\.)*"|(/\*[\s\S]*?\*/|//.*)|(,\s*(?=[\]}]))')
123 clean_content = pattern.sub(lambda m: "" if (m.group(1) or m.group(2)) else m.group(0), content)
124 return json.loads(clean_content)
125
126
127 def write_testcases(path: Path, data: dict) -> None:
128 with path.open("w", encoding="utf-8") as stream:
129 json.dump(data, stream, ensure_ascii=False, indent=2)
130 stream.write("\n")
131
132
133 def parse_args() -> argparse.Namespace:
134 parser = argparse.ArgumentParser(
135 description="Generate an OpenCC testcase from current conversion output."
136 )
137 parser.add_argument("--kind", "--pr-or-issue", dest="kind")
138 parser.add_argument("--number")
139 parser.add_argument("--brief-description", "--brief_description", dest="brief")
140 parser.add_argument("--input", dest="input_text")
141 parser.add_argument("--testcases", type=Path)
142 parser.add_argument("--opencc", type=Path)
143 parser.add_argument("--config-dir", type=Path)
144 parser.add_argument("--dict-dir", type=Path)
145 parser.add_argument("--no-build", action="store_true")
146 parser.add_argument("--replace", action="store_true")
147 parser.add_argument("--dry-run", action="store_true")
148 return parser.parse_args()
149
150
151 def main() -> int:
152 args = parse_args()
153 root = repo_root()
154
155 try:
156 kind = normalize_kind(prompt_if_missing(args.kind, "PR or Issue: "))
157 except ValueError as error:
158 print(error, file=sys.stderr)
159 return 2
160
161 number = prompt_if_missing(args.number, "Number: ")
162 if not number:
163 print("Number is required", file=sys.stderr)
164 return 2
165
166 brief = prompt_if_missing(args.brief, "brief_description: ")
167 input_text = prompt_if_missing(args.input_text, "input text: ")
168 if not input_text:
169 print("input text is required", file=sys.stderr)
170 return 2
171
172 if not args.no_build:
173 build_current_artifacts(root)
174
175 testcases_path = args.testcases or root / "test/testcases/testcases.json"
176 config_dir = args.config_dir or root / "data/config"
177 dict_dir = args.dict_dir or default_dict_dir(root)
178 opencc = args.opencc or default_opencc_path(root)
179
180 if not opencc.exists():
181 print(f"opencc binary not found: {opencc}", file=sys.stderr)
182 return 1
183 if not dict_dir.is_dir():
184 print(f"dictionary directory not found: {dict_dir}", file=sys.stderr)
185 return 1
186
187 expected = {}
188 for config in CONFIGS:
189 expected[config] = convert(
190 opencc=opencc,
191 config=config_dir / f"{config}.json",
192 dict_dir=dict_dir,
193 text=input_text,
194 )
195
196 entry = {
197 "id": testcase_id(kind, number, brief),
198 "input": input_text,
199 "expected": expected,
200 }
201
202 data = load_testcases(testcases_path)
203 cases = data.setdefault("cases", [])
204 existing_index = next(
205 (index for index, case in enumerate(cases) if case.get("id") == entry["id"]),
206 None,
207 )
208 if existing_index is not None:
209 if not args.replace:
210 print(
211 f"testcase id already exists: {entry['id']} "
212 "(use --replace to update it)",
213 file=sys.stderr,
214 )
215 return 1
216 cases[existing_index] = entry
217 else:
218 cases.append(entry)
219
220 if args.dry_run:
221 print(json.dumps(entry, ensure_ascii=False, indent=2))
222 return 0
223
224 write_testcases(testcases_path, data)
225 print(f"Added testcase {entry['id']} to {testcases_path}")
226 return 0
227
228
229 if __name__ == "__main__":
230 raise SystemExit(main())