Debian Codegraph @

third_party/python/fluent.migrate/fluent/migrate/validator.py

raw
1 import argparse
2 import ast
3 from itertools import zip_longest
4
5 from fluent.migrate import transforms
6 from fluent.migrate.errors import MigrationError
7 from fluent.migrate.helpers import transforms_from
8 from fluent.syntax.visitor import Visitor
9 from compare_locales import mozpath
10
11
12 class MigrateNotFoundException(Exception):
13 pass
14
15
16 class BadContextAPIException(Exception):
17 pass
18
19
20 def process_assign(node, context):
21 if isinstance(node.value, ast.Constant):
22 val = node.value.value
23 elif isinstance(node.value, ast.Name):
24 val = context.get(node.value.id)
25 elif isinstance(node.value, ast.Call):
26 val = node.value
27 else:
28 val = None
29 if val is None:
30 return
31 for target in node.targets:
32 if isinstance(target, ast.Name):
33 context[target.id] = val
34
35
36 class Validator:
37 """Validate a migration recipe
38
39 Extract information from the migration recipe about which files to
40 migrate from, and which files to migrate to.
41 Also check for errors in the recipe, or bad API usage.
42 """
43
44 @classmethod
45 def validate(cls, path, code=None):
46 if code is None:
47 with open(path) as fh:
48 code = fh.read()
49 validator = cls(code, path)
50 return validator.inspect()
51
52 def __init__(self, code, path):
53 self.ast = ast.parse(code, path)
54
55 def inspect(self):
56 migrate_func = None
57 global_assigns = {}
58 for top_level in ast.iter_child_nodes(self.ast):
59 if isinstance(top_level, ast.FunctionDef) and top_level.name == "migrate":
60 if migrate_func:
61 raise MigrateNotFoundException("Duplicate definition of migrate")
62 migrate_func = top_level
63 details = self.inspect_migrate(migrate_func, global_assigns)
64 if isinstance(top_level, ast.Assign):
65 process_assign(top_level, global_assigns)
66 if isinstance(top_level, (ast.Import, ast.ImportFrom)):
67 if "module" in top_level._fields:
68 module = top_level.module
69 else:
70 module = None
71 for alias in top_level.names:
72 asname = alias.asname or alias.name
73 dotted = alias.name
74 if module:
75 dotted = f"{module}.{dotted}"
76 global_assigns[asname] = dotted
77 if not migrate_func:
78 raise MigrateNotFoundException("migrate function not found")
79 return details
80
81 def inspect_migrate(self, migrate_func, global_assigns):
82 if len(migrate_func.args.args) != 1 or any(
83 getattr(migrate_func.args, arg_field)
84 for arg_field in migrate_func.args._fields
85 if arg_field != "args"
86 ):
87 raise MigrateNotFoundException("migrate takes only one positional argument")
88 arg = migrate_func.args.args[0]
89 if isinstance(arg, ast.Name):
90 ctx_var = arg.id # python 2
91 else:
92 ctx_var = arg.arg # python 3
93 visitor = MigrateAnalyzer(ctx_var, global_assigns)
94 visitor.visit(migrate_func)
95 return {
96 "references": visitor.references,
97 "issues": visitor.issues,
98 }
99
100
101 def full_name(node, global_assigns):
102 leafs = []
103 while isinstance(node, ast.Attribute):
104 leafs.append(node.attr)
105 node = node.value
106 if isinstance(node, ast.Name):
107 leafs.append(global_assigns.get(node.id, node.id))
108 return ".".join(reversed(leafs))
109
110
111 PATH_TYPES = (str,) + (ast.Call,)
112
113
114 class MigrateAnalyzer(ast.NodeVisitor):
115 def __init__(self, ctx_var, global_assigns):
116 super().__init__()
117 self.ctx_var = ctx_var
118 self.global_assigns = global_assigns
119 self.depth = 0
120 self.issues = []
121 self.references = set()
122
123 def generic_visit(self, node):
124 self.depth += 1
125 super().generic_visit(node)
126 self.depth -= 1
127
128 def visit_Assign(self, node):
129 if self.depth == 1:
130 process_assign(node, self.global_assigns)
131 self.generic_visit(node)
132
133 def visit_Attribute(self, node):
134 if isinstance(node.value, ast.Name) and node.value.id == self.ctx_var:
135 if node.attr not in (
136 "add_transforms",
137 "locale",
138 ):
139 raise BadContextAPIException(
140 "Unexpected attribute access on {}.{}".format(
141 self.ctx_var, node.attr
142 )
143 )
144 self.generic_visit(node)
145
146 def visit_Call(self, node):
147 if (
148 isinstance(node.func, ast.Attribute)
149 and isinstance(node.func.value, ast.Name)
150 and node.func.value.id == self.ctx_var
151 ):
152 return self.call_ctx(node)
153 dotted = full_name(node.func, self.global_assigns)
154 if dotted == "fluent.migrate.helpers.transforms_from":
155 return self.call_helpers_transforms_from(node)
156 if dotted.startswith("fluent.migrate."):
157 return self.call_transform(node, dotted)
158 self.generic_visit(node)
159
160 def call_ctx(self, node):
161 if node.func.attr == "add_transforms":
162 return self.call_add_transforms(node)
163 raise BadContextAPIException(
164 "Unexpected call on {}.{}".format(self.ctx_var, node.func.attr)
165 )
166
167 def call_add_transforms(self, node):
168 args_msg = (
169 "Expected arguments to {}.add_transforms: "
170 "target_ftl_path, reference_ftl_path, list_of_transforms"
171 ).format(self.ctx_var)
172 ref_msg = (
173 "Expected second argument to {}.add_transforms: "
174 "reference should be string or variable with string value"
175 ).format(self.ctx_var)
176 # Just check call signature here, check actual types below
177 if not self.check_arguments(node, (ast.AST, ast.AST, ast.AST)):
178 self.issues.append(
179 {
180 "msg": args_msg,
181 "line": node.lineno,
182 }
183 )
184 return
185 in_reference = node.args[1]
186 if isinstance(in_reference, ast.Name):
187 in_reference = self.global_assigns.get(in_reference.id)
188 if isinstance(in_reference, ast.Constant):
189 in_reference = in_reference.value
190 if not isinstance(in_reference, str):
191 self.issues.append(
192 {
193 "msg": ref_msg,
194 "line": node.args[1].lineno,
195 }
196 )
197 return
198 self.references.add(in_reference)
199 # Checked node.args[1].
200 # There's not a lot we can say about our target path,
201 # ignoring that.
202 # For our transforms, we want more checks.
203 self.generic_visit(node.args[2])
204
205 def call_transform(self, node, dotted):
206 module, called = dotted.rsplit(".", 1)
207 if module not in ("fluent.migrate", "fluent.migrate.transforms"):
208 return
209 transform = getattr(transforms, called)
210 if not issubclass(transform, transforms.Source):
211 return
212 bad_args = f"{called} takes path and key as first two params"
213 if not self.check_arguments(
214 node,
215 (
216 (ast.Constant, ast.Name),
217 (ast.Constant, ast.Name),
218 ),
219 allow_more=True,
220 check_kwargs=False,
221 ):
222 self.issues.append({"msg": bad_args, "line": node.lineno})
223 return
224 path = node.args[0]
225 if isinstance(path, ast.Constant):
226 path = path.value
227 if isinstance(path, ast.Name):
228 path = self.global_assigns.get(path.id)
229 if not isinstance(path, PATH_TYPES):
230 self.issues.append({"msg": bad_args, "line": node.lineno})
231
232 def call_helpers_transforms_from(self, node):
233 args_msg = "Expected arguments to transforms_from: " "str, **substitions"
234 if not self.check_arguments(node, (ast.Constant,), check_kwargs=False):
235 self.issues.append(
236 {
237 "msg": args_msg,
238 "line": node.lineno,
239 }
240 )
241 return
242 kwargs = {}
243 found_bad_keywords = False
244 for keyword in node.keywords:
245 v = keyword.value
246 if isinstance(v, ast.Constant):
247 v = v.value
248 if isinstance(v, ast.Name):
249 v = self.global_assigns.get(v.id)
250 if isinstance(v, ast.Call):
251 v = "determined at runtime"
252 if not isinstance(v, PATH_TYPES):
253 msg = "Bad keyword arg {} to transforms_from".format(keyword.arg)
254 self.issues.append(
255 {
256 "msg": msg,
257 "line": node.lineno,
258 }
259 )
260 found_bad_keywords = True
261 else:
262 kwargs[keyword.arg] = v
263 if found_bad_keywords:
264 return
265 try:
266 transforms = transforms_from(node.args[0].value, **kwargs)
267 except MigrationError as e:
268 self.issues.append(
269 {
270 "msg": str(e),
271 "line": node.lineno,
272 }
273 )
274 return
275 ti = TransformsInspector()
276 ti.visit(transforms)
277 self.issues.extend(
278 {
279 "msg": issue,
280 "line": node.lineno,
281 }
282 for issue in set(ti.issues)
283 )
284
285 def check_arguments(self, node, argspec, check_kwargs=True, allow_more=False):
286 if check_kwargs and (
287 node.keywords or (hasattr(node, "kwargs") and node.kwargs)
288 ):
289 return False
290 if hasattr(node, "starargs") and node.starargs:
291 return False
292 for arg, NODE_TYPE in zip_longest(node.args, argspec):
293 if NODE_TYPE is None:
294 return True if allow_more else False
295 if not (isinstance(arg, NODE_TYPE)):
296 return False
297 return True
298
299
300 class TransformsInspector(Visitor):
301 def __init__(self):
302 super().__init__()
303 self.issues = []
304
305 def generic_visit(self, node):
306 if isinstance(node, transforms.Source):
307 src = node.path
308 # Source needs paths to be normalized
309 # https://bugzilla.mozilla.org/show_bug.cgi?id=1568199
310 if src != mozpath.normpath(src):
311 self.issues.append(f'Source "{src}" needs to be a normalized path')
312 super().generic_visit(node)
313
314
315 def cli():
316 parser = argparse.ArgumentParser()
317 parser.add_argument("migration")
318 args = parser.parse_args()
319 issues = Validator.validate(args.migration)["issues"]
320 for issue in issues:
321 print(issue["msg"], "at line", issue["line"])
322 return 1 if issues else 0