Failed Conditions
Pull Request — master (#1093)
by Lasse
01:44
created

bears.natural_language.get_language_tool_results()   B

Complexity

Conditions 4

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 4
dl 0
loc 22
rs 8.9197
1
from language_check import LanguageTool, correct
2
3
from coalib.bears.LocalBear import LocalBear
4
from coalib.results.Result import Result
5
from coalib.results.Diff import Diff
6
from coalib.results.SourceRange import SourceRange
7
8
9
def get_language_tool_results(filename, file_contents, locale):
10
    tool = LanguageTool(locale)
11
    joined_text = "".join(file_contents)
12
    matches = tool.check(joined_text)
13
    for match in matches:
14
        if not match.replacements:
15
            diffs = None
16
        else:
17
            replaced = correct(joined_text, [match]).splitlines(True)
18
            diffs = {filename:
19
                     Diff.from_string_arrays(file_contents, replaced)}
20
21
        rule_id = match.ruleId
22
        if match.subId is not None:
23
            rule_id += '[{}]'.format(match.subId)
24
25
        message = match.msg + ' (' + rule_id + ')'
26
        yield message, diffs, SourceRange.from_values(filename,
27
                                                      match.fromy+1,
28
                                                      match.fromx+1,
29
                                                      match.toy+1,
30
                                                      match.tox+1)
31
32
33
class LanguageToolBear(LocalBear):
34
    def run(self,
35
            filename,
36
            file,
37
            locale: str='en-US'):
38
        '''
39
        Checks the code with LanguageTool.
40
41
        locale: A locale representing the language you want to have checked.
42
        '''
43
        for message, diffs, range in get_language_tool_results(
44
                filename, file, locale):
45
            yield Result(self, message, diffs=diffs, affected_code=(range,))
46