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