Completed
Pull Request — master (#2201)
by Lasse
01:49
created

print_from_name()   A

Complexity

Conditions 1

Size

Total Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
c 0
b 0
f 0
dl 0
loc 2
rs 10
1
import difflib
2
from os.path import relpath, join
3
4
from pyprint.ConsolePrinter import ConsolePrinter
5
6
from coalib.results.Diff import ConflictError
7
from coalib.results.Result import Result
8
from coalib.results.result_actions.ResultAction import ResultAction
9
10
11
def format_line(line, real_nr="", sign="|", mod_nr="", symbol="", ):
12
    return "|{:>4}{}{:>4}|{:1}{}".format(real_nr,
13
                                         sign,
14
                                         mod_nr,
15
                                         symbol,
16
                                         line.rstrip("\n"))
17
18
19
def print_from_name(printer, line):
20
    printer.print(format_line(line, real_nr="----"), color="red")
21
22
23
def print_to_name(printer, line):
24
    printer.print(format_line(line, mod_nr="++++"), color="green")
25
26
27
def print_beautified_diff(difflines, printer):
28
    current_line_added = None
29
    current_line_subtracted = None
30
    for line in difflines:
31
        if line.startswith("@@"):
32
            values = line[line.find("-"):line.rfind(" ")]
33
            subtracted, added = tuple(values.split(" "))
34
            current_line_added = int(added.split(",")[0][1:])
35
            current_line_subtracted = int(subtracted.split(",")[0][1:])
36
        elif line.startswith("---"):
37
            print_from_name(printer, line[4:])
38
        elif line.startswith("+++"):
39
            print_to_name(printer, line[4:])
40
        elif line.startswith("+"):
41
            printer.print(format_line(line[1:],
42
                                      mod_nr=current_line_added,
43
                                      symbol="+"),
44
                          color="green")
45
            current_line_added += 1
46
        elif line.startswith("-"):
47
            printer.print(format_line(line[1:],
48
                                      real_nr=current_line_subtracted,
49
                                      symbol="-"),
50
                          color="red")
51
            current_line_subtracted += 1
52
        else:
53
            printer.print(format_line(line[1:],
54
                                      real_nr=current_line_subtracted,
55
                                      mod_nr=current_line_added,
56
                                      symbol=" "))
57
            current_line_subtracted += 1
58
            current_line_added += 1
59
60
61
class ShowPatchAction(ResultAction):
62
63
    SUCCESS_MESSAGE = "Displayed patch successfully."
64
65
    @staticmethod
66
    def is_applicable(result, original_file_dict, file_diff_dict):
67
        if not isinstance(result, Result) or not result.diffs:
68
            return False
69
70
        try:
71
            for filename in result.diffs:
72
                if filename in file_diff_dict:
73
                    result.diffs[filename].__add__(file_diff_dict[filename])
74
            return True
75
        except ConflictError:
76
            return False
77
78
    def apply(self,
79
              result,
80
              original_file_dict,
81
              file_diff_dict,
82
              colored: bool=True):
83
        '''
84
        Print a diff of the patch that would be applied.
85
86
        :param colored: Wether or not to use colored output.
87
        '''
88
        printer = ConsolePrinter(colored)
89
90
        for filename, this_diff in sorted(result.diffs.items()):
91
            to_filename = this_diff.rename if this_diff.rename else filename
92
            to_filename = "/dev/null" if this_diff.delete else to_filename
93
            original_file = original_file_dict[filename]
94
            try:
95
                current_file = file_diff_dict[filename].modified
96
                new_file = (file_diff_dict[filename] + this_diff).modified
97
            except KeyError:
98
                current_file = original_file
99
                new_file = this_diff.modified
100
101
            if tuple(current_file) != tuple(new_file):
102
                print_beautified_diff(difflib.unified_diff(current_file,
103
                                                           new_file,
104
                                                           fromfile=filename,
105
                                                           tofile=to_filename),
106
                                      printer)
107
            elif filename != to_filename:
108
                print_from_name(printer, join('a', relpath(filename)))
109
                print_to_name(printer, join('b', relpath(to_filename)))
110
111
        return file_diff_dict
112