Skip to content

Reference

Define all the orchestration functionality required by the program to work.

Classes and functions that connect the different domain model objects with the adapters and handlers to achieve the program's purpose.

fix_code(original_source_code, config=None, keep_unused_imports=False)

Fix python source code to correct import statements.

It corrects these errors
  • Add missed import statements.
  • Remove unused import statements.
  • Move import statements to the top.

Parameters:

Name Type Description Default
original_source_code str

Source code to be corrected.

required
keep_unused_imports bool

If true, unused imports are retained.

False

Returns:

Type Description
str

Corrected source code.

Source code in autoimport/services.py
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
def fix_code(
    original_source_code: str,
    config: Optional[Dict[str, Any]] = None,
    keep_unused_imports: bool = False,
) -> str:
    """Fix python source code to correct import statements.

    It corrects these errors:

        * Add missed import statements.
        * Remove unused import statements.
        * Move import statements to the top.

    Args:
        original_source_code: Source code to be corrected.
        keep_unused_imports: If true, unused imports are retained.

    Returns:
        Corrected source code.
    """
    return SourceCode(
        original_source_code, config=config, keep_unused_imports=keep_unused_imports
    ).fix()

fix_files(files, config=None, keep_unused_imports=False)

Fix the python source code of a list of files.

If the input is taken from stdin, it will output the value to stdout.

Parameters:

Name Type Description Default
files Tuple[TextIOWrapper, ...]

List of files to fix.

required

Returns:

Type Description
Optional[str]

Fixed code retrieved from stdin or None.

Source code in autoimport/services.py
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
def fix_files(
    files: Tuple[TextIOWrapper, ...],
    config: Optional[Dict[str, Any]] = None,
    keep_unused_imports: bool = False,
) -> Optional[str]:
    """Fix the python source code of a list of files.

    If the input is taken from stdin, it will output the value to stdout.

    Args:
        files: List of files to fix.

    Returns:
        Fixed code retrieved from stdin or None.
    """
    for file_wrapper in files:
        source = file_wrapper.read()
        fixed_source = fix_code(source, config, keep_unused_imports)

        if fixed_source == source and file_wrapper.name != "<stdin>":
            continue

        try:
            # Click testing runner doesn't simulate correctly the reading from stdin
            # instead of setting the name attribute to `<stdin>` it gives an
            # AttributeError. But when you use it outside testing, no AttributeError
            # is raised and name has the value <stdin>. So there is no way of testing
            # this behaviour.
            if file_wrapper.name == "<stdin>":  # pragma no cover
                output = "output"
            else:
                output = "file"
        except AttributeError:
            output = "output"

        if output == "file":
            file_wrapper.seek(0)
            file_wrapper.write(fixed_source)
            file_wrapper.truncate()
            file_wrapper.close()
        else:
            return fixed_source

    return None

Define the different ways to expose the program functionality.

Functions

load_logger(verbose=False)

Configure the Logging logger.

Parameters:

Name Type Description Default
verbose bool

Set the logging level to Debug.

False
Source code in autoimport/entrypoints/__init__.py
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
def load_logger(verbose: bool = False) -> None:  # pragma no cover
    """Configure the Logging logger.

    Args:
        verbose: Set the logging level to Debug.
    """
    logging.addLevelName(logging.INFO, "[\033[36m+\033[0m]")
    logging.addLevelName(logging.ERROR, "[\033[31m+\033[0m]")
    logging.addLevelName(logging.DEBUG, "[\033[32m+\033[0m]")
    logging.addLevelName(logging.WARNING, "[\033[33m+\033[0m]")
    if verbose:
        logging.basicConfig(
            stream=sys.stderr, level=logging.DEBUG, format="  %(levelname)s %(message)s"
        )
    else:
        logging.basicConfig(
            stream=sys.stderr, level=logging.INFO, format="  %(levelname)s %(message)s"
        )

Utilities to retrieve the information of the program version.

version_info()

Display the version of the program, python and the platform.

Source code in autoimport/version.py
12
13
14
15
16
17
18
19
20
21
def version_info() -> str:
    """Display the version of the program, python and the platform."""
    return dedent(
        f"""\
        ------------------------------------------------------------------
             autoimport: {__version__}
             Python: {sys.version.split(" ", maxsplit=1)[0]}
             Platform: {platform.platform()}
        ------------------------------------------------------------------"""
    )