Completed
Pull Request — master (#2186)
by Udayan
01:54
created

OpenEditorAction.is_applicable()   B

Complexity

Conditions 5

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
c 0
b 0
f 0
dl 0
loc 12
rs 8.5454
1
import subprocess
2
from os.path import exists
3
4
from coalib.results.Diff import Diff
5
from coalib.results.Result import Result
6
from coalib.results.result_actions.ResultAction import ResultAction
7
8
EDITOR_ARGS = {
9
    "subl": "--wait",
10
    "gedit": "-s",
11
    "atom": "--wait"
12
}
13
14
15
GUI_EDITORS = ["kate", "gedit", "subl", "atom"]
16
17
18
class OpenEditorAction(ResultAction):
19
20
    SUCCESS_MESSAGE = "Changes saved successfully."
21
22
    @staticmethod
23
    def is_applicable(result, original_file_dict, file_diff_dict):
24
        """
25
        For being applicable, the result has to point to a number of files
26
        that have to exist i.e. have not been previously deleted.
27
        """
28
        if not isinstance(result, Result) or not len(result.affected_code) > 0:
29
            return False
30
31
        filenames = set(src.renamed_file(file_diff_dict)
32
                        for src in result.affected_code)
33
        return all(exists(filename) for filename in filenames)
34
35
    def apply(self, result, original_file_dict, file_diff_dict, editor: str):
36
        '''
37
        Open the affected file(s) in an editor.
38
39
        :param editor: The editor to open the file with.
40
        '''
41
        # Use set to remove duplicates
42
        filenames = {src.file: src.renamed_file(file_diff_dict)
43
                     for src in result.affected_code}
44
45
        editor_args = [editor] + list(filenames.values())
46
        arg = EDITOR_ARGS.get(editor.strip(), None)
47
        if arg:
48
            editor_args.append(arg)
49
50
        # Dear user, you wanted an editor, so you get it. But do you really
51
        # think you can do better than we?
52
        if editor in GUI_EDITORS:
53
            subprocess.call(editor_args, stdout=subprocess.PIPE)
54
        else:
55
            subprocess.call(editor_args)
56
57
        for original_name, filename in filenames.items():
58
            with open(filename, encoding='utf-8') as file:
59
                file_diff_dict[original_name] = Diff.from_string_arrays(
60
                    original_file_dict[original_name], file.readlines(),
61
                    rename=False if original_name == filename else filename)
62
63
        return file_diff_dict
64