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
20
from bzrlib.errors import (
32
binary_files_re = 'Binary files (.*) and (.*) differ\n'
26
binary_files_re = b'Binary files (.*) and (.*) differ\n'
29
class PatchSyntax(BzrError):
30
"""Base class for patch syntax errors."""
33
class BinaryFiles(BzrError):
35
_fmt = 'Binary files section encountered.'
37
def __init__(self, orig_name, mod_name):
38
self.orig_name = orig_name
39
self.mod_name = mod_name
42
class MalformedPatchHeader(PatchSyntax):
44
_fmt = "Malformed patch header. %(desc)s\n%(line)r"
46
def __init__(self, desc, line):
51
class MalformedLine(PatchSyntax):
53
_fmt = "Malformed line. %(desc)s\n%(line)r"
55
def __init__(self, desc, line):
60
class PatchConflict(BzrError):
62
_fmt = ('Text contents mismatch at line %(line_no)d. Original has '
63
'"%(orig_line)s", but patch says it should be "%(patch_line)s"')
65
def __init__(self, line_no, orig_line, patch_line):
66
self.line_no = line_no
67
self.orig_line = orig_line.rstrip('\n')
68
self.patch_line = patch_line.rstrip('\n')
71
class MalformedHunkHeader(PatchSyntax):
73
_fmt = "Malformed hunk header. %(desc)s\n%(line)r"
75
def __init__(self, desc, line):
35
80
def get_patch_names(iter_lines):
36
line = iter_lines.next()
81
line = next(iter_lines)
38
83
match = re.match(binary_files_re, line)
39
84
if match is not None:
40
85
raise BinaryFiles(match.group(1), match.group(2))
41
if not line.startswith("--- "):
86
if not line.startswith(b"--- "):
42
87
raise MalformedPatchHeader("No orig name", line)
44
orig_name = line[4:].rstrip("\n")
89
orig_name = line[4:].rstrip(b"\n")
45
90
except StopIteration:
46
91
raise MalformedPatchHeader("No orig line", "")
48
line = iter_lines.next()
49
if not line.startswith("+++ "):
93
line = next(iter_lines)
94
if not line.startswith(b"+++ "):
50
95
raise PatchSyntax("No mod name")
52
mod_name = line[4:].rstrip("\n")
97
mod_name = line[4:].rstrip(b"\n")
53
98
except StopIteration:
54
99
raise MalformedPatchHeader("No mod line", "")
55
100
return (orig_name, mod_name)
77
122
def hunk_from_header(line):
79
matches = re.match(r'\@\@ ([^@]*) \@\@( (.*))?\n', line)
124
matches = re.match(br'\@\@ ([^@]*) \@\@( (.*))?\n', line)
80
125
if matches is None:
81
126
raise MalformedHunkHeader("Does not match format.", line)
83
(orig, mod) = matches.group(1).split(" ")
84
except (ValueError, IndexError), e:
128
(orig, mod) = matches.group(1).split(b" ")
129
except (ValueError, IndexError) as e:
85
130
raise MalformedHunkHeader(str(e), line)
86
if not orig.startswith('-') or not mod.startswith('+'):
131
if not orig.startswith(b'-') or not mod.startswith(b'+'):
87
132
raise MalformedHunkHeader("Positions don't start with + or -.", line)
89
134
(orig_pos, orig_range) = parse_range(orig[1:])
90
135
(mod_pos, mod_range) = parse_range(mod[1:])
91
except (ValueError, IndexError), e:
136
except (ValueError, IndexError) as e:
92
137
raise MalformedHunkHeader(str(e), line)
93
138
if mod_range < 0 or orig_range < 0:
94
139
raise MalformedHunkHeader("Hunk range is negative", line)
96
141
return Hunk(orig_pos, orig_range, mod_pos, mod_range, tail)
144
class HunkLine(object):
100
146
def __init__(self, contents):
101
147
self.contents = contents
103
149
def get_str(self, leadchar):
104
if self.contents == "\n" and leadchar == " " and False:
106
if not self.contents.endswith('\n'):
107
terminator = '\n' + NO_NL
150
if self.contents == b"\n" and leadchar == b" " and False:
152
if not self.contents.endswith(b'\n'):
153
terminator = b'\n' + NO_NL
110
156
return leadchar + self.contents + terminator
159
raise NotImplementedError
113
162
class ContextLine(HunkLine):
114
164
def __init__(self, contents):
115
165
HunkLine.__init__(self, contents)
118
return self.get_str(" ")
168
return self.get_str(b" ")
121
171
class InsertLine(HunkLine):
122
172
def __init__(self, contents):
123
173
HunkLine.__init__(self, contents)
126
return self.get_str("+")
176
return self.get_str(b"+")
129
179
class RemoveLine(HunkLine):
130
180
def __init__(self, contents):
131
181
HunkLine.__init__(self, contents)
134
return self.get_str("-")
136
NO_NL = '\\ No newline at end of file\n'
137
__pychecker__="no-returnvalues"
184
return self.get_str(b"-")
187
NO_NL = b'\\ No newline at end of file\n'
188
__pychecker__ = "no-returnvalues"
139
191
def parse_line(line):
140
if line.startswith("\n"):
192
if line.startswith(b"\n"):
141
193
return ContextLine(line)
142
elif line.startswith(" "):
194
elif line.startswith(b" "):
143
195
return ContextLine(line[1:])
144
elif line.startswith("+"):
196
elif line.startswith(b"+"):
145
197
return InsertLine(line[1:])
146
elif line.startswith("-"):
198
elif line.startswith(b"-"):
147
199
return RemoveLine(line[1:])
149
201
raise MalformedLine("Unknown line type", line)
154
209
def __init__(self, orig_pos, orig_range, mod_pos, mod_range, tail=None):
155
210
self.orig_pos = orig_pos
156
211
self.orig_range = orig_range
162
217
def get_header(self):
163
218
if self.tail is None:
166
tail_str = ' ' + self.tail
167
return "@@ -%s +%s @@%s\n" % (self.range_str(self.orig_pos,
169
self.range_str(self.mod_pos,
221
tail_str = b' ' + self.tail
222
return b"@@ -%s +%s @@%s\n" % (self.range_str(self.orig_pos,
224
self.range_str(self.mod_pos,
173
228
def range_str(self, pos, range):
174
229
"""Return a file range, special-casing for 1-line files.
180
235
:return: a string in the format 1,4 except when range == pos == 1
185
return "%i,%i" % (pos, range)
240
return b"%i,%i" % (pos, range)
188
243
lines = [self.get_header()]
189
244
for line in self.lines:
190
lines.append(str(line))
191
return "".join(lines)
245
lines.append(line.as_bytes())
246
return b"".join(lines)
193
250
def shift_to_mod(self, pos):
194
if pos < self.orig_pos-1:
251
if pos < self.orig_pos - 1:
196
elif pos > self.orig_pos+self.orig_range:
253
elif pos > self.orig_pos + self.orig_range:
197
254
return self.mod_range - self.orig_range
199
256
return self.shift_to_mod_lines(pos)
201
258
def shift_to_mod_lines(self, pos):
202
position = self.orig_pos-1
259
position = self.orig_pos - 1
204
261
for line in self.lines:
205
262
if isinstance(line, InsertLine):
269
327
BinaryPatch.__init__(self, oldname, newname)
273
331
ret = self.get_header()
274
ret += "".join([str(h) for h in self.hunks])
332
ret += b"".join([h.as_bytes() for h in self.hunks])
277
335
def get_header(self):
278
return "--- %s\n+++ %s\n" % (self.oldname, self.newname)
336
return b"--- %s\n+++ %s\n" % (self.oldname, self.newname)
280
338
def stats_values(self):
281
339
"""Calculate the number of inserts and removes."""
345
404
first patch are stripped away in iter_hunks() if it is also passed
346
405
allow_dirty=True. Default False.
348
### FIXME: Docstring is not quite true. We allow certain comments no
407
# FIXME: Docstring is not quite true. We allow certain comments no
349
408
# matter what, If they startwith '===', '***', or '#' Someone should
350
409
# reexamine this logic and decide if we should include those in
351
410
# allow_dirty or restrict those to only being before the patch is found
369
428
dirty_head.append(line)
371
if line.startswith('*** '):
430
if line.startswith(b'*** '):
373
if line.startswith('#'):
432
if line.startswith(b'#'):
375
434
elif orig_range > 0:
376
if line.startswith('-') or line.startswith(' '):
435
if line.startswith(b'-') or line.startswith(b' '):
378
elif line.startswith('--- ') or regex.match(line):
437
elif line.startswith(b'--- ') or regex.match(line):
379
438
if allow_dirty and beginning:
380
439
# Patches can have "junk" at the beginning
381
440
# Stripping junk from the end of patches is handled when we
431
490
:kwarg keep_dirty: If True, returns a dict of patches with dirty headers.
435
493
for patch_lines in iter_file_patch(iter_lines, allow_dirty, keep_dirty):
436
494
if 'dirty_head' in patch_lines:
437
patches.append({'patch': parse_patch(
438
patch_lines['saved_lines'], allow_dirty),
439
'dirty_head': patch_lines['dirty_head']})
495
yield ({'patch': parse_patch(patch_lines['saved_lines'], allow_dirty),
496
'dirty_head': patch_lines['dirty_head']})
441
patches.append(parse_patch(patch_lines, allow_dirty))
498
yield parse_patch(patch_lines, allow_dirty)
445
501
def difference_index(atext, btext):
483
539
orig_lines = iter(orig_lines)
484
540
for hunk in hunks:
485
541
while line_no < hunk.orig_pos:
486
orig_line = orig_lines.next()
542
orig_line = next(orig_lines)
489
545
for hunk_line in hunk.lines:
490
seen_patch.append(str(hunk_line))
546
seen_patch.append(hunk_line.contents)
491
547
if isinstance(hunk_line, InsertLine):
492
548
yield hunk_line.contents
493
549
elif isinstance(hunk_line, (ContextLine, RemoveLine)):
494
orig_line = orig_lines.next()
550
orig_line = next(orig_lines)
495
551
if orig_line != hunk_line.contents:
496
raise PatchConflict(line_no, orig_line, "".join(seen_patch))
552
raise PatchConflict(line_no, orig_line,
553
b''.join(seen_patch))
497
554
if isinstance(hunk_line, ContextLine):
503
560
if orig_lines is not None:
504
561
for line in orig_lines:
565
def apply_patches(tt, patches, prefix=1):
566
"""Apply patches to a TreeTransform.
568
:param tt: TreeTransform instance
569
:param patches: List of patches
570
:param prefix: Number leading path segments to strip
573
return '/'.join(p.split('/')[1:])
575
from breezy.bzr.generate_ids import gen_file_id
576
# TODO(jelmer): Extract and set mode
577
for patch in patches:
578
if patch.oldname == b'/dev/null':
582
oldname = strip_prefix(patch.oldname.decode())
583
trans_id = tt.trans_id_tree_path(oldname)
584
orig_contents = tt._tree.get_file_text(oldname)
585
tt.delete_contents(trans_id)
587
if patch.newname != b'/dev/null':
588
newname = strip_prefix(patch.newname.decode())
589
new_contents = iter_patched_from_hunks(
590
orig_contents.splitlines(True), patch.hunks)
592
parts = os.path.split(newname)
594
for part in parts[1:-1]:
595
trans_id = tt.new_directory(part, trans_id)
597
parts[-1], trans_id, new_contents,
598
file_id=gen_file_id(newname))
600
tt.create_file(new_contents, trans_id)
603
class AppliedPatches(object):
604
"""Context that provides access to a tree with patches applied.
607
def __init__(self, tree, patches, prefix=1):
609
self.patches = patches
613
self._tt = self.tree.preview_transform()
614
apply_patches(self._tt, self.patches, prefix=self.prefix)
615
return self._tt.get_preview_tree()
617
def __exit__(self, exc_type, exc_value, exc_tb):