-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
67 lines (55 loc) · 2.18 KB
/
Copy pathcli.py
File metadata and controls
67 lines (55 loc) · 2.18 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import typer
from pathlib import Path
from scanners.scanner import FileScanner
from parsers.html import parse_html
from parsers.ts import parse_ts
from combiners.combiner import TextMerger
from models.text import Result, Text
from exporteurs.json import ResultJSONExporter
def main(
dir: Path = typer.Option(".", help="Directory to scan"),
out: Path = typer.Option("translations.json", help="Output JSON file"),
pretty: bool = typer.Option(False, help="Pretty-print JSON"),
nosources: bool = typer.Option(False, help="Exlude sources files"),
debug: bool = typer.Option(
False, help="Include debug info (sources, etc.)"),
):
scanner = FileScanner()
files: list[Path] = scanner.walk(dir)
if debug:
typer.echo(f"Found {len(files)} files")
for f in files:
typer.echo(f"- {f}")
all_results: list[Text] = []
for f in files:
if f.suffix.lower() == ".html":
if debug:
typer.echo(f"Parsing HTML file: {f}")
try:
h: list[Text] = parse_html(str(f), base_path=dir.as_posix())
all_results.extend(h)
except Exception as e:
typer.echo(f"Error parsing {f}: {e}")
elif f.suffix.lower() == ".ts":
if debug:
typer.echo(f"Parsing HTML file: {f}")
try:
t: list[Text] = parse_ts(str(f), base_path=dir.as_posix())
all_results.extend(t)
except Exception as e:
typer.echo(f"Error parsing {f}: {e}")
merged_texts = TextMerger().add_texts(all_results).get_merged()
sorted_texts = sorted(merged_texts, key=lambda x: (x.Key, x.Context))
result: Result = Result(Texts=sorted_texts)
exporter = ResultJSONExporter(exclude_sources=nosources, pretty=pretty)
json_output: str = exporter.to_json(result)
robust_write(json_output, out)
def robust_write(text: str, filepath: Path):
filepath.parent.mkdir(parents=True, exist_ok=True)
try:
with open(filepath, 'w', encoding='utf-8') as f:
f.write(text)
except IOError as e:
print(f'Write failed: {e}')
if __name__ == "__main__":
typer.run(main)