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"-")
189
NO_NL = b'\\ No newline at end of file\n'
190
__pychecker__ = "no-returnvalues"
168
return self.get_str("-")
170
NO_NL = '\\ No newline at end of file\n'
171
__pychecker__="no-returnvalues"
193
173
def parse_line(line):
194
if line.startswith(b"\n"):
174
if line.startswith("\n"):
195
175
return ContextLine(line)
196
elif line.startswith(b" "):
176
elif line.startswith(" "):
197
177
return ContextLine(line[1:])
198
elif line.startswith(b"+"):
178
elif line.startswith("+"):
199
179
return InsertLine(line[1:])
200
elif line.startswith(b"-"):
180
elif line.startswith("-"):
201
181
return RemoveLine(line[1:])
203
183
raise MalformedLine("Unknown line type", line)
211
188
def __init__(self, orig_pos, orig_range, mod_pos, mod_range, tail=None):
212
189
self.orig_pos = orig_pos
213
190
self.orig_range = orig_range
237
214
:return: a string in the format 1,4 except when range == pos == 1
242
return b"%i,%i" % (pos, range)
219
return "%i,%i" % (pos, range)
245
222
lines = [self.get_header()]
246
223
for line in self.lines:
247
lines.append(line.as_bytes())
248
return b"".join(lines)
224
lines.append(str(line))
225
return "".join(lines)
252
227
def shift_to_mod(self, pos):
253
if pos < self.orig_pos - 1:
228
if pos < self.orig_pos-1:
255
elif pos > self.orig_pos + self.orig_range:
230
elif pos > self.orig_pos+self.orig_range:
256
231
return self.mod_range - self.orig_range
258
233
return self.shift_to_mod_lines(pos)
260
235
def shift_to_mod_lines(self, pos):
261
position = self.orig_pos - 1
236
position = self.orig_pos-1
263
238
for line in self.lines:
264
239
if isinstance(line, InsertLine):
406
380
first patch are stripped away in iter_hunks() if it is also passed
407
381
allow_dirty=True. Default False.
409
# FIXME: Docstring is not quite true. We allow certain comments no
383
### FIXME: Docstring is not quite true. We allow certain comments no
410
384
# matter what, If they startwith '===', '***', or '#' Someone should
411
385
# reexamine this logic and decide if we should include those in
412
386
# allow_dirty or restrict those to only being before the patch is found
413
387
# (as allow_dirty does).
414
388
regex = re.compile(binary_files_re)
420
392
for line in iter_lines:
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'#'):
393
if line.startswith('=== ') or line.startswith('*** '):
395
if line.startswith('#'):
436
397
elif orig_range > 0:
437
if line.startswith(b'-') or line.startswith(b' '):
398
if line.startswith('-') or line.startswith(' '):
439
elif line.startswith(b'--- ') or regex.match(line):
400
elif line.startswith('--- ') or regex.match(line):
440
401
if allow_dirty and beginning:
441
402
# Patches can have "junk" at the beginning
442
403
# Stripping junk from the end of patches is handled when we
443
404
# parse the patch
444
405
beginning = False
445
406
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}
453
elif line.startswith(b'@@'):
409
elif line.startswith('@@'):
454
410
hunk = hunk_from_header(line)
455
411
orig_range = hunk.orig_range
456
412
saved_lines.append(line)
457
413
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}
465
417
def iter_lines_handle_nl(iter_lines):
486
def parse_patches(iter_lines, allow_dirty=False, keep_dirty=False):
438
def parse_patches(iter_lines, allow_dirty=False):
488
440
:arg iter_lines: iterable of lines to parse for patches
489
441
:kwarg allow_dirty: If True, allow text that's not part of the patch at
490
442
selected places. This includes comments before and after a patch
491
443
for instance. Default False.
492
:kwarg keep_dirty: If True, returns a dict of patches with dirty headers.
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)
445
return [parse_patch(f.__iter__(), allow_dirty) for f in
446
iter_file_patch(iter_lines, allow_dirty)]
503
449
def difference_index(atext, btext):
541
487
orig_lines = iter(orig_lines)
542
488
for hunk in hunks:
543
489
while line_no < hunk.orig_pos:
544
orig_line = next(orig_lines)
490
orig_line = orig_lines.next()
547
493
for hunk_line in hunk.lines:
548
seen_patch.append(hunk_line.contents)
494
seen_patch.append(str(hunk_line))
549
495
if isinstance(hunk_line, InsertLine):
550
496
yield hunk_line.contents
551
497
elif isinstance(hunk_line, (ContextLine, RemoveLine)):
552
orig_line = next(orig_lines)
498
orig_line = orig_lines.next()
553
499
if orig_line != hunk_line.contents:
554
raise PatchConflict(line_no, orig_line,
555
b''.join(seen_patch))
500
raise PatchConflict(line_no, orig_line, "".join(seen_patch))
556
501
if isinstance(hunk_line, ContextLine):
562
507
if orig_lines is not None:
563
508
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):