14
14
# You should have received a copy of the GNU General Public License
15
15
# along with this program; if not, write to the Free Software
16
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
from __future__ import absolute_import
28
binary_files_re = b'Binary files (.*) and (.*) differ\n'
31
class PatchSyntax(BzrError):
32
"""Base class for patch syntax errors."""
35
class BinaryFiles(BzrError):
37
_fmt = 'Binary files section encountered.'
20
binary_files_re = 'Binary files (.*) and (.*) differ\n'
23
class BinaryFiles(Exception):
39
25
def __init__(self, orig_name, mod_name):
40
26
self.orig_name = orig_name
41
27
self.mod_name = mod_name
28
Exception.__init__(self, 'Binary files section encountered.')
31
class PatchSyntax(Exception):
32
def __init__(self, msg):
33
Exception.__init__(self, msg)
44
36
class MalformedPatchHeader(PatchSyntax):
46
_fmt = "Malformed patch header. %(desc)s\n%(line)r"
48
def __init__(self, desc, line):
37
def __init__(self, desc, line):
40
msg = "Malformed patch header. %s\n%r" % (self.desc, self.line)
41
PatchSyntax.__init__(self, msg)
44
class MalformedHunkHeader(PatchSyntax):
45
def __init__(self, desc, line):
48
msg = "Malformed hunk header. %s\n%r" % (self.desc, self.line)
49
PatchSyntax.__init__(self, msg)
53
52
class MalformedLine(PatchSyntax):
55
_fmt = "Malformed line. %(desc)s\n%(line)r"
57
53
def __init__(self, desc, line):
62
class PatchConflict(BzrError):
64
_fmt = ('Text contents mismatch at line %(line_no)d. Original has '
65
'"%(orig_line)s", but patch says it should be "%(patch_line)s"')
56
msg = "Malformed line. %s\n%s" % (self.desc, self.line)
57
PatchSyntax.__init__(self, msg)
60
class PatchConflict(Exception):
67
61
def __init__(self, line_no, orig_line, patch_line):
68
self.line_no = line_no
69
self.orig_line = orig_line.rstrip('\n')
70
self.patch_line = patch_line.rstrip('\n')
73
class MalformedHunkHeader(PatchSyntax):
75
_fmt = "Malformed hunk header. %(desc)s\n%(line)r"
77
def __init__(self, desc, line):
62
orig = orig_line.rstrip('\n')
63
patch = str(patch_line).rstrip('\n')
64
msg = 'Text contents mismatch at line %d. Original has "%s",'\
65
' but patch says it should be "%s"' % (line_no, orig, patch)
66
Exception.__init__(self, msg)
82
69
def get_patch_names(iter_lines):
83
line = next(iter_lines)
71
line = iter_lines.next()
85
72
match = re.match(binary_files_re, line)
86
73
if match is not None:
87
74
raise BinaryFiles(match.group(1), match.group(2))
88
if not line.startswith(b"--- "):
75
if not line.startswith("--- "):
89
76
raise MalformedPatchHeader("No orig name", line)
91
orig_name = line[4:].rstrip(b"\n")
78
orig_name = line[4:].rstrip("\n")
92
79
except StopIteration:
93
80
raise MalformedPatchHeader("No orig line", "")
95
line = next(iter_lines)
96
if not line.startswith(b"+++ "):
82
line = iter_lines.next()
83
if not line.startswith("+++ "):
97
84
raise PatchSyntax("No mod name")
99
mod_name = line[4:].rstrip(b"\n")
86
mod_name = line[4:].rstrip("\n")
100
87
except StopIteration:
101
88
raise MalformedPatchHeader("No mod line", "")
102
89
return (orig_name, mod_name)
124
111
def hunk_from_header(line):
126
matches = re.match(br'\@\@ ([^@]*) \@\@( (.*))?\n', line)
113
matches = re.match(r'\@\@ ([^@]*) \@\@( (.*))?\n', line)
127
114
if matches is None:
128
115
raise MalformedHunkHeader("Does not match format.", line)
130
(orig, mod) = matches.group(1).split(b" ")
131
except (ValueError, IndexError) as e:
117
(orig, mod) = matches.group(1).split(" ")
118
except (ValueError, IndexError), e:
132
119
raise MalformedHunkHeader(str(e), line)
133
if not orig.startswith(b'-') or not mod.startswith(b'+'):
120
if not orig.startswith('-') or not mod.startswith('+'):
134
121
raise MalformedHunkHeader("Positions don't start with + or -.", line)
136
123
(orig_pos, orig_range) = parse_range(orig[1:])
137
124
(mod_pos, mod_range) = parse_range(mod[1:])
138
except (ValueError, IndexError) as e:
125
except (ValueError, IndexError), e:
139
126
raise MalformedHunkHeader(str(e), line)
140
127
if mod_range < 0 or orig_range < 0:
141
128
raise MalformedHunkHeader("Hunk range is negative", line)
143
130
return Hunk(orig_pos, orig_range, mod_pos, mod_range, tail)
146
class HunkLine(object):
148
134
def __init__(self, contents):
149
135
self.contents = contents
151
137
def get_str(self, leadchar):
152
if self.contents == b"\n" and leadchar == b" " and False:
154
if not self.contents.endswith(b'\n'):
155
terminator = b'\n' + NO_NL
138
if self.contents == "\n" and leadchar == " " and False:
140
if not self.contents.endswith('\n'):
141
terminator = '\n' + NO_NL
158
144
return leadchar + self.contents + terminator
161
raise NotImplementedError
164
147
class ContextLine(HunkLine):
166
148
def __init__(self, contents):
167
149
HunkLine.__init__(self, contents)
170
return self.get_str(b" ")
152
return self.get_str(" ")
173
155
class InsertLine(HunkLine):
174
156
def __init__(self, contents):
175
157
HunkLine.__init__(self, contents)
178
return self.get_str(b"+")
160
return self.get_str("+")
181
163
class RemoveLine(HunkLine):
182
164
def __init__(self, contents):
183
165
HunkLine.__init__(self, contents)
186
return self.get_str(b"-")
168
return self.get_str("-")
188
NO_NL = b'\\ No newline at end of file\n'
170
NO_NL = '\\ No newline at end of file\n'
189
171
__pychecker__="no-returnvalues"
191
173
def parse_line(line):
192
if line.startswith(b"\n"):
174
if line.startswith("\n"):
193
175
return ContextLine(line)
194
elif line.startswith(b" "):
176
elif line.startswith(" "):
195
177
return ContextLine(line[1:])
196
elif line.startswith(b"+"):
178
elif line.startswith("+"):
197
179
return InsertLine(line[1:])
198
elif line.startswith(b"-"):
180
elif line.startswith("-"):
199
181
return RemoveLine(line[1:])
201
183
raise MalformedLine("Unknown line type", line)
207
188
def __init__(self, orig_pos, orig_range, mod_pos, mod_range, tail=None):
208
189
self.orig_pos = orig_pos
209
190
self.orig_range = orig_range
407
387
# (as allow_dirty does).
408
388
regex = re.compile(binary_files_re)
414
392
for line in iter_lines:
415
if line.startswith(b'=== '):
416
if len(saved_lines) > 0:
417
if keep_dirty and len(dirty_head) > 0:
418
yield {'saved_lines': saved_lines,
419
'dirty_head': dirty_head}
424
dirty_head.append(line)
426
if line.startswith(b'*** '):
428
if line.startswith(b'#'):
393
if line.startswith('=== ') or line.startswith('*** '):
395
if line.startswith('#'):
430
397
elif orig_range > 0:
431
if line.startswith(b'-') or line.startswith(b' '):
398
if line.startswith('-') or line.startswith(' '):
433
elif line.startswith(b'--- ') or regex.match(line):
400
elif line.startswith('--- ') or regex.match(line):
434
401
if allow_dirty and beginning:
435
402
# Patches can have "junk" at the beginning
436
403
# Stripping junk from the end of patches is handled when we
437
404
# parse the patch
438
405
beginning = False
439
406
elif len(saved_lines) > 0:
440
if keep_dirty and len(dirty_head) > 0:
441
yield {'saved_lines': saved_lines,
442
'dirty_head': dirty_head}
447
elif line.startswith(b'@@'):
409
elif line.startswith('@@'):
448
410
hunk = hunk_from_header(line)
449
411
orig_range = hunk.orig_range
450
412
saved_lines.append(line)
451
413
if len(saved_lines) > 0:
452
if keep_dirty and len(dirty_head) > 0:
453
yield {'saved_lines': saved_lines,
454
'dirty_head': dirty_head}
459
417
def iter_lines_handle_nl(iter_lines):
480
def parse_patches(iter_lines, allow_dirty=False, keep_dirty=False):
438
def parse_patches(iter_lines, allow_dirty=False):
482
440
:arg iter_lines: iterable of lines to parse for patches
483
441
:kwarg allow_dirty: If True, allow text that's not part of the patch at
484
442
selected places. This includes comments before and after a patch
485
443
for instance. Default False.
486
:kwarg keep_dirty: If True, returns a dict of patches with dirty headers.
489
for patch_lines in iter_file_patch(iter_lines, allow_dirty, keep_dirty):
490
if 'dirty_head' in patch_lines:
491
yield ({'patch': parse_patch(patch_lines['saved_lines'], allow_dirty),
492
'dirty_head': patch_lines['dirty_head']})
494
yield parse_patch(patch_lines, allow_dirty)
445
return [parse_patch(f.__iter__(), allow_dirty) for f in
446
iter_file_patch(iter_lines, allow_dirty)]
497
449
def difference_index(atext, btext):