Debian Codegraph @

third_party/python/moz.l10n/moz/l10n/bin/fix.py

raw
1 #!/usr/bin/env python
2
3 # Copyright Mozilla Foundation
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 from __future__ import annotations
18
19 import logging
20 import sys
21 from argparse import ArgumentParser, RawDescriptionHelpFormatter
22 from collections.abc import Iterable
23 from enum import Enum
24 from glob import glob
25 from os import getcwd
26 from os.path import abspath, isdir, relpath
27 from textwrap import dedent
28
29 from moz.l10n.paths.config import L10nConfigPaths
30 from moz.l10n.paths.discover import L10nDiscoverPaths
31 from moz.l10n.resource import UnsupportedResource, parse_resource, serialize_resource
32
33 log = logging.getLogger(__name__)
34
35 Result = Enum("Result", ("OK", "FIXED", "UNSUPPORTED", "FAIL"))
36
37
38 def cli() -> None:
39 parser = ArgumentParser(
40 description=dedent(
41 """
42 Fix the formatting for localization resources.
43
44 If `paths` is a single directory, it is iterated with L10nConfigPaths if --config is set, or L10nDiscoverPaths otherwise.
45
46 If `paths` is not a single directory, its values are treated as glob expressions, with ** support.
47 """
48 ),
49 formatter_class=RawDescriptionHelpFormatter,
50 )
51 parser.add_argument("-q", "--quiet", action="store_true", help="only log errors")
52 parser.add_argument(
53 "-v", "--verbose", action="count", default=0, help="increase logging verbosity"
54 )
55 parser.add_argument(
56 "--config", metavar="PATH", type=str, help="path to l10n.toml config file"
57 )
58 parser.add_argument(
59 "--continue",
60 action="store_true",
61 dest="continue_on_error",
62 help="do not stop at first parse error",
63 )
64 parser.add_argument("paths", nargs="*", type=str, help="directory or files to fix")
65 args = parser.parse_args()
66
67 log_level = (
68 logging.ERROR
69 if args.quiet
70 else (
71 logging.WARNING
72 if args.verbose == 0
73 else logging.INFO
74 if args.verbose == 1
75 else logging.DEBUG
76 )
77 )
78 logging.basicConfig(format="%(message)s", level=log_level)
79
80 res = fix(args.paths, args.config, args.continue_on_error)
81 sys.exit(res)
82
83
84 def fix(
85 file_paths: list[str],
86 config_path: str | None = None,
87 continue_on_error: bool = False,
88 ) -> int:
89 """
90 Fix the formatting for `file_paths` localization resources.
91
92 If a single directory is given,
93 it is iterated with `L10nConfigPaths` if `config_path` is set,
94 or `L10nDiscoverPaths` otherwise.
95
96 If `file_paths` is not a single directory,
97 the paths are treated as glob expressions.
98
99 If `continue_on_error` is not set, operation terminates on the first error.
100
101 Returns 0 on success, 1 on parse error, or 2 on argument error.
102 """
103 if config_path:
104 if file_paths:
105 log.error("With --config, paths must not be set.")
106 return 2
107 cfg_paths = L10nConfigPaths(config_path)
108 root_dir = abspath(cfg_paths.base)
109 path_iter: Iterable[str] = cfg_paths.ref_paths
110 elif len(file_paths) == 1 and isdir(file_paths[0]):
111 root_dir = abspath(file_paths[0])
112 path_iter = L10nDiscoverPaths(root_dir, ref_root=".").ref_paths
113 elif file_paths:
114 root_dir = getcwd()
115 path_iter = (path for fp in file_paths for path in glob(fp, recursive=True))
116 else:
117 log.error("Either paths of --config is required")
118 return 2
119
120 fixed = 0
121 unsupported = 0
122 failed = 0
123 total = 0
124 for path in path_iter:
125 res = fix_file(root_dir, path)
126 total += 1
127 if res == Result.FIXED:
128 fixed += 1
129 elif res == Result.UNSUPPORTED:
130 unsupported += 1
131 elif res == Result.FAIL:
132 failed += 1
133 if not continue_on_error:
134 break
135
136 log.warning("")
137 if unsupported > 0:
138 log.warning(plural(f"Skipped {unsupported} unsupported file", unsupported))
139 touched = total - unsupported
140 if touched == 0:
141 log.warning("Found no localization resources")
142 else:
143 log.warning(plural(f"Fixed {fixed}/{touched} file", touched))
144 if failed > 0:
145 log.warning(plural(f"With {failed} parse failure", failed))
146 return 0 if failed == 0 else 1
147
148
149 def fix_file(root: str, path: str) -> Result:
150 rel_path = relpath(path, root)
151 try:
152 with open(path, "+rb") as file:
153 prev = file.read()
154 res = parse_resource(path, prev)
155 next = bytearray()
156 for line in serialize_resource(res):
157 next.extend(line.encode("utf-8"))
158 if next == prev:
159 log.info(f"OK: {rel_path}")
160 return Result.OK
161 else:
162 file.seek(0)
163 file.write(next)
164 file.truncate()
165 log.warning(f"Fixed: {rel_path}")
166 return Result.FIXED
167 except (UnsupportedResource, UnicodeDecodeError):
168 log.info(f"Skip: {rel_path}")
169 return Result.UNSUPPORTED
170 except Exception as error:
171 log.error(f"FAIL: {rel_path}\n{error}")
172 return Result.FAIL
173
174
175 def plural(noun: str, count: int) -> str:
176 """Hacky and English-only"""
177 return noun if count == 1 else noun + "s"
178
179
180 if __name__ == "__main__":
181 cli()