ApplyPatchAction   A
last analyzed

Complexity

Total Complexity 17

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 58
rs 10
c 0
b 0
f 0
wmc 17

2 Methods

Rating   Name   Duplication   Size   Complexity  
B is_applicable() 0 14 5
F apply() 0 39 12
1
import shutil
2
from os.path import isfile
3
from os import remove
4
5
from coalib.results.Diff import ConflictError
6
from coalib.results.result_actions.ResultAction import ResultAction
7
8
9
class ApplyPatchAction(ResultAction):
10
11
    SUCCESS_MESSAGE = "Patch applied successfully."
12
13
    @staticmethod
14
    def is_applicable(result, original_file_dict, file_diff_dict):
15
        if not result.diffs:
16
            return False
17
18
        try:
19
            for filename in result.diffs:
20
                if filename in file_diff_dict:
21
                    result.diffs[filename].__add__(
22
                        file_diff_dict[filename])
23
24
            return True
25
        except ConflictError:
26
            return False
27
28
    def apply(self,
29
              result,
30
              original_file_dict,
31
              file_diff_dict,
32
              no_orig: bool=False):
33
        """
34
        Apply the patch automatically.
35
36
        :param no_orig: Whether or not to create .orig backup files
37
        """
38
        for filename in result.diffs:
39
            pre_patch_filename = filename
40
            if filename in file_diff_dict:
41
                diff = file_diff_dict[filename]
42
                pre_patch_filename = (diff.rename
43
                                      if diff.rename is not False
44
                                      else filename)
45
                file_diff_dict[filename] += result.diffs[filename]
46
            else:
47
                file_diff_dict[filename] = result.diffs[filename]
48
49
                # Backup original file, only if there was no previous patch
50
                # from this run though!
51
                if not no_orig and isfile(pre_patch_filename):
52
                    shutil.copy2(pre_patch_filename,
53
                                 pre_patch_filename + ".orig")
54
55
            diff = file_diff_dict[filename]
56
            if diff.delete or diff.rename:
57
                if isfile(pre_patch_filename):
58
                    remove(pre_patch_filename)
59
            if not diff.delete:
60
                new_filename = (diff.rename
61
                                if diff.rename is not False
62
                                else filename)
63
                with open(new_filename, mode='w', encoding='utf-8') as file:
64
                    file.writelines(diff.modified)
65
66
        return file_diff_dict
67