Works like `does_tree_import` but adds an import statement if it was not imported.
(package, name, node)
| 313 | return node.type in (syms.import_name, syms.import_from) |
| 314 | |
| 315 | def touch_import(package, name, node): |
| 316 | """ Works like `does_tree_import` but adds an import statement |
| 317 | if it was not imported. """ |
| 318 | def is_import_stmt(node): |
| 319 | return (node.type == syms.simple_stmt and node.children and |
| 320 | is_import(node.children[0])) |
| 321 | |
| 322 | root = find_root(node) |
| 323 | |
| 324 | if does_tree_import(package, name, root): |
| 325 | return |
| 326 | |
| 327 | # figure out where to insert the new import. First try to find |
| 328 | # the first import and then skip to the last one. |
| 329 | insert_pos = offset = 0 |
| 330 | for idx, node in enumerate(root.children): |
| 331 | if not is_import_stmt(node): |
| 332 | continue |
| 333 | for offset, node2 in enumerate(root.children[idx:]): |
| 334 | if not is_import_stmt(node2): |
| 335 | break |
| 336 | insert_pos = idx + offset |
| 337 | break |
| 338 | |
| 339 | # if there are no imports where we can insert, find the docstring. |
| 340 | # if that also fails, we stick to the beginning of the file |
| 341 | if insert_pos == 0: |
| 342 | for idx, node in enumerate(root.children): |
| 343 | if (node.type == syms.simple_stmt and node.children and |
| 344 | node.children[0].type == token.STRING): |
| 345 | insert_pos = idx + 1 |
| 346 | break |
| 347 | |
| 348 | if package is None: |
| 349 | import_ = Node(syms.import_name, [ |
| 350 | Leaf(token.NAME, "import"), |
| 351 | Leaf(token.NAME, name, prefix=" ") |
| 352 | ]) |
| 353 | else: |
| 354 | import_ = FromImport(package, [Leaf(token.NAME, name, prefix=" ")]) |
| 355 | |
| 356 | children = [import_, Newline()] |
| 357 | root.insert_child(insert_pos, Node(syms.simple_stmt, children)) |
| 358 | |
| 359 | |
| 360 | _def_syms = {syms.classdef, syms.funcdef} |
no test coverage detected