Debian Codegraph @

third_party/python/fluent.migrate/fluent/migrate/context.py

raw
1 from __future__ import annotations
2 from typing import List, Set, Tuple, cast
3
4 import logging
5
6 import fluent.syntax.ast as FTL
7 from fluent.migrate.util import fold
8
9 from .transforms import Source
10 from .util import get_message, skeleton
11 from .errors import (
12 EmptyLocalizationError,
13 UnreadableReferenceError,
14 )
15 from ._context import InternalContext
16
17
18 __all__ = [
19 "EmptyLocalizationError",
20 "UnreadableReferenceError",
21 "MigrationContext",
22 ]
23
24
25 class MigrationContext(InternalContext):
26 """Stateful context for merging translation resources.
27
28 `MigrationContext` must be configured with the target locale and the
29 directory locations of the input data.
30
31 The transformation takes four types of input data:
32
33 - The en-US FTL reference files which will be used as templates for
34 message order, comments and sections. If the reference_dir is None,
35 the migration will create Messages and Terms in the order given by
36 the transforms.
37
38 - The current FTL files for the given locale.
39
40 - A list of `FTL.Message` or `FTL.Term` objects some of whose nodes
41 are special helper or transform nodes:
42
43 helpers: VARIABLE_REFERENCE, MESSAGE_REFERENCE, TERM_REFERENCE
44 transforms: COPY, REPLACE_IN_TEXT, REPLACE, PLURALS, CONCAT
45 fluent value helper: COPY_PATTERN
46
47 The legacy (DTD, properties) translation files are deduced by the
48 dependencies in the transforms. The translations from these files will be
49 read from the localization_dir and transformed into FTL and merged
50 into the existing FTL files for the given language.
51 """
52
53 def __init__(
54 self,
55 locale: str,
56 reference_dir: str,
57 localization_dir: str,
58 enforce_translated=False,
59 ):
60 super().__init__(
61 locale,
62 enforce_translated=enforce_translated,
63 )
64 self.locale = locale
65 # Paths to directories with input data, relative to CWD.
66 self.reference_dir = reference_dir
67 self.localization_dir = localization_dir
68
69 self.dependencies = {}
70 """
71 A dict whose keys are `(path, key)` tuples corresponding to target
72 FTL translations, and values are sets of `(path, key)` tuples
73 corresponding to localized entities which will be migrated.
74 """
75
76 def add_transforms(
77 self, target: str, reference: str, transforms: List[FTL.Message | FTL.Term]
78 ):
79 """Define transforms for target using reference as template.
80
81 `target` is a path of the destination FTL file relative to the
82 localization directory. `reference` is a path to the template FTL
83 file relative to the reference directory.
84
85 Each transform is an extended FTL node with `Transform` nodes as some
86 values. Transforms are stored in their lazy AST form until
87 `merge_changeset` is called, at which point they are evaluated to real
88 FTL nodes with migrated translations.
89
90 Each transform is scanned for `Source` nodes which will be used to
91 build the list of dependencies for the transformed message.
92
93 For transforms that merely copy legacy messages or Fluent patterns,
94 using `fluent.migrate.helpers.transforms_from` is recommended.
95 """
96
97 def get_sources(acc, cur):
98 if isinstance(cur, Source):
99 acc.add((cur.path, cur.key))
100 return acc
101
102 if self.reference_dir is None:
103 # Add skeletons to resource body for each transform
104 # if there's no reference.
105 reference_ast = self.reference_resources.get(target)
106 if reference_ast is None:
107 reference_ast = FTL.Resource()
108 reference_ast.body.extend(skeleton(transform) for transform in transforms)
109 else:
110 reference_ast = self.read_reference_ftl(reference)
111 self.reference_resources[target] = reference_ast
112
113 for node in transforms:
114 ident = cast(str, node.id.name)
115 # Scan `node` for `Source` nodes and collect the information they
116 # store into a set of dependencies.
117 dependencies = cast(Set[Tuple[str, Source]], fold(get_sources, node, set()))
118 # Set these sources as dependencies for the current transform.
119 self.dependencies[(target, ident)] = dependencies
120
121 # The target Fluent message should exist in the reference file. If
122 # it doesn't, it's probably a typo.
123 # Of course, only if we're having a reference.
124 if self.reference_dir is None:
125 continue
126 if get_message(reference_ast.body, ident) is None:
127 logger = logging.getLogger("migrate")
128 logger.warning(
129 '{} "{}" was not found in {}'.format(
130 type(node).__name__, ident, reference
131 )
132 )
133
134 # Keep track of localization resource paths which were defined as
135 # sources in the transforms.
136 expected_paths = set()
137
138 # Read all legacy translation files defined in Source transforms. This
139 # may fail but a single missing legacy resource doesn't mean that the
140 # migration can't succeed.
141 for dependencies in self.dependencies.values():
142 for path in {path for path, _ in dependencies}:
143 expected_paths.add(path)
144 self.maybe_add_localization(path)
145
146 # However, if all legacy resources are missing, bail out early. There
147 # are no translations to migrate. We'd also get errors in hg annotate.
148 if len(expected_paths) > 0 and len(self.localization_resources) == 0:
149 error_message = "No localization files were found"
150 logging.getLogger("migrate").error(error_message)
151 raise EmptyLocalizationError(error_message)
152
153 # Add the current transforms to any other transforms added earlier for
154 # this path.
155 path_transforms = self.transforms.setdefault(target, [])
156 path_transforms += transforms
157
158 if target not in self.target_resources:
159 target_ast = self.read_localization_ftl(target)
160 self.target_resources[target] = target_ast