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
18
20
from .errors import (
26
binary_files_re = b'Binary files (.*) and (.*) differ\n'
27
binary_files_re = 'Binary files (.*) and (.*) differ\n'
29
30
class PatchSyntax(BzrError):
83
84
match = re.match(binary_files_re, line)
84
85
if match is not None:
85
86
raise BinaryFiles(match.group(1), match.group(2))
86
if not line.startswith(b"--- "):
87
if not line.startswith("--- "):
87
88
raise MalformedPatchHeader("No orig name", line)
89
orig_name = line[4:].rstrip(b"\n")
90
orig_name = line[4:].rstrip("\n")
90
91
except StopIteration:
91
92
raise MalformedPatchHeader("No orig line", "")
93
94
line = next(iter_lines)
94
if not line.startswith(b"+++ "):
95
if not line.startswith("+++ "):
95
96
raise PatchSyntax("No mod name")
97
mod_name = line[4:].rstrip(b"\n")
98
mod_name = line[4:].rstrip("\n")
98
99
except StopIteration:
99
100
raise MalformedPatchHeader("No mod line", "")
100
101
return (orig_name, mod_name)
122
123
def hunk_from_header(line):
124
matches = re.match(br'\@\@ ([^@]*) \@\@( (.*))?\n', line)
125
matches = re.match(r'\@\@ ([^@]*) \@\@( (.*))?\n', line)
125
126
if matches is None:
126
127
raise MalformedHunkHeader("Does not match format.", line)
128
(orig, mod) = matches.group(1).split(b" ")
129
(orig, mod) = matches.group(1).split(" ")
129
130
except (ValueError, IndexError) as e:
130
131
raise MalformedHunkHeader(str(e), line)
131
if not orig.startswith(b'-') or not mod.startswith(b'+'):
132
if not orig.startswith('-') or not mod.startswith('+'):
132
133
raise MalformedHunkHeader("Positions don't start with + or -.", line)
134
135
(orig_pos, orig_range) = parse_range(orig[1:])
141
142
return Hunk(orig_pos, orig_range, mod_pos, mod_range, tail)
144
class HunkLine(object):
146
146
def __init__(self, contents):
147
147
self.contents = contents
149
149
def get_str(self, leadchar):
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
150
if self.contents == "\n" and leadchar == " " and False:
152
if not self.contents.endswith('\n'):
153
terminator = '\n' + NO_NL
156
156
return leadchar + self.contents + terminator
159
raise NotImplementedError
162
159
class ContextLine(HunkLine):
164
160
def __init__(self, contents):
165
161
HunkLine.__init__(self, contents)
168
return self.get_str(b" ")
164
return self.get_str(" ")
171
167
class InsertLine(HunkLine):
172
168
def __init__(self, contents):
173
169
HunkLine.__init__(self, contents)
176
return self.get_str(b"+")
172
return self.get_str("+")
179
175
class RemoveLine(HunkLine):
180
176
def __init__(self, contents):
181
177
HunkLine.__init__(self, contents)
184
return self.get_str(b"-")
187
NO_NL = b'\\ No newline at end of file\n'
188
__pychecker__ = "no-returnvalues"
180
return self.get_str("-")
182
NO_NL = '\\ No newline at end of file\n'
183
__pychecker__="no-returnvalues"
191
185
def parse_line(line):
192
if line.startswith(b"\n"):
186
if line.startswith("\n"):
193
187
return ContextLine(line)
194
elif line.startswith(b" "):
188
elif line.startswith(" "):
195
189
return ContextLine(line[1:])
196
elif line.startswith(b"+"):
190
elif line.startswith("+"):
197
191
return InsertLine(line[1:])
198
elif line.startswith(b"-"):
192
elif line.startswith("-"):
199
193
return RemoveLine(line[1:])
201
195
raise MalformedLine("Unknown line type", line)
209
200
def __init__(self, orig_pos, orig_range, mod_pos, mod_range, tail=None):
210
201
self.orig_pos = orig_pos
211
202
self.orig_range = orig_range
217
208
def get_header(self):
218
209
if self.tail is None:
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,
212
tail_str = ' ' + self.tail
213
return "@@ -%s +%s @@%s\n" % (self.range_str(self.orig_pos,
215
self.range_str(self.mod_pos,
228
219
def range_str(self, pos, range):
229
220
"""Return a file range, special-casing for 1-line files.
235
226
:return: a string in the format 1,4 except when range == pos == 1
240
return b"%i,%i" % (pos, range)
231
return "%i,%i" % (pos, range)
243
234
lines = [self.get_header()]
244
235
for line in self.lines:
245
lines.append(line.as_bytes())
246
return b"".join(lines)
236
lines.append(str(line))
237
return "".join(lines)
250
239
def shift_to_mod(self, pos):
251
if pos < self.orig_pos - 1:
240
if pos < self.orig_pos-1:
253
elif pos > self.orig_pos + self.orig_range:
242
elif pos > self.orig_pos+self.orig_range:
254
243
return self.mod_range - self.orig_range
256
245
return self.shift_to_mod_lines(pos)
258
247
def shift_to_mod_lines(self, pos):
259
position = self.orig_pos - 1
248
position = self.orig_pos-1
261
250
for line in self.lines:
262
251
if isinstance(line, InsertLine):
314
303
class BinaryPatch(object):
316
304
def __init__(self, oldname, newname):
317
305
self.oldname = oldname
318
306
self.newname = newname
321
return b'Binary files %s and %s differ\n' % (self.oldname, self.newname)
309
return 'Binary files %s and %s differ\n' % (self.oldname, self.newname)
324
312
class Patch(BinaryPatch):
327
315
BinaryPatch.__init__(self, oldname, newname)
331
319
ret = self.get_header()
332
ret += b"".join([h.as_bytes() for h in self.hunks])
320
ret += "".join([str(h) for h in self.hunks])
335
323
def get_header(self):
336
return b"--- %s\n+++ %s\n" % (self.oldname, self.newname)
324
return "--- %s\n+++ %s\n" % (self.oldname, self.newname)
338
326
def stats_values(self):
339
327
"""Calculate the number of inserts and removes."""
404
391
first patch are stripped away in iter_hunks() if it is also passed
405
392
allow_dirty=True. Default False.
407
# FIXME: Docstring is not quite true. We allow certain comments no
394
### FIXME: Docstring is not quite true. We allow certain comments no
408
395
# matter what, If they startwith '===', '***', or '#' Someone should
409
396
# reexamine this logic and decide if we should include those in
410
397
# allow_dirty or restrict those to only being before the patch is found
428
415
dirty_head.append(line)
430
if line.startswith(b'*** '):
417
if line.startswith('*** '):
432
if line.startswith(b'#'):
419
if line.startswith('#'):
434
421
elif orig_range > 0:
435
if line.startswith(b'-') or line.startswith(b' '):
422
if line.startswith('-') or line.startswith(' '):
437
elif line.startswith(b'--- ') or regex.match(line):
424
elif line.startswith('--- ') or regex.match(line):
438
425
if allow_dirty and beginning:
439
426
# Patches can have "junk" at the beginning
440
427
# Stripping junk from the end of patches is handled when we
490
477
:kwarg keep_dirty: If True, returns a dict of patches with dirty headers.
493
481
for patch_lines in iter_file_patch(iter_lines, allow_dirty, keep_dirty):
494
482
if 'dirty_head' in patch_lines:
495
yield ({'patch': parse_patch(patch_lines['saved_lines'], allow_dirty),
496
'dirty_head': patch_lines['dirty_head']})
483
patches.append({'patch': parse_patch(
484
patch_lines['saved_lines'], allow_dirty),
485
'dirty_head': patch_lines['dirty_head']})
498
yield parse_patch(patch_lines, allow_dirty)
487
patches.append(parse_patch(patch_lines, allow_dirty))
501
491
def difference_index(atext, btext):
545
535
for hunk_line in hunk.lines:
546
seen_patch.append(hunk_line.contents)
536
seen_patch.append(str(hunk_line))
547
537
if isinstance(hunk_line, InsertLine):
548
538
yield hunk_line.contents
549
539
elif isinstance(hunk_line, (ContextLine, RemoveLine)):
550
540
orig_line = next(orig_lines)
551
541
if orig_line != hunk_line.contents:
552
raise PatchConflict(line_no, orig_line,
553
b''.join(seen_patch))
542
raise PatchConflict(line_no, orig_line, "".join(seen_patch))
554
543
if isinstance(hunk_line, ContextLine):
560
549
if orig_lines is not None:
561
550
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):