Debian Codegraph @

third_party/python/moz.l10n/moz/l10n/bin/compare.py

raw
1 #!/usr/bin/env python
2
3 # Copyright Mozilla Foundation
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 from __future__ import annotations
18
19 import json
20 from argparse import ArgumentParser, RawDescriptionHelpFormatter
21 from os.path import abspath, basename, dirname, isdir, join, normpath, relpath
22 from textwrap import dedent
23
24 from moz.l10n.paths import L10nConfigPaths, L10nDiscoverPaths
25 from moz.l10n.resource import UnsupportedResource, parse_resource
26 from moz.l10n.resource.data import Entry
27
28
29 def cli() -> None:
30 parser = ArgumentParser(
31 description=dedent(
32 """
33 Compare localizations to their `source`, which may be
34 - a directory (using L10nDiscoverPaths),
35 - a TOML config file (using L10nConfigPaths), or
36 - a JSON file containing a mapping of file paths to arrays of messages.
37 """
38 ),
39 formatter_class=RawDescriptionHelpFormatter,
40 )
41 parser.add_argument(
42 "-v", "--verbose", action="count", default=0, help="increase output verbosity"
43 )
44 parser.add_argument("--json", action="store_true", help="output JSON")
45 parser.add_argument(
46 "--ext", nargs="+", type=str, help="file extensions, prefix with ! to exclude"
47 )
48 parser.add_argument(
49 "--source",
50 metavar="PATH",
51 required=True,
52 type=str,
53 help="path to source file listing expected files & messages",
54 )
55 parser.add_argument("paths", nargs="+", type=str, help="directories to test")
56 args = parser.parse_args()
57
58 ext_include: set[str] = set()
59 ext_exclude: set[str] = set()
60 if args.ext:
61 arg_ext: list[str] = args.ext
62 if len(arg_ext) == 1 and "," in arg_ext[0]:
63 arg_ext = [ext.strip() for ext in arg_ext[0].split(",")]
64 for ext in arg_ext:
65 if ext.startswith("!"):
66 ext = ext[1:]
67 ext_exclude.add(ext if ext.startswith(".") else f".{ext}")
68 else:
69 ext_include.add(ext if ext.startswith(".") else f".{ext}")
70
71 def ext_filter(path: str) -> bool:
72 included = not ext_include or any(path.endswith(ext) for ext in ext_include)
73 excluded = ext_exclude and any(path.endswith(ext) for ext in ext_exclude)
74 return included and not excluded
75
76 if args.source.endswith(".json"):
77 with open(args.source) as f:
78 source_data: dict[str, list[str] | set[str]] = json.load(f)
79 if ext_include or ext_exclude:
80 source_data = {k: set(v) for k, v in source_data.items() if ext_filter(k)}
81 else:
82 source_paths: L10nConfigPaths | L10nDiscoverPaths = (
83 L10nConfigPaths(args.source)
84 if args.source.endswith(".toml")
85 else L10nDiscoverPaths(args.source, args.source)
86 )
87 path0 = abspath(args.paths[0])
88 locale0 = basename(path0)
89 source_paths.base = dirname(path0)
90 source_data = {}
91 for ref_path, tgt_path in source_paths.all():
92 if ext_filter(tgt_path):
93 try:
94 path = relpath(tgt_path.format(locale=locale0), path0)
95 source_data[path] = msg_ids(ref_path)
96 except UnsupportedResource:
97 continue
98 source_total = sum(len(sd) for sd in source_data.values())
99 if source_total == 0:
100 raise ValueError(f"No messages found for source {args.source}")
101 if not args.json:
102 print(f"source: {source_total}")
103
104 json_res = {}
105 for path in args.paths:
106 if not isdir(path):
107 continue
108 lc = basename(normpath(path))
109 errors, missing = compare(source_data, path)
110 if args.json:
111 json_res[lc] = {
112 "errors": errors or None,
113 "missing": missing or None,
114 }
115 else:
116 total = sum(len(rm) for rm in missing.values())
117 print(f"{lc}: {-total}")
118 for path, error in errors.items():
119 print(f" !!! {path}: {error}")
120 if args.verbose > 0:
121 for path, messages in missing.items():
122 print(f" {path}: {-len(messages)}")
123 if args.verbose > 1:
124 for msg in messages:
125 print(f" {msg}")
126
127 if args.json:
128 print(json.dumps(json_res))
129
130
131 def compare(
132 source_data: dict[str, list[str] | set[str]], root: str
133 ) -> tuple[dict[str, str], dict[str, list[str]]]:
134 errors: dict[str, str] = {}
135 missing: dict[str, list[str]] = {}
136 for path, src_messages in source_data.items():
137 if src_messages:
138 try:
139 tgt_messages = msg_ids(join(root, path))
140 for msg in src_messages:
141 if msg not in tgt_messages:
142 if path in missing:
143 missing[path].append(msg)
144 else:
145 missing[path] = [msg]
146 except FileNotFoundError:
147 missing[path] = list(src_messages)
148 except Exception as e:
149 errors[path] = str(e)
150 return errors, missing
151
152
153 def msg_ids(path: str) -> set[str]:
154 res = parse_resource(path)
155 return {
156 ".".join(section.id + entry.id)
157 for section in res.sections
158 for entry in section.entries
159 if isinstance(entry, Entry)
160 }
161
162
163 if __name__ == "__main__":
164 cli()