Completed
Pull Request — master (#1406)
by Lasse
01:45
created

bears.python.PyImportSortBear   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 42
Duplicated Lines 0 %
Metric Value
dl 0
loc 42
rs 10
wmc 3

1 Method

Rating   Name   Duplication   Size   Complexity  
B run() 0 40 3
1
from isort import SortImports
2
3
from coalib.bearlib.spacing.SpacingHelper import SpacingHelper
4
from coalib.bears.LocalBear import LocalBear
5
from coalib.results.Diff import Diff
6
from coalib.results.Result import Result
7
8
9
class PyImportSortBear(LocalBear):
10
11
    def run(self,
12
            filename,
13
            file,
14
            use_spaces: bool=True,
15
            tab_width: int=SpacingHelper.DEFAULT_TAB_WIDTH,
16
            max_line_length: int=80,
17
            use_parentheses_in_import: bool=True,
18
            sort_imports_by_length: bool=False,
19
            isort_multi_line_output: int=4):
20
        """
21
        Sorts imports for python.
22
23
        :param use_spaces:                True if spaces are to be used
24
                                          instead of tabs.
25
        :param tab_width:                 Number of spaces per indent level.
26
        :param max_line_length:           Maximum number of characters for
27
                                          a line.
28
        :param use_parentheses_in_import: True if parenthesis are to be used
29
                                          in import statements.
30
        :param sort_imports_by_length:    Set to true to sort imports by length
31
                                          instead of alphabetically.
32
        :param isort_multi_line_output:   The type of formatting to be used by
33
                                          isort when indenting imports. This
34
                                          value if passed to isort as the
35
                                          `multi_line_output` setting.
36
        """
37
        indent = "Tab" if use_spaces == False else tab_width
38
        new_file = SortImports(
39
            file_contents=''.join(file),
40
            line_length=max_line_length,
41
            indent=indent,
42
            multi_line_output=isort_multi_line_output,
43
            use_parentheses=use_parentheses_in_import,
44
            length_sort=sort_imports_by_length).output.splitlines(True)
45
        if new_file != file:
46
            diff = Diff.from_string_arrays(file, new_file)
47
            yield Result(self,
48
                         "Imports can be sorted.",
49
                         affected_code=diff.affected_code(filename),
50
                         diffs={filename: diff})
51