File: ensure_import_present.py

package info (click to toggle)
python-libcst 1.8.6-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,240 kB
  • sloc: python: 78,096; makefile: 15; sh: 2
file content (59 lines) | stat: -rw-r--r-- 1,870 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
#
import argparse
from typing import Generator, Type

from libcst.codemod import Codemod, MagicArgsCodemodCommand
from libcst.codemod.visitors import AddImportsVisitor


class EnsureImportPresentCommand(MagicArgsCodemodCommand):
    DESCRIPTION: str = (
        "Given a module and possibly an entity in that module, add an import "
        + "as long as one does not already exist."
    )

    @staticmethod
    def add_args(arg_parser: argparse.ArgumentParser) -> None:
        arg_parser.add_argument(
            "--module",
            dest="module",
            metavar="MODULE",
            help="Module that should be imported.",
            type=str,
            required=True,
        )
        arg_parser.add_argument(
            "--entity",
            dest="entity",
            metavar="ENTITY",
            help=(
                "Entity that should be imported from module. If left empty, entire "
                + " module will be imported."
            ),
            type=str,
            default=None,
        )
        arg_parser.add_argument(
            "--alias",
            dest="alias",
            metavar="ALIAS",
            help=(
                "Alias that will be used for the imported module or entity. If left "
                + "empty, no alias will be applied."
            ),
            type=str,
            default=None,
        )

    def get_transforms(self) -> Generator[Type[Codemod], None, None]:
        AddImportsVisitor.add_needed_import(
            self.context,
            self.context.scratch["module"],
            self.context.scratch["entity"],
            self.context.scratch["alias"],
        )
        yield AddImportsVisitor