Debian Codegraph @

third_party/python/fluent.migrate/fluent/migrate/tool.py

raw
1 from __future__ import annotations
2 from types import ModuleType
3 from typing import Iterable, cast
4
5 import argparse
6 from contextlib import contextmanager
7 import importlib
8 import logging
9 import os
10 import sys
11
12 from fluent.migrate.blame import Blame
13 from fluent.migrate.changesets import Changes, convert_blame_to_changesets
14 from fluent.migrate.context import MigrationContext
15 from fluent.migrate.errors import MigrationError
16 from fluent.migrate.repo_client import RepoClient
17
18
19 @contextmanager
20 def dont_write_bytecode():
21 _dont_write_bytecode = sys.dont_write_bytecode
22 sys.dont_write_bytecode = True
23 yield
24 sys.dont_write_bytecode = _dont_write_bytecode
25
26
27 class Migrator:
28 def __init__(
29 self, locale: str, reference_dir: str, localization_dir: str, dry_run: bool
30 ):
31 self.locale = locale
32 self.reference_dir = reference_dir
33 self.localization_dir = localization_dir
34 self.dry_run = dry_run
35 self._client = None
36
37 @property
38 def client(self):
39 if self._client is None:
40 self._client = RepoClient(self.localization_dir)
41 return self._client
42
43 def close(self):
44 # close hglib.client, if we cached one.
45 if self._client is not None:
46 self._client.close()
47
48 def run(self, migration: ModuleType):
49 print("\nRunning migration {} for {}".format(migration.__name__, self.locale))
50
51 # For each migration create a new context.
52 ctx = MigrationContext(self.locale, self.reference_dir, self.localization_dir)
53
54 try:
55 # Add the migration spec.
56 migration.migrate(ctx)
57 except MigrationError as e:
58 print(
59 " Skipping migration {} for {}:\n {}".format(
60 migration.__name__, self.locale, e
61 )
62 )
63 return
64
65 # Keep track of how many changesets we're committing.
66 index = 0
67 description_template = cast(str, migration.migrate.__doc__)
68
69 # Annotate localization files used as sources by this migration
70 # to preserve attribution of translations.
71 files = ctx.localization_resources.keys()
72 blame = Blame(self.client).attribution(files)
73 changesets = convert_blame_to_changesets(blame)
74 known_legacy_translations = set()
75
76 for changeset in changesets:
77 snapshot = self.snapshot(
78 ctx, changeset["changes"], known_legacy_translations
79 )
80 if not snapshot:
81 continue
82 self.serialize_changeset(snapshot)
83 index += 1
84 self.commit_changeset(description_template, changeset["author"], index)
85
86 def snapshot(
87 self,
88 ctx: MigrationContext,
89 changes_in_changeset: Changes,
90 known_legacy_translations: Changes,
91 ):
92 """Run the migration for the changeset, with the set of
93 this and all prior legacy translations.
94 """
95 known_legacy_translations.update(changes_in_changeset)
96 return ctx.serialize_changeset(changes_in_changeset, known_legacy_translations)
97
98 def serialize_changeset(self, snapshot):
99 """Write serialized FTL files to disk."""
100 for path, content in snapshot.items():
101 fullpath = os.path.join(self.localization_dir, path)
102 print(f" Writing to {fullpath}")
103 if not self.dry_run:
104 fulldir = os.path.dirname(fullpath)
105 if not os.path.isdir(fulldir):
106 os.makedirs(fulldir)
107 with open(fullpath, "wb") as f:
108 f.write(content.encode("utf8"))
109 f.close()
110
111 def commit_changeset(self, description_template: str, author: str, index: int):
112 message = description_template.format(index=index, author=author)
113
114 print(f" Committing changeset: {message}")
115 if self.dry_run:
116 return
117 try:
118 self.client.commit(message, author)
119 except Exception as err:
120 print(f" WARNING: commit failed ({err})")
121
122
123 def main(
124 locale,
125 reference_dir: str,
126 localization_dir: str,
127 migrations: Iterable[ModuleType],
128 dry_run: bool,
129 ):
130 """Run migrations and commit files with the result."""
131 migrator = Migrator(locale, reference_dir, localization_dir, dry_run)
132
133 for migration in migrations:
134 migrator.run(migration)
135
136 migrator.close()
137
138
139 def cli():
140 parser = argparse.ArgumentParser(description="Migrate translations to FTL.")
141 parser.add_argument(
142 "migrations",
143 metavar="MIGRATION",
144 type=str,
145 nargs="+",
146 help="migrations to run (Python modules)",
147 )
148 parser.add_argument(
149 "--locale", "--lang", type=str, help="target locale code (--lang is deprecated)"
150 )
151 parser.add_argument(
152 "--reference-dir", type=str, help="directory with reference FTL files"
153 )
154 parser.add_argument(
155 "--localization-dir", type=str, help="directory for localization files"
156 )
157 parser.add_argument(
158 "--dry-run",
159 action="store_true",
160 help="do not write to disk nor commit any changes",
161 )
162 parser.set_defaults(dry_run=False)
163
164 logger = logging.getLogger("migrate")
165 logger.setLevel(logging.INFO)
166
167 args = parser.parse_args()
168
169 # Don't byte-compile migrations.
170 # They're not our code, and infrequently run
171 with dont_write_bytecode():
172 migrations = map(importlib.import_module, args.migrations)
173
174 main(
175 locale=args.locale,
176 reference_dir=args.reference_dir,
177 localization_dir=args.localization_dir,
178 migrations=migrations,
179 dry_run=args.dry_run,
180 )
181
182
183 if __name__ == "__main__":
184 cli()