| 1 |
from __future__ import annotations |
| 2 |
from typing import Dict, Optional, Set, Tuple, cast |
| 3 |
|
| 4 |
import os |
| 5 |
import codecs |
| 6 |
from functools import partial |
| 7 |
import logging |
| 8 |
from itertools import zip_longest |
| 9 |
|
| 10 |
from compare_locales.parser import getParser |
| 11 |
from compare_locales.plurals import get_plural |
| 12 |
import fluent.syntax.ast as FTL |
| 13 |
from fluent.syntax.parser import FluentParser |
| 14 |
from fluent.syntax.serializer import FluentSerializer |
| 15 |
|
| 16 |
from .changesets import Changes |
| 17 |
from .errors import UnreadableReferenceError |
| 18 |
from .evaluator import Evaluator |
| 19 |
from .merge import merge_resource |
| 20 |
from .transforms import Source |
| 21 |
|
| 22 |
|
| 23 |
class InternalContext: |
| 24 |
"""Internal context for merging translation resources. |
| 25 |
|
| 26 |
For the public interface, see `context.MigrationContext`. |
| 27 |
""" |
| 28 |
|
| 29 |
dependencies: Dict[Tuple[str, str], Set[Tuple[str, Source]]] = {} |
| 30 |
localization_dir: str |
| 31 |
reference_dir: str |
| 32 |
|
| 33 |
def __init__(self, lang, enforce_translated=False): |
| 34 |
self.fluent_parser = FluentParser(with_spans=False) |
| 35 |
self.fluent_serializer = FluentSerializer() |
| 36 |
|
| 37 |
# An iterable of plural category names relevant to the context's |
| 38 |
# language. E.g. ('one', 'other') for English. |
| 39 |
self.plural_categories = get_plural(lang) |
| 40 |
if self.plural_categories is None: |
| 41 |
logger = logging.getLogger("migrate") |
| 42 |
logger.warning( |
| 43 |
f'Plural rule for "{lang}" is not defined in "compare-locales"' |
| 44 |
) |
| 45 |
self.plural_categories = ("one", "other") |
| 46 |
|
| 47 |
self.enforce_translated = enforce_translated |
| 48 |
# Parsed input resources stored by resource path. |
| 49 |
self.reference_resources = {} |
| 50 |
self.localization_resources = {} |
| 51 |
self.target_resources = {} |
| 52 |
|
| 53 |
# An iterable of `FTL.Message` objects some of whose nodes can be the |
| 54 |
# transform operations. |
| 55 |
self.transforms = {} |
| 56 |
|
| 57 |
# The evaluator instance is an AST transformer capable of walking an |
| 58 |
# AST hierarchy and evaluating nodes which are migration Transforms. |
| 59 |
self.evaluator = Evaluator(self) |
| 60 |
|
| 61 |
def read_ftl_resource(self, path: str): |
| 62 |
"""Read an FTL resource and parse it into an AST.""" |
| 63 |
f = codecs.open(path, "r", "utf8") |
| 64 |
try: |
| 65 |
contents = f.read() |
| 66 |
except UnicodeDecodeError as err: |
| 67 |
logger = logging.getLogger("migrate") |
| 68 |
logger.warning(f"Unable to read file {path}: {err}") |
| 69 |
raise err |
| 70 |
finally: |
| 71 |
f.close() |
| 72 |
|
| 73 |
ast = self.fluent_parser.parse(contents) |
| 74 |
|
| 75 |
annots = [ |
| 76 |
annot |
| 77 |
for entry in ast.body |
| 78 |
if isinstance(entry, FTL.Junk) |
| 79 |
for annot in entry.annotations |
| 80 |
] |
| 81 |
|
| 82 |
if len(annots): |
| 83 |
logger = logging.getLogger("migrate") |
| 84 |
for annot in annots: |
| 85 |
msg = annot.message |
| 86 |
logger.warning(f"Syntax error in {path}: {msg}") |
| 87 |
|
| 88 |
return ast |
| 89 |
|
| 90 |
def read_legacy_resource(self, path: str): |
| 91 |
"""Read a legacy resource and parse it into a dict.""" |
| 92 |
parser = getParser(path) |
| 93 |
parser.readFile(path) |
| 94 |
# Transform the parsed result which is an iterator into a dict. |
| 95 |
return { |
| 96 |
entity.key: entity.val |
| 97 |
for entity in parser |
| 98 |
if entity.localized or self.enforce_translated |
| 99 |
} |
| 100 |
|
| 101 |
def read_reference_ftl(self, path: str): |
| 102 |
"""Read and parse a reference FTL file. |
| 103 |
|
| 104 |
A missing resource file is a fatal error and will raise an |
| 105 |
UnreadableReferenceError. |
| 106 |
""" |
| 107 |
fullpath = os.path.join(self.reference_dir, path) |
| 108 |
try: |
| 109 |
return self.read_ftl_resource(fullpath) |
| 110 |
except OSError: |
| 111 |
error_message = f"Missing reference file: {fullpath}" |
| 112 |
logging.getLogger("migrate").error(error_message) |
| 113 |
raise UnreadableReferenceError(error_message) |
| 114 |
except UnicodeDecodeError as err: |
| 115 |
error_message = f"Error reading file {fullpath}: {err}" |
| 116 |
logging.getLogger("migrate").error(error_message) |
| 117 |
raise UnreadableReferenceError(error_message) |
| 118 |
|
| 119 |
def read_localization_ftl(self, path: str): |
| 120 |
"""Read and parse an existing localization FTL file. |
| 121 |
|
| 122 |
Create a new FTL.Resource if the file doesn't exist or can't be |
| 123 |
decoded. |
| 124 |
""" |
| 125 |
fullpath = os.path.join(self.localization_dir, path) |
| 126 |
try: |
| 127 |
return self.read_ftl_resource(fullpath) |
| 128 |
except OSError: |
| 129 |
logger = logging.getLogger("migrate") |
| 130 |
logger.info( |
| 131 |
"Localization file {} does not exist and " |
| 132 |
"it will be created".format(path) |
| 133 |
) |
| 134 |
return FTL.Resource() |
| 135 |
except UnicodeDecodeError: |
| 136 |
logger = logging.getLogger("migrate") |
| 137 |
logger.warning( |
| 138 |
"Localization file {} has broken encoding. " |
| 139 |
"It will be re-created and some translations " |
| 140 |
"may be lost".format(path) |
| 141 |
) |
| 142 |
return FTL.Resource() |
| 143 |
|
| 144 |
def maybe_add_localization(self, path: str): |
| 145 |
"""Add a localization resource to migrate translations from. |
| 146 |
|
| 147 |
Uses a compare-locales parser to create a dict of (key, string value) |
| 148 |
tuples. |
| 149 |
For Fluent sources, we store the AST. |
| 150 |
""" |
| 151 |
try: |
| 152 |
fullpath = os.path.join(self.localization_dir, path) |
| 153 |
if not fullpath.endswith(".ftl"): |
| 154 |
collection = self.read_legacy_resource(fullpath) |
| 155 |
else: |
| 156 |
collection = self.read_ftl_resource(fullpath) |
| 157 |
except OSError: |
| 158 |
logger = logging.getLogger("migrate") |
| 159 |
logger.warning(f"Missing localization file: {path}") |
| 160 |
else: |
| 161 |
self.localization_resources[path] = collection |
| 162 |
|
| 163 |
def get_legacy_source(self, path: str, key: str): |
| 164 |
"""Get an entity value from a localized legacy source. |
| 165 |
|
| 166 |
Used by the `Source` transform. |
| 167 |
""" |
| 168 |
resource = self.localization_resources[path] |
| 169 |
return resource.get(key, None) |
| 170 |
|
| 171 |
def get_fluent_source_pattern(self, path: str, key: str): |
| 172 |
"""Get a pattern from a localized Fluent source. |
| 173 |
|
| 174 |
If the key contains a `.`, does an attribute lookup. |
| 175 |
Used by the `COPY_PATTERN` transform. |
| 176 |
""" |
| 177 |
resource = self.localization_resources[path] |
| 178 |
msg_key, _, attr_key = key.partition(".") |
| 179 |
found = None |
| 180 |
for entry in resource.body: |
| 181 |
if isinstance(entry, (FTL.Message, FTL.Term)): |
| 182 |
if entry.id.name == msg_key: |
| 183 |
found = entry |
| 184 |
break |
| 185 |
if found is None: |
| 186 |
return None |
| 187 |
if not attr_key: |
| 188 |
return found.value |
| 189 |
for attribute in found.attributes: |
| 190 |
if attribute.id.name == attr_key: |
| 191 |
return attribute.value |
| 192 |
return None |
| 193 |
|
| 194 |
def messages_equal(self, res1, res2): |
| 195 |
"""Compare messages and terms of two FTL resources. |
| 196 |
|
| 197 |
Uses FTL.BaseNode.equals to compare all messages/terms |
| 198 |
in two FTL resources. |
| 199 |
If the order or number of messages differ, the result is also False. |
| 200 |
""" |
| 201 |
|
| 202 |
def message_id(message): |
| 203 |
"Return the message's identifer name for sorting purposes." |
| 204 |
return message.id.name |
| 205 |
|
| 206 |
messages1 = sorted( |
| 207 |
( |
| 208 |
entry |
| 209 |
for entry in res1.body |
| 210 |
if isinstance(entry, FTL.Message) or isinstance(entry, FTL.Term) |
| 211 |
), |
| 212 |
key=message_id, |
| 213 |
) |
| 214 |
messages2 = sorted( |
| 215 |
( |
| 216 |
entry |
| 217 |
for entry in res2.body |
| 218 |
if isinstance(entry, FTL.Message) or isinstance(entry, FTL.Term) |
| 219 |
), |
| 220 |
key=message_id, |
| 221 |
) |
| 222 |
for msg1, msg2 in zip_longest(messages1, messages2): |
| 223 |
if msg1 is None or msg2 is None: |
| 224 |
return False |
| 225 |
if not msg1.equals(msg2): |
| 226 |
return False |
| 227 |
return True |
| 228 |
|
| 229 |
def merge_changeset( |
| 230 |
self, |
| 231 |
changeset: Optional[Changes] = None, |
| 232 |
known_translations: Optional[Changes] = None, |
| 233 |
): |
| 234 |
"""Return a generator of FTL ASTs for the changeset. |
| 235 |
|
| 236 |
The input data must be configured earlier using the `add_*` methods. |
| 237 |
if given, `changeset` must be a set of (path, key) tuples describing |
| 238 |
which legacy translations are to be merged. If `changeset` is None, |
| 239 |
all legacy translations will be allowed to be migrated in a single |
| 240 |
changeset. |
| 241 |
|
| 242 |
We use the `in_changeset` method to determine if a message should be |
| 243 |
migrated for the given changeset. |
| 244 |
|
| 245 |
Given `changeset`, return a dict whose keys are resource paths and |
| 246 |
values are `FTL.Resource` instances. The values will also be used to |
| 247 |
update this context's existing localization resources. |
| 248 |
""" |
| 249 |
|
| 250 |
if changeset is None: |
| 251 |
# Merge all known legacy translations. Used in tests. |
| 252 |
changeset = { |
| 253 |
(path, key) |
| 254 |
for path, strings in self.localization_resources.items() |
| 255 |
if not path.endswith(".ftl") |
| 256 |
for key in strings.keys() |
| 257 |
} |
| 258 |
|
| 259 |
if known_translations is None: |
| 260 |
known_translations = changeset |
| 261 |
|
| 262 |
for path, reference in self.reference_resources.items(): |
| 263 |
current = self.target_resources[path] |
| 264 |
transforms = self.transforms.get(path, []) |
| 265 |
in_changeset = partial( |
| 266 |
self.in_changeset, changeset, known_translations, path |
| 267 |
) |
| 268 |
|
| 269 |
# Merge legacy translations with the existing ones using the |
| 270 |
# reference as a template. |
| 271 |
snapshot = merge_resource( |
| 272 |
self, reference, current, transforms, in_changeset |
| 273 |
) |
| 274 |
|
| 275 |
# Skip this path if the messages in the merged snapshot are |
| 276 |
# identical to those in the current state of the localization file. |
| 277 |
# This may happen when: |
| 278 |
# |
| 279 |
# - none of the transforms is in the changset, or |
| 280 |
# - all messages which would be migrated by the context's |
| 281 |
# transforms already exist in the current state. |
| 282 |
if self.messages_equal(current, snapshot): |
| 283 |
continue |
| 284 |
|
| 285 |
# Store the merged snapshot on the context so that the next merge |
| 286 |
# already takes it into account as the existing localization. |
| 287 |
self.target_resources[path] = snapshot |
| 288 |
|
| 289 |
# The result for this path is a complete `FTL.Resource`. |
| 290 |
yield path, snapshot |
| 291 |
|
| 292 |
def in_changeset( |
| 293 |
self, changeset: Changes, known_translations: Changes, path: str, ident |
| 294 |
) -> bool: |
| 295 |
"""Check if a message should be migrated in this changeset. |
| 296 |
|
| 297 |
The message is identified by path and ident. |
| 298 |
|
| 299 |
|
| 300 |
A message will be migrated only if all of its dependencies |
| 301 |
are present in the currently processed changeset. |
| 302 |
|
| 303 |
If a transform defined for this message points to a missing |
| 304 |
legacy translation, this message will not be merged. The |
| 305 |
missing legacy dependency won't be present in the changeset. |
| 306 |
|
| 307 |
This also means that partially translated messages (e.g. |
| 308 |
constructed from two legacy strings out of which only one is |
| 309 |
avaiable) will never be migrated. |
| 310 |
""" |
| 311 |
message_deps = self.dependencies.get((path, ident), None) |
| 312 |
|
| 313 |
# Don't merge if we don't have a transform for this message. |
| 314 |
if message_deps is None: |
| 315 |
return False |
| 316 |
|
| 317 |
# As a special case, if a transform exists but has no |
| 318 |
# dependecies, it's a hardcoded `FTL.Node` which doesn't |
| 319 |
# migrate any existing translation but rather creates a new |
| 320 |
# one. Merge it. |
| 321 |
if len(message_deps) == 0: |
| 322 |
return True |
| 323 |
|
| 324 |
# Make sure all the dependencies are present in the current |
| 325 |
# changeset. Partial migrations are not currently supported. |
| 326 |
# See https://bugzilla.mozilla.org/show_bug.cgi?id=1321271 |
| 327 |
# We only return True if our current changeset touches |
| 328 |
# the transform, and we have all of the dependencies. |
| 329 |
active_deps = cast(bool, message_deps & changeset) |
| 330 |
available_deps = message_deps & known_translations |
| 331 |
return active_deps and message_deps == available_deps |
| 332 |
|
| 333 |
def serialize_changeset( |
| 334 |
self, changeset: Changes, known_translations: Optional[Changes] = None |
| 335 |
): |
| 336 |
"""Return a dict of serialized FTLs for the changeset. |
| 337 |
|
| 338 |
Given `changeset`, return a dict whose keys are resource paths and |
| 339 |
values are serialized FTL snapshots. |
| 340 |
""" |
| 341 |
|
| 342 |
return { |
| 343 |
path: self.fluent_serializer.serialize(snapshot) |
| 344 |
for path, snapshot in self.merge_changeset(changeset, known_translations) |
| 345 |
} |
| 346 |
|
| 347 |
def evaluate(self, node): |
| 348 |
return self.evaluator.visit(node) |
| 349 |
|
| 350 |
|
| 351 |
logging.basicConfig() |