| 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 re |
| 18 |
from collections.abc import Iterable, Iterator |
| 19 |
from itertools import chain |
| 20 |
from os import sep, walk |
| 21 |
from os.path import commonpath, isdir, join, normpath, relpath, splitext |
| 22 |
|
| 23 |
from moz.l10n.resource.format import l10n_extensions |
| 24 |
from moz.l10n.util import walk_files |
| 25 |
|
| 26 |
locale_id = re.compile( |
| 27 |
r"[a-z]{2,3}(?:[-_][A-Z][a-z]{3})?(?:[-_][A-Z]{2})?|ca-valencia|ja-JP-mac" |
| 28 |
) |
| 29 |
|
| 30 |
|
| 31 |
def dir_contains(dir: str, path: str) -> bool: |
| 32 |
return commonpath((dir, path)) == dir |
| 33 |
|
| 34 |
|
| 35 |
def locale_dirname(base: str, locale: str) -> str: |
| 36 |
if "-" in locale and not isdir(join(base, locale)): |
| 37 |
alt_dir = locale.replace("-", "_") |
| 38 |
if isdir(join(base, alt_dir)): |
| 39 |
return alt_dir |
| 40 |
return locale |
| 41 |
|
| 42 |
|
| 43 |
class MissingSourceDirectoryError(Exception): |
| 44 |
"""Raised when no source directory can be found.""" |
| 45 |
|
| 46 |
|
| 47 |
class L10nDiscoverPaths: |
| 48 |
"""Automagical localization resource discovery""" |
| 49 |
|
| 50 |
base: str | None |
| 51 |
"""The target base directory, with subdirectories for each locale.""" |
| 52 |
locales: list[str] | None |
| 53 |
"""Locales detected from subdirectory names under `base`.""" |
| 54 |
ref_paths: list[str] |
| 55 |
"""Reference paths""" |
| 56 |
|
| 57 |
def __init__( |
| 58 |
self, |
| 59 |
root: str, |
| 60 |
ref_root: str | None = None, |
| 61 |
*, |
| 62 |
force_paths: list[str] | None = None, |
| 63 |
ignorepath: str | None = ".l10n-ignore", |
| 64 |
source_locale: str | list[str] | None = None, |
| 65 |
) -> None: |
| 66 |
""" |
| 67 |
Automagical localization resource discovery. |
| 68 |
|
| 69 |
Given a `root` directory, finds the likeliest reference and target directories. |
| 70 |
|
| 71 |
The reference directory has a name matching the `source_locale` |
| 72 |
and contains files with extensions that appear localizable. |
| 73 |
|
| 74 |
If `ref_root` is given, the reference directory must be within it. |
| 75 |
If it does not contain a directory matching `source_locale` |
| 76 |
but `ref_root` itself contains files with extensions that appear localizable, |
| 77 |
it is used as the reference directory. |
| 78 |
|
| 79 |
Use `force_paths` to list fully-qualified file paths to include |
| 80 |
as reference paths if they are within the reference directory, |
| 81 |
even if no file is present at those paths. |
| 82 |
|
| 83 |
The default `source_locale` is `['en-US', 'en']`, |
| 84 |
with earlier values taking priority. |
| 85 |
For the reference directory, an underscore may also be used as a separator and it may be all lower-case, |
| 86 |
such that a directory named `en_us` is considered to match a source locale `en-US`. |
| 87 |
|
| 88 |
The localization target root is a directory within `root` with subdirectories named as |
| 89 |
BCP 47 locale identifiers, i.e. like `aa`, `aa-AA`, `aa-Aaaa`, or `aa-Aaaa-AA`. |
| 90 |
|
| 91 |
To ignore files, include a `.l10n-ignore` file in the reference base directory |
| 92 |
or some other location passed in as `ignorepath`. |
| 93 |
This file uses git-ignore syntax, |
| 94 |
and is always based in the reference base directory. |
| 95 |
""" |
| 96 |
root = normpath(root) |
| 97 |
if not isdir(root): |
| 98 |
raise ValueError(f"Not a directory: {root}") |
| 99 |
if ref_root: |
| 100 |
ref_root = normpath(join(root, ref_root)) |
| 101 |
if source_locale is None: |
| 102 |
source_locale = ["en-US", "en"] |
| 103 |
elif isinstance(source_locale, str): |
| 104 |
source_locale = [source_locale] |
| 105 |
ref_dir_scores: dict[str, int] = { |
| 106 |
lc_var: idx |
| 107 |
for idx, lc in enumerate(source_locale) |
| 108 |
for lc_var in locale_code_variants(lc) |
| 109 |
} |
| 110 |
|
| 111 |
# dir -> score |
| 112 |
ref_dirs: dict[str, int] = {ref_root: len(source_locale)} if ref_root else {} |
| 113 |
base_dirs: list[tuple[str, list[str]]] = [] # [(root, [locale_dir])] |
| 114 |
pot_dirs: list[str] = [] |
| 115 |
l10n_dirs: list[str] = [] |
| 116 |
if ref_root and not dir_contains(root, ref_root): |
| 117 |
walk_roots: Iterator[tuple[str, list[str], list[str]]] = chain( |
| 118 |
walk(root), walk(ref_root) |
| 119 |
) |
| 120 |
else: |
| 121 |
walk_roots = walk(root) |
| 122 |
for dirpath, dirnames, filenames in walk_roots: |
| 123 |
locale_dirs = [] |
| 124 |
for dir in dirnames: |
| 125 |
if dir in ref_dir_scores: |
| 126 |
ref_dirs[join(dirpath, dir)] = ref_dir_scores[dir] |
| 127 |
elif locale_id.fullmatch(dir): |
| 128 |
locale_dirs.append(dir) |
| 129 |
if locale_dirs: |
| 130 |
base_dirs.append((dirpath, locale_dirs)) |
| 131 |
dirnames[:] = (dn for dn in dirnames if not dn.startswith(".")) |
| 132 |
|
| 133 |
if any(not fn.startswith(".") and fn.endswith(".pot") for fn in filenames): |
| 134 |
pot_dirs.append(dirpath) |
| 135 |
if any( |
| 136 |
not fn.startswith(".") and splitext(fn)[1] in l10n_extensions |
| 137 |
for fn in filenames |
| 138 |
): |
| 139 |
l10n_dirs.append(dirpath) |
| 140 |
|
| 141 |
if ref_root: |
| 142 |
for dir in list(ref_dirs): |
| 143 |
if not dir_contains(ref_root, dir): |
| 144 |
del ref_dirs[dir] |
| 145 |
|
| 146 |
# Filter reference dirs to those with localizable contents, |
| 147 |
# with a preference for .pot template files. |
| 148 |
ref_dirs_with_files = [ |
| 149 |
dir for dir in ref_dirs if any(dir_contains(dir, pd) for pd in pot_dirs) |
| 150 |
] or [dir for dir in ref_dirs if any(dir_contains(dir, ld) for ld in l10n_dirs)] |
| 151 |
if ref_dirs_with_files: |
| 152 |
self._ref_root = min( |
| 153 |
(rd for rd in ref_dirs.items() if rd[0] in ref_dirs_with_files), |
| 154 |
key=lambda s: s[1], |
| 155 |
)[0] |
| 156 |
else: |
| 157 |
raise MissingSourceDirectoryError |
| 158 |
|
| 159 |
# Pick the localization base dir not in the reference directory |
| 160 |
# with the most locale subdirectories, |
| 161 |
# with a preference for directories with localizable contents. |
| 162 |
base_dirs = [bd for bd in base_dirs if not dir_contains(self._ref_root, bd[0])] |
| 163 |
base_dirs = [ |
| 164 |
bd for bd in base_dirs if any(dir_contains(bd[0], ld) for ld in l10n_dirs) |
| 165 |
] or base_dirs |
| 166 |
|
| 167 |
locale_dirs_: list[str] | None |
| 168 |
self.base, locale_dirs_ = max( |
| 169 |
base_dirs, key=lambda s: len(s[1]), default=(None, None) |
| 170 |
) |
| 171 |
if locale_dirs_: |
| 172 |
self.locales = [dir.replace("_", "-") for dir in locale_dirs_] |
| 173 |
self.locales.sort() |
| 174 |
else: |
| 175 |
self.locales = None |
| 176 |
|
| 177 |
self.ref_paths = ( |
| 178 |
list(walk_files(self._ref_root, ignorepath=ignorepath)) |
| 179 |
if isdir(self._ref_root) |
| 180 |
else [] |
| 181 |
) |
| 182 |
if force_paths: |
| 183 |
self.ref_paths.extend( |
| 184 |
path for path in force_paths if dir_contains(self._ref_root, path) |
| 185 |
) |
| 186 |
|
| 187 |
@property |
| 188 |
def ref_root(self) -> str: |
| 189 |
"""The reference root directory.""" |
| 190 |
return self._ref_root |
| 191 |
|
| 192 |
def _base(self) -> str: |
| 193 |
if self.base is None: |
| 194 |
raise ValueError("self.base is required for target paths") |
| 195 |
return self.base |
| 196 |
|
| 197 |
def all(self) -> dict[tuple[str, str], list[str] | None]: |
| 198 |
""" |
| 199 |
Returns a mapping of `(reference_path, target_path)` to `locales` |
| 200 |
for all resources. |
| 201 |
|
| 202 |
Target paths will include a `{locale}` variable. |
| 203 |
""" |
| 204 |
locale_root = join(self._base(), "{locale}") |
| 205 |
paths: dict[tuple[str, str], list[str] | None] = {} |
| 206 |
for ref_path in self.ref_paths: |
| 207 |
target = ref_path.replace(self._ref_root, locale_root, 1) |
| 208 |
if target.endswith(".pot"): |
| 209 |
target = target[:-1] |
| 210 |
paths[(ref_path, target)] = self.locales |
| 211 |
return paths |
| 212 |
|
| 213 |
def target( |
| 214 |
self, ref_path: str, *, ref_required: bool = True |
| 215 |
) -> tuple[str | None, Iterable[str]]: |
| 216 |
""" |
| 217 |
If `ref_path` is a valid reference path, |
| 218 |
returns its corresponding target path. |
| 219 |
Otherwise, returns `None` for the path. |
| 220 |
|
| 221 |
Target path will include a `{locale}` variable. |
| 222 |
""" |
| 223 |
ref_path = normpath(join(self._ref_root, ref_path)) |
| 224 |
if ref_path.endswith(".po"): |
| 225 |
ref_path += "t" |
| 226 |
if ref_required and ref_path not in self.ref_paths: |
| 227 |
return None, () |
| 228 |
locale_root = join(self._base(), "{locale}") |
| 229 |
target = ref_path.replace(self._ref_root, locale_root, 1) |
| 230 |
if target.endswith(".pot"): |
| 231 |
target = target[:-1] |
| 232 |
return target, self.locales or () |
| 233 |
|
| 234 |
def format_target_path(self, target: str, locale: str) -> str: |
| 235 |
base = self._base() |
| 236 |
dir = locale_dirname(base, locale) |
| 237 |
return normpath(join(base, target.format(locale=dir))) |
| 238 |
|
| 239 |
def find_reference(self, target: str) -> tuple[str, dict[str, str]] | None: |
| 240 |
""" |
| 241 |
A reverse lookup for the reference path and locale matching `target`, |
| 242 |
or `None` if not found. |
| 243 |
|
| 244 |
The locale is returned as `{"locale": locale}` to match `L10nConfig`. |
| 245 |
""" |
| 246 |
base = self._base() |
| 247 |
locale, *path_parts = normpath(relpath(join(base, target), base)).split(sep) |
| 248 |
if path_parts and locale_id.fullmatch(locale): |
| 249 |
ref_path = join(self._ref_root, *path_parts) |
| 250 |
vars = {"locale": locale.replace("_", "-")} |
| 251 |
if ref_path in self.ref_paths: |
| 252 |
return ref_path, vars |
| 253 |
elif ref_path.endswith(".po") and ref_path + "t" in self.ref_paths: |
| 254 |
return ref_path + "t", vars |
| 255 |
return None |
| 256 |
|
| 257 |
|
| 258 |
def locale_code_variants(locale_code: str) -> Iterable[str]: |
| 259 |
yield locale_code |
| 260 |
yield locale_code.lower() |
| 261 |
lc_ = locale_code.replace("-", "_") |
| 262 |
yield lc_ |
| 263 |
yield lc_.lower() |