Debian Codegraph @

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

raw
1 # Copyright Mozilla Foundation
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 from __future__ import annotations
16
17 import logging
18 from argparse import ArgumentParser, RawDescriptionHelpFormatter
19 from collections import defaultdict
20 from os import makedirs
21 from os.path import dirname, exists, join, relpath
22 from shutil import copyfile
23 from textwrap import dedent
24
25 from moz.l10n.message import Message
26 from moz.l10n.paths.config import L10nConfigPaths
27 from moz.l10n.resource import UnsupportedResource, parse_resource, serialize_resource
28 from moz.l10n.resource.data import Comment, Entry, Resource, Section
29 from moz.l10n.resource.format import Format
30
31 log = logging.getLogger(__name__)
32
33
34 def cli() -> None:
35 parser = ArgumentParser(
36 description=dedent(
37 """
38 Build localization files for release.
39
40 Iterates source files as defined by --config, reads localization sources from --base, and writes to --target.
41
42 Trims out all comments and messages not in the source files for each of the --locales.
43
44 For Fluent, adds empty files for any missing from the target locale.
45 For other formats, copies file from the source locale if they are missing from the target.
46 """
47 ),
48 formatter_class=RawDescriptionHelpFormatter,
49 )
50 parser.add_argument(
51 "-v", "--verbose", action="count", default=0, help="increase logging verbosity"
52 )
53 parser.add_argument(
54 "--config", metavar="PATH", required=True, help="l10n.toml config file"
55 )
56 parser.add_argument(
57 "--base", metavar="PATH", required=True, help="base dir for localizations"
58 )
59 parser.add_argument(
60 "--target", metavar="PATH", required=True, help="target dir for localizations"
61 )
62 parser.add_argument(
63 "--locales", metavar="LOCALE", nargs="+", required=True, help="target locales"
64 )
65 args = parser.parse_args()
66
67 log_level = (
68 logging.WARNING
69 if args.verbose == 0
70 else logging.INFO
71 if args.verbose == 1
72 else logging.DEBUG
73 )
74 logging.basicConfig(format="%(message)s", level=log_level)
75
76 cfg_path: str = args.config
77 l10n_base: str = args.base
78 l10n_target: str = args.target
79 locales: set[str] = set(args.locales)
80
81 # locale -> [ftl_missing, src_fallback]
82 msg_data: dict[str, list[int]] = defaultdict(lambda: [0, 0])
83
84 paths = L10nConfigPaths(cfg_path)
85 paths.base = l10n_base
86 paths.locales = None
87 for (source_path, l10n_path_template), path_locales in paths.all().items():
88 log.debug(f"source {source_path}")
89 try:
90 source = parse_resource(source_path)
91 except UnsupportedResource:
92 source = None
93 for locale in locales.intersection(path_locales) if path_locales else locales:
94 l10n_path = l10n_path_template.format(locale=locale)
95 rel_path = relpath(l10n_path, l10n_base)
96 tgt_path = join(l10n_target, rel_path)
97 makedirs(dirname(tgt_path), exist_ok=True)
98 if source:
99 msg_delta = write_target_file(rel_path, source, l10n_path, tgt_path)
100 if msg_delta < 0:
101 msg_data[locale][0] -= msg_delta
102 elif msg_delta > 0:
103 msg_data[locale][1] += msg_delta
104 else:
105 msg_data[locale]
106 else:
107 from_path = l10n_path if exists(l10n_path) else source_path
108 if from_path != tgt_path:
109 copy = "copy" if from_path == l10n_path else "copy-src"
110 log.info(f"{copy} {rel_path}")
111 copyfile(from_path, tgt_path)
112 else:
113 log.info(f"skip {rel_path}")
114
115 log.info("----")
116 for locale, (ftl_missing, src_fallback) in sorted(
117 msg_data.items(), key=lambda d: d[0]
118 ):
119 log.info(f"{locale}:")
120 log.info(f" ftl_missing {ftl_missing:>6}")
121 log.info(f" src_fallback {src_fallback:>6}")
122
123
124 def write_target_file(
125 name: str,
126 source_res: Resource[Message, str],
127 l10n_path: str,
128 tgt_path: str,
129 ) -> int:
130 if exists(l10n_path):
131 l10n_res = parse_resource(l10n_path)
132 l10n_map = {
133 section.id + entry.id: entry
134 for section in l10n_res.sections
135 for entry in section.entries
136 if isinstance(entry, Entry)
137 }
138 l10n_res.sections = []
139 else:
140 l10n_res = Resource(source_res.format, [])
141 l10n_map = {}
142 # Fluent uses per-message fallback at runtime, allowing resources to be incomplete.
143 fill_from_source = source_res.format != Format.fluent
144 msg_delta = 0
145
146 def get_entry(
147 section_id: tuple[str, ...], source_entry: Entry[Message, str] | Comment
148 ) -> Entry[Message, str] | Comment | None:
149 nonlocal msg_delta
150 if isinstance(source_entry, Comment):
151 return None
152 id = section_id + source_entry.id
153 if id in l10n_map:
154 return l10n_map[id]
155 elif fill_from_source:
156 msg_delta += 1
157 return source_entry
158 else:
159 msg_delta -= 1
160 return None
161
162 for section in source_res.sections:
163 tgt_entries = [
164 entry
165 for entry_ in section.entries
166 if (entry := get_entry(section.id, entry_)) is not None
167 ]
168 l10n_res.sections.append(Section(section.id, tgt_entries))
169
170 msg = f"merge {name}"
171 log.info(f"{msg} ({msg_delta:+d})" if msg_delta != 0 else msg)
172 with open(tgt_path, "w", encoding="utf-8") as file:
173 for line in serialize_resource(l10n_res, trim_comments=True):
174 file.write(line)
175 return msg_delta
176
177
178 if __name__ == "__main__":
179 cli()