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
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.'
20
binary_files_re = 'Binary files (.*) and (.*) differ\n'
23
class BinaryFiles(Exception):
37
25
def __init__(self, orig_name, mod_name):
38
26
self.orig_name = orig_name
39
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)
42
36
class MalformedPatchHeader(PatchSyntax):
44
_fmt = "Malformed patch header. %(desc)s\n%(line)r"
46
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)
51
52
class MalformedLine(PatchSyntax):
53
_fmt = "Malformed line. %(desc)s\n%(line)r"
55
53
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"')
56
msg = "Malformed line. %s\n%s" % (self.desc, self.line)
57
PatchSyntax.__init__(self, msg)
60
class PatchConflict(Exception):
65
61
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):
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)
80
69
def get_patch_names(iter_lines):
81
line = next(iter_lines)
71
line = iter_lines.next()
83
72
match = re.match(binary_files_re, line)
84
73
if match is not None:
85
74
raise BinaryFiles(match.group(1), match.group(2))
86
if not line.startswith(b"--- "):
75
if not line.startswith("--- "):
87
76
raise MalformedPatchHeader("No orig name", line)
89
orig_name = line[4:].rstrip(b"\n")
78
orig_name = line[4:].rstrip("\n")
90
79
except StopIteration:
91
80
raise MalformedPatchHeader("No orig line", "")
93
line = next(iter_lines)
94
if not line.startswith(b"+++ "):
82
line = iter_lines.next()
83
if not line.startswith("+++ "):
95
84
raise PatchSyntax("No mod name")
97
mod_name = line[4:].rstrip(b"\n")
86
mod_name = line[4:].rstrip("\n")
98
87
except StopIteration:
99
88
raise MalformedPatchHeader("No mod line", "")
100
89
return (orig_name, mod_name)
122
111
def hunk_from_header(line):
124
matches = re.match(br'\@\@ ([^@]*) \@\@( (.*))?\n', line)
113
matches = re.match(r'\@\@ ([^@]*) \@\@( (.*))?\n', line)
125
114
if matches is None:
126
115
raise MalformedHunkHeader("Does not match format.", line)
128
(orig, mod) = matches.group(1).split(b" ")
129
except (ValueError, IndexError) as e:
117
(orig, mod) = matches.group(1).split(" ")
118
except (ValueError, IndexError), e:
130
119
raise MalformedHunkHeader(str(e), line)
131
if not orig.startswith(b'-') or not mod.startswith(b'+'):
120
if not orig.startswith('-') or not mod.startswith('+'):
132
121
raise MalformedHunkHeader("Positions don't start with + or -.", line)
134
123
(orig_pos, orig_range) = parse_range(orig[1:])
135
124
(mod_pos, mod_range) = parse_range(mod[1:])
136
except (ValueError, IndexError) as e:
125
except (ValueError, IndexError), e:
137
126
raise MalformedHunkHeader(str(e), line)
138
127
if mod_range < 0 or orig_range < 0:
139
128
raise MalformedHunkHeader("Hunk range is negative", line)
141
130
return Hunk(orig_pos, orig_range, mod_pos, mod_range, tail)
144
class HunkLine(object):
146
134
def __init__(self, contents):
147
135
self.contents = contents
149
137
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
138
if self.contents == "\n" and leadchar == " " and False:
140
if not self.contents.endswith('\n'):
141
terminator = '\n' + NO_NL
156
144
return leadchar + self.contents + terminator
159
raise NotImplementedError
162
147
class ContextLine(HunkLine):
164
148
def __init__(self, contents):
165
149
HunkLine.__init__(self, contents)
168
return self.get_str(b" ")
152
return self.get_str(" ")
171
155
class InsertLine(HunkLine):
172
156
def __init__(self, contents):
173
157
HunkLine.__init__(self, contents)
176
return self.get_str(b"+")
160
return self.get_str("+")
179
163
class RemoveLine(HunkLine):
180
164
def __init__(self, contents):
181
165
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"
168
return self.get_str("-")
170
NO_NL = '\\ No newline at end of file\n'
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)
209
188
def __init__(self, orig_pos, orig_range, mod_pos, mod_range, tail=None):
210
189
self.orig_pos = orig_pos
211
190
self.orig_range = orig_range
235
214
:return: a string in the format 1,4 except when range == pos == 1
240
return b"%i,%i" % (pos, range)
219
return "%i,%i" % (pos, range)
243
222
lines = [self.get_header()]
244
223
for line in self.lines:
245
lines.append(line.as_bytes())
246
return b"".join(lines)
224
lines.append(str(line))
225
return "".join(lines)
250
227
def shift_to_mod(self, pos):
251
if pos < self.orig_pos - 1:
228
if pos < self.orig_pos-1:
253
elif pos > self.orig_pos + self.orig_range:
230
elif pos > self.orig_pos+self.orig_range:
254
231
return self.mod_range - self.orig_range
256
233
return self.shift_to_mod_lines(pos)
258
235
def shift_to_mod_lines(self, pos):
259
position = self.orig_pos - 1
236
position = self.orig_pos-1
261
238
for line in self.lines:
262
239
if isinstance(line, InsertLine):
404
380
first patch are stripped away in iter_hunks() if it is also passed
405
381
allow_dirty=True. Default False.
407
# FIXME: Docstring is not quite true. We allow certain comments no
383
### FIXME: Docstring is not quite true. We allow certain comments no
408
384
# matter what, If they startwith '===', '***', or '#' Someone should
409
385
# reexamine this logic and decide if we should include those in
410
386
# allow_dirty or restrict those to only being before the patch is found
411
387
# (as allow_dirty does).
412
388
regex = re.compile(binary_files_re)
418
392
for line in iter_lines:
419
if line.startswith(b'=== '):
420
if len(saved_lines) > 0:
421
if keep_dirty and len(dirty_head) > 0:
422
yield {'saved_lines': saved_lines,
423
'dirty_head': dirty_head}
428
dirty_head.append(line)
430
if line.startswith(b'*** '):
432
if line.startswith(b'#'):
393
if line.startswith('=== ') or line.startswith('*** '):
395
if line.startswith('#'):
434
397
elif orig_range > 0:
435
if line.startswith(b'-') or line.startswith(b' '):
398
if line.startswith('-') or line.startswith(' '):
437
elif line.startswith(b'--- ') or regex.match(line):
400
elif line.startswith('--- ') or regex.match(line):
438
401
if allow_dirty and beginning:
439
402
# Patches can have "junk" at the beginning
440
403
# Stripping junk from the end of patches is handled when we
441
404
# parse the patch
442
405
beginning = False
443
406
elif len(saved_lines) > 0:
444
if keep_dirty and len(dirty_head) > 0:
445
yield {'saved_lines': saved_lines,
446
'dirty_head': dirty_head}
451
elif line.startswith(b'@@'):
409
elif line.startswith('@@'):
452
410
hunk = hunk_from_header(line)
453
411
orig_range = hunk.orig_range
454
412
saved_lines.append(line)
455
413
if len(saved_lines) > 0:
456
if keep_dirty and len(dirty_head) > 0:
457
yield {'saved_lines': saved_lines,
458
'dirty_head': dirty_head}
463
417
def iter_lines_handle_nl(iter_lines):
484
def parse_patches(iter_lines, allow_dirty=False, keep_dirty=False):
438
def parse_patches(iter_lines, allow_dirty=False):
486
440
:arg iter_lines: iterable of lines to parse for patches
487
441
:kwarg allow_dirty: If True, allow text that's not part of the patch at
488
442
selected places. This includes comments before and after a patch
489
443
for instance. Default False.
490
:kwarg keep_dirty: If True, returns a dict of patches with dirty headers.
493
for patch_lines in iter_file_patch(iter_lines, allow_dirty, keep_dirty):
494
if 'dirty_head' in patch_lines:
495
yield ({'patch': parse_patch(patch_lines['saved_lines'], allow_dirty),
496
'dirty_head': patch_lines['dirty_head']})
498
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)]
501
449
def difference_index(atext, btext):
539
487
orig_lines = iter(orig_lines)
540
488
for hunk in hunks:
541
489
while line_no < hunk.orig_pos:
542
orig_line = next(orig_lines)
490
orig_line = orig_lines.next()
545
493
for hunk_line in hunk.lines:
546
seen_patch.append(hunk_line.contents)
494
seen_patch.append(str(hunk_line))
547
495
if isinstance(hunk_line, InsertLine):
548
496
yield hunk_line.contents
549
497
elif isinstance(hunk_line, (ContextLine, RemoveLine)):
550
orig_line = next(orig_lines)
498
orig_line = orig_lines.next()
551
499
if orig_line != hunk_line.contents:
552
raise PatchConflict(line_no, orig_line,
553
b''.join(seen_patch))
500
raise PatchConflict(line_no, orig_line, "".join(seen_patch))
554
501
if isinstance(hunk_line, ContextLine):
560
507
if orig_lines is not None:
561
508
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):