Debian Codegraph @

third_party/python/fluent.migrate/fluent/migrate/merge.py

raw
1 import fluent.syntax.ast as FTL
2
3 from .errors import SkipTransform
4 from .util import get_message, get_transform
5
6
7 def merge_resource(ctx, reference, current, transforms, in_changeset):
8 """Transform legacy translations into FTL.
9
10 Use the `reference` FTL AST as a template. For each en-US string in the
11 reference, first check for an existing translation in the current FTL
12 `localization` and use it if it's present; then if the string has
13 a transform defined in the migration specification and if it's in the
14 currently processed changeset, evaluate the transform.
15 """
16
17 def merge_body(body):
18 return [entry for entry in map(merge_entry, body) if entry is not None]
19
20 def merge_entry(entry):
21 # All standalone comments will be merged.
22 if isinstance(entry, FTL.BaseComment):
23 return entry
24
25 # Ignore Junk
26 if isinstance(entry, FTL.Junk):
27 return None
28
29 ident = entry.id.name
30
31 # If the message is present in the existing localization, we add it to
32 # the resulting resource. This ensures consecutive merges don't remove
33 # translations but rather create supersets of them.
34 existing = get_message(current.body, ident)
35 if existing is not None:
36 return existing
37
38 transform = get_transform(transforms, ident)
39
40 # Make sure this message is supposed to be migrated as part of the
41 # current changeset.
42 if transform is not None and in_changeset(ident):
43 if transform.comment is None:
44 transform.comment = entry.comment
45 try:
46 return ctx.evaluate(transform)
47 except SkipTransform:
48 return None
49
50 body = merge_body(reference.body)
51 return FTL.Resource(body)