Debian Codegraph @

third_party/python/moz.l10n/moz/l10n/paths/config.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 sys
18 from collections.abc import Callable, Iterable, Iterator
19 from glob import glob
20 from os import sep
21 from os.path import dirname, isfile, join, normpath, relpath
22 from re import Pattern, compile
23 from typing import Any, Dict
24
25 if sys.version_info >= (3, 11):
26 from tomllib import load
27 else:
28 from tomli import load
29
30 path_stars = compile(r"[*](?:[*](?:[/\\][*]*)?)?")
31 path_var = compile(r"{(\w+)}")
32
33
34 def path_regex(path: str) -> Pattern[str]:
35 """
36 Captures * groups as indexed and {vars} as named.
37 Expects `path` to use `/` as separator.
38 """
39 if path.startswith("{l10n_base}/"):
40 path = path[12:]
41 path = path_stars.sub(
42 lambda m: (
43 "([^/]*)" if m[0] == "*" else "((?:.*/)?)" if m[0] == "**/" else "(.*)"
44 ),
45 path,
46 )
47 path = path_var.sub(r"(?P<\1>[^/]*)", path)
48 return compile(path)
49
50
51 class PartialMap(Dict[str, str]):
52 """Allows `str.format_map()` calls with partial values."""
53
54 def __missing__(self, key: str) -> str:
55 return "{" + str(key) + "}"
56
57
58 class L10nConfigPaths:
59 """
60 Wrapper for localization config files.
61
62 Supports a subset of the format specified at:
63 https://moz-l10n-config.readthedocs.io/en/latest/fileformat.html
64
65 Differences:
66 - `[build]` is ignored
67 - `[[excludes]]` are not supported
68 - `[[filters]]` are ignored
69 - `[[paths]]` must always include both `reference` and `l10n`
70
71 Does not consider `.l10n-ignore` files.
72 """
73
74 def __init__(
75 self,
76 cfg_path: str,
77 *,
78 cfg_load: Callable[[str], dict[str, Any]] | None = None,
79 force_paths: list[str] | None = None,
80 locale_map: dict[str, Callable[[str], str]] | None = None,
81 _seen: set[str] | None = None,
82 ) -> None:
83 """
84 To customize the loading of a configuration at `cfg_path`, set `cfg_load`.
85
86 As configurations may include others, `cfg_load` can get called multiple times.
87 `_seen` is used internally to deduplicate file loads.
88
89 Use `force_paths` to list fully-qualified file paths to include
90 as reference paths if they match the `[[paths]]` config,
91 even if no file is present at those paths.
92
93 To use custom path variables for locales,
94 set `locale_map` to be a mapping of path variable names to functions,
95 which will be called with `locale` as their only argument.
96 """
97 if cfg_load:
98 toml = cfg_load(cfg_path)
99 else:
100 with open(cfg_path, mode="rb") as file:
101 toml = load(file)
102 self._cfg_path = cfg_path
103 self._locale_map = locale_map or {}
104 base = toml.get("basepath", ".")
105 self._base = normpath(join(dirname(cfg_path), base))
106 self._ref_root = self._base
107 self._locales: list[str] | None = toml.get("locales", None)
108 env = toml.get("env", None)
109 env_map = PartialMap(env) if env else None
110
111 self._templates: list[tuple[str, Pattern[str]]] = [] #
112 """
113 `[(ref, target)]`
114
115 To find references for targets,
116 retains a `ref` string with `{}` slots for the corresponding
117 `*` and `**` parts of the template paths,
118 which are also the indexed groups captured in `target`.
119 """
120
121 self._path_data: dict[str, tuple[str, list[str] | None]] = {}
122 """ ref -> (target, locales) """
123 fp = set(force_paths) if force_paths else None
124 for path in toml.get("paths", []):
125 ref: str = normpath(join(self._ref_root, path["reference"]))
126 target: str = path["l10n"] # Note: not normalised, so sep=="/"
127 if env_map:
128 target = target.format_map(env_map)
129 self._templates.append((path_stars.sub("{}", ref), path_regex(target)))
130 locales: list[str] | None = path.get("locales", None)
131 if "*" in ref:
132 if ref.count("*") != target.count("*"):
133 raise ValueError(
134 f"Wildcard mismatch between reference & l10n: {path}"
135 )
136 ref_re = compile(
137 path_stars.sub("(.*)", ref.replace(sep, "/").replace(".", r"\."))
138 )
139 *tgt_parts, tgt_end = path_stars.split(target)
140
141 def get_target(ref_file: str) -> str:
142 m = ref_re.fullmatch(ref_file.replace(sep, "/"))
143 assert m is not None, f"Unexpected ref with path {path}"
144 return (
145 "".join(a + b for a, b in zip(tgt_parts, m.groups())) + tgt_end
146 )
147
148 self._path_data.update(
149 (ref_file, (get_target(ref_file), locales))
150 for ref_file in glob(ref, recursive=True)
151 if isfile(ref_file)
152 )
153 if fp:
154 ref_re = path_regex(ref.replace(sep, "/"))
155 fp_match = {
156 path for path in fp if ref_re.fullmatch(path.replace(sep, "/"))
157 }
158 if fp_match:
159 self._path_data.update(
160 (path, (get_target(path), locales)) for path in fp_match
161 )
162 fp -= fp_match
163 else:
164 self._path_data[ref] = (target, locales)
165
166 self._includes: list[L10nConfigPaths] = []
167 if "includes" in toml:
168 if _seen is None:
169 _seen = set()
170 for incl in toml["includes"]:
171 incl_path: str = incl["path"]
172 if env_map:
173 incl_path = incl_path.format_map(env_map)
174 incl_path = normpath(join(self._ref_root, incl_path))
175 if incl_path not in _seen:
176 _seen.add(incl_path)
177 self._includes.append(
178 L10nConfigPaths(incl_path, cfg_load=cfg_load, _seen=_seen)
179 )
180
181 @property
182 def base(self) -> str:
183 """
184 The configuration root,
185 determined in the TOML by `basepath` relative to the config file path
186 or set by the user.
187 """
188 return self._base
189
190 @base.setter
191 def base(self, base: str) -> None:
192 for incl in self._includes:
193 incl.base = base
194 self._base = base
195
196 @property
197 def locales(self) -> list[str] | None:
198 """
199 Locales for the config,
200 determined in the TOML by `locales` or set directly by the user.
201 """
202 return self._locales
203
204 @locales.setter
205 def locales(self, locales: list[str] | None) -> None:
206 self._locales = locales
207 for incl in self._includes:
208 incl.locales = locales
209
210 @property
211 def ref_root(self) -> str:
212 """The reference root directory."""
213 return self._ref_root
214
215 @property
216 def ref_paths(self) -> Iterator[str]:
217 yield from self._path_data
218 for incl in self._includes:
219 yield from incl.ref_paths
220
221 def config_paths(self) -> Iterator[str]:
222 yield self._cfg_path
223 for incl in self._includes:
224 yield from incl.config_paths()
225
226 def all(
227 self, format_map: dict[str, str] | None = None
228 ) -> dict[tuple[str, str], list[str] | None]:
229 """
230 Returns a mapping of `(reference_path, target_path)` to `locales`
231 for all resources.
232
233 In target paths, `{l10n_base}` is replaced by `self.base`.
234 Any `{locale}` or `locale_map` variables will be left in.
235 Additional format variables may be set in `format_map`.
236 """
237 all: dict[tuple[str, str], list[str] | None] = {}
238 for key, locales in self._all(format_map):
239 prev = all.get(key, None)
240 if prev is None:
241 all[key] = locales
242 elif locales:
243 locales_ = list(set(prev).union(locales))
244 locales_.sort()
245 all[key] = locales_
246 return all
247
248 def _all(
249 self, format_map: dict[str, str] | None
250 ) -> Iterator[tuple[tuple[str, str], list[str] | None]]:
251 lc_map = PartialMap(format_map or ())
252 lc_map["l10n_base"] = self._base
253 for ref, (target, locales) in self._path_data.items():
254 target = target.format_map(lc_map)
255 if target.endswith(".pot"):
256 target = target[:-1]
257 target = normpath(join(self._base, target))
258 yield (ref, target), locales or self._locales
259 for incl in self._includes:
260 yield from incl._all(format_map)
261
262 def target(
263 self,
264 ref_path: str,
265 *,
266 format_map: dict[str, str] | None = None,
267 ) -> tuple[str | None, Iterable[str]]:
268 """
269 If `ref_path` is a valid reference path,
270 returns its corresponding target path and locales.
271 Otherwise, returns `None` for the path.
272
273 In the target path, `{l10n_base}` is replaced by `self.base`.
274 Any `{locale}` or `locale_map` variables will be left in.
275 Additional format variables may be set in `format_map`.
276 """
277 norm_ref_path = normpath(join(self._ref_root, ref_path))
278 if norm_ref_path.endswith(".po"):
279 norm_ref_path += "t"
280 pd = self._path_data.get(norm_ref_path, None)
281 if pd is None:
282 for incl in self._includes:
283 target = incl.target(norm_ref_path, format_map=format_map)
284 if target[0] is not None:
285 return target
286 return None, ()
287 pd_path, pd_locales = pd
288
289 fmt_map = PartialMap(format_map or ())
290 fmt_map["l10n_base"] = self._base
291 path = pd_path.format_map(fmt_map)
292 if path.endswith(".pot"):
293 path = path[:-1]
294 path = normpath(join(self._base, path))
295
296 locales = (
297 set(pd_locales).intersection(self._locales)
298 if pd_locales and self._locales
299 else pd_locales or self._locales or ()
300 )
301
302 return path, locales
303
304 def format_target_path(self, target: str, locale: str) -> str:
305 lc_map = {"locale": locale}
306 for key, fn in self._locale_map.items():
307 lc_map[key] = fn(locale)
308 return normpath(join(self._base, target.format_map(lc_map)))
309
310 def find_reference(self, target: str) -> tuple[str, dict[str, str]] | None:
311 """
312 A reverse lookup for the reference path and variables matching `target`,
313 or `None` if not found.
314 """
315 abs_target = join(self._base, normpath(target))
316 rel_target = normpath(relpath(abs_target, self._base)).replace(sep, "/")
317 for ref, pattern in self._templates:
318 match = pattern.fullmatch(rel_target)
319 if match:
320 vars = match.groupdict()
321 var_spans = {match.span(name) for name in vars}
322 star_values = [
323 group
324 for idx, group in enumerate(match.groups())
325 if match.span(idx + 1) not in var_spans
326 ]
327 ref_path = normpath(ref.format(*star_values))
328 if ref_path in self._path_data:
329 return ref_path, vars
330 elif ref_path.endswith(".po") and ref_path + "t" in self._path_data:
331 return ref_path + "t", vars
332 for incl in self._includes:
333 res = incl.find_reference(abs_target)
334 if res is not None:
335 return res
336 return None