Completed
Pull Request — master (#1073)
by Lasse
01:56
created

bears.NaturalLanguage.LanguageToolBear.run()   A

Complexity

Conditions 2

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 2
dl 0
loc 12
rs 9.4286
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: Diff.from_string_arrays(file_contents, replaced)}
19
20
        rule_id = match.ruleId
21
        if match.subId is not None:
22
            rule_id += '[{}]'.format(match.subId)
23
24
        message = match.msg + ' (' + rule_id + ')'
25
        yield message, diffs, SourceRange.from_values(filename,
26
                                                      match.fromy+1,
27
                                                      match.fromx+1,
28
                                                      match.toy+1,
29
                                                      match.tox+1)
30
31
32
class LanguageToolBear(LocalBear):
33
    def run(self,
34
            filename,
35
            file,
36
            locale: str='en-US'):
37
        '''
38
        Checks the code with LanguageTool.
39
40
        locale: A locale representing the language you want to have checked.
41
        '''
42
        for message, diffs, range in get_language_tool_results(
43
                filename, file, locale):
44
            yield Result(self, message, diffs=diffs, affected_code=(range,))
45