Completed
Pull Request — master (#1401)
by Abdeali
01:47
created

bears.python.PyImportSortBear   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 52
Duplicated Lines 0 %
Metric Value
dl 0
loc 52
rs 10
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
B run() 0 32 2
A run_isort() 0 14 2
1
from isort import SortImports
2
3
from coalib.bearlib.abstractions.CorrectionBasedBear import CorrectionBasedBear
4
from coalib.bearlib.spacing.SpacingHelper import SpacingHelper
5
6
7
class PyImportSortBear(CorrectionBasedBear):
8
    RESULT_MESSAGE = "Imports can be sorted."
9
10
    @staticmethod
11
    def run_isort(file,
12
                  use_spaces,
13
                  max_line_length,
14
                  indent_size,
15
                  use_parentheses_in_import,
16
                  isort_multi_line_output):
17
        indent = "Tab" if use_spaces == False else indent_size
18
        new_file = SortImports(file_contents=''.join(file),
19
                               line_length=max_line_length,
20
                               indent=indent,
21
                               multi_line_output=isort_multi_line_output,
22
                               use_parentheses=use_parentheses_in_import).output
23
        return new_file.splitlines(True), []
24
25
    GET_REPLACEMENT = run_isort
26
27
    def run(self,
28
            filename,
29
            file,
30
            use_spaces: bool=True,
31
            tab_width: int=SpacingHelper.DEFAULT_TAB_WIDTH,
32
            max_line_length: int=80,
33
            use_parentheses_in_import: bool=True,
34
            isort_multi_line_output: int=4):
35
        """
36
        Sorts imports for python.
37
38
        :param use_spaces:                True if spaces are to be used
39
                                          instead of tabs.
40
        :param tab_width:                 Number of spaces per indent level.
41
        :param max_line_length:           Maximum number of characters for
42
                                          a line.
43
        :param use_parentheses_in_import: True if parenthesis are to be used
44
                                          in import statements.
45
        :param isort_multi_line_output:   The type of formatting to be used by
46
                                          isort when indenting imports. This
47
                                          value if passed to isort as the
48
                                          `multi_line_output` setting.
49
        """
50
        for result in self.retrieve_results(
51
                  filename,
52
                  file,
53
                  use_spaces=use_spaces,
54
                  indent_size=tab_width,
55
                  max_line_length=max_line_length,
56
                  use_parentheses_in_import=use_parentheses_in_import,
57
                  isort_multi_line_output=isort_multi_line_output):
58
            yield result
59