|
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, override old backup if needed |
|
50
|
|
|
if (not no_orig and |
|
51
|
|
|
isfile(pre_patch_filename) and |
|
52
|
|
|
not isfile(pre_patch_filename + ".orig")): |
|
53
|
|
|
shutil.copy2(pre_patch_filename, pre_patch_filename + ".orig") |
|
54
|
|
|
|
|
55
|
|
|
diff = file_diff_dict[filename] |
|
56
|
|
|
if diff.delete: |
|
57
|
|
|
if isfile(pre_patch_filename): |
|
58
|
|
|
remove(pre_patch_filename) |
|
59
|
|
|
else: |
|
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
|
|
|
|