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
20
binary_files_re = 'Binary files (.*) and (.*) differ\n'
23
class BinaryFiles(Exception):
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.'
25
39
def __init__(self, orig_name, mod_name):
26
40
self.orig_name = orig_name
27
41
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)
36
44
class MalformedPatchHeader(PatchSyntax):
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)
46
_fmt = "Malformed patch header. %(desc)s\n%(line)r"
48
def __init__(self, desc, line):
52
53
class MalformedLine(PatchSyntax):
55
_fmt = "Malformed line. %(desc)s\n%(line)r"
53
57
def __init__(self, desc, line):
56
msg = "Malformed line. %s\n%s" % (self.desc, self.line)
57
PatchSyntax.__init__(self, msg)
60
class PatchConflict(Exception):
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"')
61
67
def __init__(self, line_no, orig_line, patch_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)
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):
69
82
def get_patch_names(iter_lines):
83
line = next(iter_lines)
71
line = iter_lines.next()
72
85
match = re.match(binary_files_re, line)
73
86
if match is not None:
74
87
raise BinaryFiles(match.group(1), match.group(2))
75
if not line.startswith("--- "):
88
if not line.startswith(b"--- "):
76
89
raise MalformedPatchHeader("No orig name", line)
78
orig_name = line[4:].rstrip("\n")
91
orig_name = line[4:].rstrip(b"\n")
79
92
except StopIteration:
80
93
raise MalformedPatchHeader("No orig line", "")
82
line = iter_lines.next()
83
if not line.startswith("+++ "):
95
line = next(iter_lines)
96
if not line.startswith(b"+++ "):
84
97
raise PatchSyntax("No mod name")
86
mod_name = line[4:].rstrip("\n")
99
mod_name = line[4:].rstrip(b"\n")
87
100
except StopIteration:
88
101
raise MalformedPatchHeader("No mod line", "")
89
102
return (orig_name, mod_name)
111
124
def hunk_from_header(line):
113
matches = re.match(r'\@\@ ([^@]*) \@\@( (.*))?\n', line)
126
matches = re.match(br'\@\@ ([^@]*) \@\@( (.*))?\n', line)
114
127
if matches is None:
115
128
raise MalformedHunkHeader("Does not match format.", line)
117
(orig, mod) = matches.group(1).split(" ")
118
except (ValueError, IndexError), e:
130
(orig, mod) = matches.group(1).split(b" ")
131
except (ValueError, IndexError) as e:
119
132
raise MalformedHunkHeader(str(e), line)
120
if not orig.startswith('-') or not mod.startswith('+'):
133
if not orig.startswith(b'-') or not mod.startswith(b'+'):
121
134
raise MalformedHunkHeader("Positions don't start with + or -.", line)
123
136
(orig_pos, orig_range) = parse_range(orig[1:])
124
137
(mod_pos, mod_range) = parse_range(mod[1:])
125
except (ValueError, IndexError), e:
138
except (ValueError, IndexError) as e:
126
139
raise MalformedHunkHeader(str(e), line)
127
140
if mod_range < 0 or orig_range < 0:
128
141
raise MalformedHunkHeader("Hunk range is negative", line)
130
143
return Hunk(orig_pos, orig_range, mod_pos, mod_range, tail)
146
class HunkLine(object):
134
148
def __init__(self, contents):
135
149
self.contents = contents
137
151
def get_str(self, leadchar):
138
if self.contents == "\n" and leadchar == " " and False:
140
if not self.contents.endswith('\n'):
141
terminator = '\n' + NO_NL
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
144
158
return leadchar + self.contents + terminator
161
raise NotImplementedError
147
164
class ContextLine(HunkLine):
148
166
def __init__(self, contents):
149
167
HunkLine.__init__(self, contents)
152
return self.get_str(" ")
170
return self.get_str(b" ")
155
173
class InsertLine(HunkLine):
156
174
def __init__(self, contents):
157
175
HunkLine.__init__(self, contents)
160
return self.get_str("+")
178
return self.get_str(b"+")
163
181
class RemoveLine(HunkLine):
164
182
def __init__(self, contents):
165
183
HunkLine.__init__(self, contents)
168
return self.get_str("-")
170
NO_NL = '\\ No newline at end of file\n'
171
__pychecker__="no-returnvalues"
186
return self.get_str(b"-")
189
NO_NL = b'\\ No newline at end of file\n'
190
__pychecker__ = "no-returnvalues"
173
193
def parse_line(line):
174
if line.startswith("\n"):
194
if line.startswith(b"\n"):
175
195
return ContextLine(line)
176
elif line.startswith(" "):
196
elif line.startswith(b" "):
177
197
return ContextLine(line[1:])
178
elif line.startswith("+"):
198
elif line.startswith(b"+"):
179
199
return InsertLine(line[1:])
180
elif line.startswith("-"):
200
elif line.startswith(b"-"):
181
201
return RemoveLine(line[1:])
183
203
raise MalformedLine("Unknown line type", line)
188
211
def __init__(self, orig_pos, orig_range, mod_pos, mod_range, tail=None):
189
212
self.orig_pos = orig_pos
190
213
self.orig_range = orig_range
214
237
:return: a string in the format 1,4 except when range == pos == 1
219
return "%i,%i" % (pos, range)
242
return b"%i,%i" % (pos, range)
222
245
lines = [self.get_header()]
223
246
for line in self.lines:
224
lines.append(str(line))
225
return "".join(lines)
247
lines.append(line.as_bytes())
248
return b"".join(lines)
227
252
def shift_to_mod(self, pos):
228
if pos < self.orig_pos-1:
253
if pos < self.orig_pos - 1:
230
elif pos > self.orig_pos+self.orig_range:
255
elif pos > self.orig_pos + self.orig_range:
231
256
return self.mod_range - self.orig_range
233
258
return self.shift_to_mod_lines(pos)
235
260
def shift_to_mod_lines(self, pos):
236
position = self.orig_pos-1
261
position = self.orig_pos - 1
238
263
for line in self.lines:
239
264
if isinstance(line, InsertLine):
380
406
first patch are stripped away in iter_hunks() if it is also passed
381
407
allow_dirty=True. Default False.
383
### FIXME: Docstring is not quite true. We allow certain comments no
409
# FIXME: Docstring is not quite true. We allow certain comments no
384
410
# matter what, If they startwith '===', '***', or '#' Someone should
385
411
# reexamine this logic and decide if we should include those in
386
412
# allow_dirty or restrict those to only being before the patch is found
387
413
# (as allow_dirty does).
388
414
regex = re.compile(binary_files_re)
392
420
for line in iter_lines:
393
if line.startswith('=== ') or line.startswith('*** '):
395
if line.startswith('#'):
421
if line.startswith(b'=== '):
422
if len(saved_lines) > 0:
423
if keep_dirty and len(dirty_head) > 0:
424
yield {'saved_lines': saved_lines,
425
'dirty_head': dirty_head}
430
dirty_head.append(line)
432
if line.startswith(b'*** '):
434
if line.startswith(b'#'):
397
436
elif orig_range > 0:
398
if line.startswith('-') or line.startswith(' '):
437
if line.startswith(b'-') or line.startswith(b' '):
400
elif line.startswith('--- ') or regex.match(line):
439
elif line.startswith(b'--- ') or regex.match(line):
401
440
if allow_dirty and beginning:
402
441
# Patches can have "junk" at the beginning
403
442
# Stripping junk from the end of patches is handled when we
404
443
# parse the patch
405
444
beginning = False
406
445
elif len(saved_lines) > 0:
446
if keep_dirty and len(dirty_head) > 0:
447
yield {'saved_lines': saved_lines,
448
'dirty_head': dirty_head}
409
elif line.startswith('@@'):
453
elif line.startswith(b'@@'):
410
454
hunk = hunk_from_header(line)
411
455
orig_range = hunk.orig_range
412
456
saved_lines.append(line)
413
457
if len(saved_lines) > 0:
458
if keep_dirty and len(dirty_head) > 0:
459
yield {'saved_lines': saved_lines,
460
'dirty_head': dirty_head}
417
465
def iter_lines_handle_nl(iter_lines):
438
def parse_patches(iter_lines, allow_dirty=False):
486
def parse_patches(iter_lines, allow_dirty=False, keep_dirty=False):
440
488
:arg iter_lines: iterable of lines to parse for patches
441
489
:kwarg allow_dirty: If True, allow text that's not part of the patch at
442
490
selected places. This includes comments before and after a patch
443
491
for instance. Default False.
492
:kwarg keep_dirty: If True, returns a dict of patches with dirty headers.
445
return [parse_patch(f.__iter__(), allow_dirty) for f in
446
iter_file_patch(iter_lines, allow_dirty)]
495
for patch_lines in iter_file_patch(iter_lines, allow_dirty, keep_dirty):
496
if 'dirty_head' in patch_lines:
497
yield ({'patch': parse_patch(patch_lines['saved_lines'], allow_dirty),
498
'dirty_head': patch_lines['dirty_head']})
500
yield parse_patch(patch_lines, allow_dirty)
449
503
def difference_index(atext, btext):
487
541
orig_lines = iter(orig_lines)
488
542
for hunk in hunks:
489
543
while line_no < hunk.orig_pos:
490
orig_line = orig_lines.next()
544
orig_line = next(orig_lines)
493
547
for hunk_line in hunk.lines:
494
seen_patch.append(str(hunk_line))
548
seen_patch.append(hunk_line.contents)
495
549
if isinstance(hunk_line, InsertLine):
496
550
yield hunk_line.contents
497
551
elif isinstance(hunk_line, (ContextLine, RemoveLine)):
498
orig_line = orig_lines.next()
552
orig_line = next(orig_lines)
499
553
if orig_line != hunk_line.contents:
500
raise PatchConflict(line_no, orig_line, "".join(seen_patch))
554
raise PatchConflict(line_no, orig_line,
555
b''.join(seen_patch))
501
556
if isinstance(hunk_line, ContextLine):
507
562
if orig_lines is not None:
508
563
for line in orig_lines:
567
def apply_patches(tt, patches, prefix=1):
568
"""Apply patches to a TreeTransform.
570
:param tt: TreeTransform instance
571
:param patches: List of patches
572
:param prefix: Number leading path segments to strip
575
return '/'.join(p.split('/')[1:])
577
from breezy.bzr.generate_ids import gen_file_id
578
# TODO(jelmer): Extract and set mode
579
for patch in patches:
580
if patch.oldname == b'/dev/null':
584
oldname = strip_prefix(patch.oldname.decode())
585
trans_id = tt.trans_id_tree_path(oldname)
586
orig_contents = tt._tree.get_file_text(oldname)
587
tt.delete_contents(trans_id)
589
if patch.newname != b'/dev/null':
590
newname = strip_prefix(patch.newname.decode())
591
new_contents = iter_patched_from_hunks(
592
orig_contents.splitlines(True), patch.hunks)
594
parts = os.path.split(newname)
596
for part in parts[1:-1]:
597
trans_id = tt.new_directory(part, trans_id)
599
parts[-1], trans_id, new_contents,
600
file_id=gen_file_id(newname))
602
tt.create_file(new_contents, trans_id)
605
class AppliedPatches(object):
606
"""Context that provides access to a tree with patches applied.
609
def __init__(self, tree, patches, prefix=1):
611
self.patches = patches
615
from .transform import TransformPreview
616
self._tt = TransformPreview(self.tree)
617
apply_patches(self._tt, self.patches, prefix=self.prefix)
618
return self._tt.get_preview_tree()
620
def __exit__(self, exc_type, exc_value, exc_tb):