~abentley/bzrtools/bzrtools.dev

« back to all changes in this revision

Viewing changes to patches.py

Initial import

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2004, 2005 Aaron Bentley
 
2
# <aaron.bentley@utoronto.ca>
 
3
#
 
4
#    This program is free software; you can redistribute it and/or modify
 
5
#    it under the terms of the GNU General Public License as published by
 
6
#    the Free Software Foundation; either version 2 of the License, or
 
7
#    (at your option) any later version.
 
8
#
 
9
#    This program is distributed in the hope that it will be useful,
 
10
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
 
11
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
12
#    GNU General Public License for more details.
 
13
#
 
14
#    You should have received a copy of the GNU General Public License
 
15
#    along with this program; if not, write to the Free Software
 
16
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
17
import sys
 
18
class PatchSyntax(Exception):
 
19
    def __init__(self, msg):
 
20
        Exception.__init__(self, msg)
 
21
 
 
22
 
 
23
class MalformedPatchHeader(PatchSyntax):
 
24
    def __init__(self, desc, line):
 
25
        self.desc = desc
 
26
        self.line = line
 
27
        msg = "Malformed patch header.  %s\n%s" % (self.desc, self.line)
 
28
        PatchSyntax.__init__(self, msg)
 
29
 
 
30
class MalformedHunkHeader(PatchSyntax):
 
31
    def __init__(self, desc, line):
 
32
        self.desc = desc
 
33
        self.line = line
 
34
        msg = "Malformed hunk header.  %s\n%s" % (self.desc, self.line)
 
35
        PatchSyntax.__init__(self, msg)
 
36
 
 
37
class MalformedLine(PatchSyntax):
 
38
    def __init__(self, desc, line):
 
39
        self.desc = desc
 
40
        self.line = line
 
41
        msg = "Malformed line.  %s\n%s" % (self.desc, self.line)
 
42
        PatchSyntax.__init__(self, msg)
 
43
 
 
44
def get_patch_names(iter_lines):
 
45
    try:
 
46
        line = iter_lines.next()
 
47
        if line.startswith("*** "):
 
48
            line = iter_lines.next()
 
49
        if not line.startswith("--- "):
 
50
            raise MalformedPatchHeader("No orig name", line)
 
51
        else:
 
52
            orig_name = line[4:].rstrip("\n")
 
53
    except StopIteration:
 
54
        raise MalformedPatchHeader("No orig line", "")
 
55
    try:
 
56
        line = iter_lines.next()
 
57
        if not line.startswith("+++ "):
 
58
            raise PatchSyntax("No mod name")
 
59
        else:
 
60
            mod_name = line[4:].rstrip("\n")
 
61
    except StopIteration:
 
62
        raise MalformedPatchHeader("No mod line", "")
 
63
    return (orig_name, mod_name)
 
64
 
 
65
def parse_range(textrange):
 
66
    """Parse a patch range, handling the "1" special-case
 
67
 
 
68
    :param textrange: The text to parse
 
69
    :type textrange: str
 
70
    :return: the position and range, as a tuple
 
71
    :rtype: (int, int)
 
72
    """
 
73
    tmp = textrange.split(',')
 
74
    if len(tmp) == 1:
 
75
        pos = tmp[0]
 
76
        range = "1"
 
77
    else:
 
78
        (pos, range) = tmp
 
79
    pos = int(pos)
 
80
    range = int(range)
 
81
    return (pos, range)
 
82
 
 
83
 
 
84
def hunk_from_header(line):
 
85
    if not line.startswith("@@") or not line.endswith("@@\n") \
 
86
        or not len(line) > 4:
 
87
        raise MalformedHunkHeader("Does not start and end with @@.", line)
 
88
    try:
 
89
        (orig, mod) = line[3:-4].split(" ")
 
90
    except Exception, e:
 
91
        raise MalformedHunkHeader(str(e), line)
 
92
    if not orig.startswith('-') or not mod.startswith('+'):
 
93
        raise MalformedHunkHeader("Positions don't start with + or -.", line)
 
94
    try:
 
95
        (orig_pos, orig_range) = parse_range(orig[1:])
 
96
        (mod_pos, mod_range) = parse_range(mod[1:])
 
97
    except Exception, e:
 
98
        raise MalformedHunkHeader(str(e), line)
 
99
    if mod_range < 0 or orig_range < 0:
 
100
        raise MalformedHunkHeader("Hunk range is negative", line)
 
101
    return Hunk(orig_pos, orig_range, mod_pos, mod_range)
 
102
 
 
103
 
 
104
class HunkLine:
 
105
    def __init__(self, contents):
 
106
        self.contents = contents
 
107
 
 
108
    def get_str(self, leadchar):
 
109
        if self.contents == "\n" and leadchar == " " and False:
 
110
            return "\n"
 
111
        return leadchar + self.contents
 
112
 
 
113
class ContextLine(HunkLine):
 
114
    def __init__(self, contents):
 
115
        HunkLine.__init__(self, contents)
 
116
 
 
117
    def __str__(self):
 
118
        return self.get_str(" ")
 
119
 
 
120
 
 
121
class InsertLine(HunkLine):
 
122
    def __init__(self, contents):
 
123
        HunkLine.__init__(self, contents)
 
124
 
 
125
    def __str__(self):
 
126
        return self.get_str("+")
 
127
 
 
128
class RemoveLine(HunkLine):
 
129
    def __init__(self, contents):
 
130
        HunkLine.__init__(self, contents)
 
131
 
 
132
    def __str__(self):
 
133
        return self.get_str("-")
 
134
 
 
135
__pychecker__="no-returnvalues"
 
136
def parse_line(line):
 
137
    if line.startswith("\n"):
 
138
        return ContextLine(line)
 
139
    elif line.startswith(" "):
 
140
        return ContextLine(line[1:])
 
141
    elif line.startswith("+"):
 
142
        return InsertLine(line[1:])
 
143
    elif line.startswith("-"):
 
144
        return RemoveLine(line[1:])
 
145
    else:
 
146
        raise MalformedLine("Unknown line type", line)
 
147
__pychecker__=""
 
148
 
 
149
 
 
150
class Hunk:
 
151
    def __init__(self, orig_pos, orig_range, mod_pos, mod_range):
 
152
        self.orig_pos = orig_pos
 
153
        self.orig_range = orig_range
 
154
        self.mod_pos = mod_pos
 
155
        self.mod_range = mod_range
 
156
        self.lines = []
 
157
 
 
158
    def get_header(self):
 
159
        return "@@ -%s +%s @@\n" % (self.range_str(self.orig_pos, 
 
160
                                                   self.orig_range),
 
161
                                    self.range_str(self.mod_pos, 
 
162
                                                   self.mod_range))
 
163
 
 
164
    def range_str(self, pos, range):
 
165
        """Return a file range, special-casing for 1-line files.
 
166
 
 
167
        :param pos: The position in the file
 
168
        :type pos: int
 
169
        :range: The range in the file
 
170
        :type range: int
 
171
        :return: a string in the format 1,4 except when range == pos == 1
 
172
        """
 
173
        if range == 1:
 
174
            return "%i" % pos
 
175
        else:
 
176
            return "%i,%i" % (pos, range)
 
177
 
 
178
    def __str__(self):
 
179
        lines = [self.get_header()]
 
180
        for line in self.lines:
 
181
            lines.append(str(line))
 
182
        return "".join(lines)
 
183
 
 
184
    def shift_to_mod(self, pos):
 
185
        if pos < self.orig_pos-1:
 
186
            return 0
 
187
        elif pos > self.orig_pos+self.orig_range:
 
188
            return self.mod_range - self.orig_range
 
189
        else:
 
190
            return self.shift_to_mod_lines(pos)
 
191
 
 
192
    def shift_to_mod_lines(self, pos):
 
193
        assert (pos >= self.orig_pos-1 and pos <= self.orig_pos+self.orig_range)
 
194
        position = self.orig_pos-1
 
195
        shift = 0
 
196
        for line in self.lines:
 
197
            if isinstance(line, InsertLine):
 
198
                shift += 1
 
199
            elif isinstance(line, RemoveLine):
 
200
                if position == pos:
 
201
                    return None
 
202
                shift -= 1
 
203
                position += 1
 
204
            elif isinstance(line, ContextLine):
 
205
                position += 1
 
206
            if position > pos:
 
207
                break
 
208
        return shift
 
209
 
 
210
def iter_hunks(iter_lines):
 
211
    hunk = None
 
212
    for line in iter_lines:
 
213
        if line.startswith("@@"):
 
214
            if hunk is not None:
 
215
                yield hunk
 
216
            hunk = hunk_from_header(line)
 
217
        else:
 
218
            hunk.lines.append(parse_line(line))
 
219
 
 
220
    if hunk is not None:
 
221
        yield hunk
 
222
 
 
223
class Patch:
 
224
    def __init__(self, oldname, newname):
 
225
        self.oldname = oldname
 
226
        self.newname = newname
 
227
        self.hunks = []
 
228
 
 
229
    def __str__(self):
 
230
        ret =  "--- %s\n+++ %s\n" % (self.oldname, self.newname) 
 
231
        ret += "".join([str(h) for h in self.hunks])
 
232
        return ret
 
233
 
 
234
    def stats_str(self):
 
235
        """Return a string of patch statistics"""
 
236
        removes = 0
 
237
        inserts = 0
 
238
        for hunk in self.hunks:
 
239
            for line in hunk.lines:
 
240
                if isinstance(line, InsertLine):
 
241
                     inserts+=1;
 
242
                elif isinstance(line, RemoveLine):
 
243
                     removes+=1;
 
244
        return "%i inserts, %i removes in %i hunks" % \
 
245
            (inserts, removes, len(self.hunks))
 
246
 
 
247
    def pos_in_mod(self, position):
 
248
        newpos = position
 
249
        for hunk in self.hunks:
 
250
            shift = hunk.shift_to_mod(position)
 
251
            if shift is None:
 
252
                return None
 
253
            newpos += shift
 
254
        return newpos
 
255
            
 
256
    def iter_inserted(self):
 
257
        """Iteraties through inserted lines
 
258
        
 
259
        :return: Pair of line number, line
 
260
        :rtype: iterator of (int, InsertLine)
 
261
        """
 
262
        for hunk in self.hunks:
 
263
            pos = hunk.mod_pos - 1;
 
264
            for line in hunk.lines:
 
265
                if isinstance(line, InsertLine):
 
266
                    yield (pos, line)
 
267
                    pos += 1
 
268
                if isinstance(line, ContextLine):
 
269
                    pos += 1
 
270
 
 
271
def parse_patch(iter_lines):
 
272
    (orig_name, mod_name) = get_patch_names(iter_lines)
 
273
    patch = Patch(orig_name, mod_name)
 
274
    for hunk in iter_hunks(iter_lines):
 
275
        patch.hunks.append(hunk)
 
276
    return patch
 
277
 
 
278
def parse_patches(iter_lines):
 
279
    def parse(lines):
 
280
        if len(lines) > 0:
 
281
            return [ parse_patch(lines.__iter__()) ]
 
282
        else:
 
283
            return []
 
284
 
 
285
    patches = []
 
286
    saved_lines = []
 
287
    while True:
 
288
        try: line = iter_lines.next()
 
289
        except StopIteration:
 
290
            patches.extend(parse(saved_lines))
 
291
            break
 
292
 
 
293
        if line.startswith('*** '):
 
294
            patches.extend(parse(saved_lines))
 
295
            saved_lines = []
 
296
            continue
 
297
        elif line.startswith('--- ') and len(saved_lines) > 1:
 
298
            patches.extend(parse(saved_lines))
 
299
            saved_lines = [ line ]
 
300
            continue
 
301
 
 
302
        saved_lines.append(line)
 
303
 
 
304
    return patches