/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to breezy/patches.py

  • Committer: Breezy landing bot
  • Author(s): Jelmer Vernooij
  • Date: 2018-11-16 18:26:22 UTC
  • mfrom: (7167.1.4 run-flake8)
  • Revision ID: breezy.the.bot@gmail.com-20181116182622-qw3gan3hz78a2imw
Add a flake8 test.

Merged from https://code.launchpad.net/~jelmer/brz/run-flake8/+merge/358902

Show diffs side-by-side

added added

removed removed

Lines of Context:
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
 
17
 
 
18
from __future__ import absolute_import
 
19
 
 
20
from .errors import (
 
21
    BzrError,
 
22
    )
 
23
 
17
24
import re
18
25
 
19
26
 
20
 
binary_files_re = 'Binary files (.*) and (.*) differ\n'
21
 
 
22
 
 
23
 
class BinaryFiles(Exception):
 
27
binary_files_re = b'Binary files (.*) and (.*) differ\n'
 
28
 
 
29
 
 
30
class PatchSyntax(BzrError):
 
31
    """Base class for patch syntax errors."""
 
32
 
 
33
 
 
34
class BinaryFiles(BzrError):
 
35
 
 
36
    _fmt = 'Binary files section encountered.'
24
37
 
25
38
    def __init__(self, orig_name, mod_name):
26
39
        self.orig_name = orig_name
27
40
        self.mod_name = mod_name
28
 
        Exception.__init__(self, 'Binary files section encountered.')
29
 
 
30
 
 
31
 
class PatchSyntax(Exception):
32
 
    def __init__(self, msg):
33
 
        Exception.__init__(self, msg)
34
41
 
35
42
 
36
43
class MalformedPatchHeader(PatchSyntax):
37
 
    def __init__(self, desc, line):
38
 
        self.desc = desc
39
 
        self.line = line
40
 
        msg = "Malformed patch header.  %s\n%r" % (self.desc, self.line)
41
 
        PatchSyntax.__init__(self, msg)
42
 
 
43
 
 
44
 
class MalformedHunkHeader(PatchSyntax):
45
 
    def __init__(self, desc, line):
46
 
        self.desc = desc
47
 
        self.line = line
48
 
        msg = "Malformed hunk header.  %s\n%r" % (self.desc, self.line)
49
 
        PatchSyntax.__init__(self, msg)
 
44
 
 
45
    _fmt = "Malformed patch header.  %(desc)s\n%(line)r"
 
46
 
 
47
    def __init__(self, desc, line):
 
48
        self.desc = desc
 
49
        self.line = line
50
50
 
51
51
 
52
52
class MalformedLine(PatchSyntax):
 
53
 
 
54
    _fmt = "Malformed line.  %(desc)s\n%(line)r"
 
55
 
53
56
    def __init__(self, desc, line):
54
57
        self.desc = desc
55
58
        self.line = line
56
 
        msg = "Malformed line.  %s\n%s" % (self.desc, self.line)
57
 
        PatchSyntax.__init__(self, msg)
58
 
 
59
 
 
60
 
class PatchConflict(Exception):
 
59
 
 
60
 
 
61
class PatchConflict(BzrError):
 
62
 
 
63
    _fmt = ('Text contents mismatch at line %(line_no)d.  Original has '
 
64
            '"%(orig_line)s", but patch says it should be "%(patch_line)s"')
 
65
 
61
66
    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)
 
67
        self.line_no = line_no
 
68
        self.orig_line = orig_line.rstrip('\n')
 
69
        self.patch_line = patch_line.rstrip('\n')
 
70
 
 
71
 
 
72
class MalformedHunkHeader(PatchSyntax):
 
73
 
 
74
    _fmt = "Malformed hunk header.  %(desc)s\n%(line)r"
 
75
 
 
76
    def __init__(self, desc, line):
 
77
        self.desc = desc
 
78
        self.line = line
67
79
 
68
80
 
69
81
def get_patch_names(iter_lines):
 
82
    line = next(iter_lines)
70
83
    try:
71
 
        line = iter_lines.next()
72
84
        match = re.match(binary_files_re, line)
73
85
        if match is not None:
74
86
            raise BinaryFiles(match.group(1), match.group(2))
75
 
        if not line.startswith("--- "):
 
87
        if not line.startswith(b"--- "):
76
88
            raise MalformedPatchHeader("No orig name", line)
77
89
        else:
78
 
            orig_name = line[4:].rstrip("\n")
 
90
            orig_name = line[4:].rstrip(b"\n")
79
91
    except StopIteration:
80
92
        raise MalformedPatchHeader("No orig line", "")
81
93
    try:
82
 
        line = iter_lines.next()
83
 
        if not line.startswith("+++ "):
 
94
        line = next(iter_lines)
 
95
        if not line.startswith(b"+++ "):
84
96
            raise PatchSyntax("No mod name")
85
97
        else:
86
 
            mod_name = line[4:].rstrip("\n")
 
98
            mod_name = line[4:].rstrip(b"\n")
87
99
    except StopIteration:
88
100
        raise MalformedPatchHeader("No mod line", "")
89
101
    return (orig_name, mod_name)
97
109
    :return: the position and range, as a tuple
98
110
    :rtype: (int, int)
99
111
    """
100
 
    tmp = textrange.split(',')
 
112
    tmp = textrange.split(b',')
101
113
    if len(tmp) == 1:
102
114
        pos = tmp[0]
103
 
        range = "1"
 
115
        range = b"1"
104
116
    else:
105
117
        (pos, range) = tmp
106
118
    pos = int(pos)
110
122
 
111
123
def hunk_from_header(line):
112
124
    import re
113
 
    matches = re.match(r'\@\@ ([^@]*) \@\@( (.*))?\n', line)
 
125
    matches = re.match(br'\@\@ ([^@]*) \@\@( (.*))?\n', line)
114
126
    if matches is None:
115
127
        raise MalformedHunkHeader("Does not match format.", line)
116
128
    try:
117
 
        (orig, mod) = matches.group(1).split(" ")
118
 
    except (ValueError, IndexError), e:
 
129
        (orig, mod) = matches.group(1).split(b" ")
 
130
    except (ValueError, IndexError) as e:
119
131
        raise MalformedHunkHeader(str(e), line)
120
 
    if not orig.startswith('-') or not mod.startswith('+'):
 
132
    if not orig.startswith(b'-') or not mod.startswith(b'+'):
121
133
        raise MalformedHunkHeader("Positions don't start with + or -.", line)
122
134
    try:
123
135
        (orig_pos, orig_range) = parse_range(orig[1:])
124
136
        (mod_pos, mod_range) = parse_range(mod[1:])
125
 
    except (ValueError, IndexError), e:
 
137
    except (ValueError, IndexError) as e:
126
138
        raise MalformedHunkHeader(str(e), line)
127
139
    if mod_range < 0 or orig_range < 0:
128
140
        raise MalformedHunkHeader("Hunk range is negative", line)
130
142
    return Hunk(orig_pos, orig_range, mod_pos, mod_range, tail)
131
143
 
132
144
 
133
 
class HunkLine:
 
145
class HunkLine(object):
 
146
 
134
147
    def __init__(self, contents):
135
148
        self.contents = contents
136
149
 
137
150
    def get_str(self, leadchar):
138
 
        if self.contents == "\n" and leadchar == " " and False:
139
 
            return "\n"
140
 
        if not self.contents.endswith('\n'):
141
 
            terminator = '\n' + NO_NL
 
151
        if self.contents == b"\n" and leadchar == b" " and False:
 
152
            return b"\n"
 
153
        if not self.contents.endswith(b'\n'):
 
154
            terminator = b'\n' + NO_NL
142
155
        else:
143
 
            terminator = ''
 
156
            terminator = b''
144
157
        return leadchar + self.contents + terminator
145
158
 
 
159
    def as_bytes(self):
 
160
        raise NotImplementedError
 
161
 
146
162
 
147
163
class ContextLine(HunkLine):
 
164
 
148
165
    def __init__(self, contents):
149
166
        HunkLine.__init__(self, contents)
150
167
 
151
 
    def __str__(self):
152
 
        return self.get_str(" ")
 
168
    def as_bytes(self):
 
169
        return self.get_str(b" ")
153
170
 
154
171
 
155
172
class InsertLine(HunkLine):
156
173
    def __init__(self, contents):
157
174
        HunkLine.__init__(self, contents)
158
175
 
159
 
    def __str__(self):
160
 
        return self.get_str("+")
 
176
    def as_bytes(self):
 
177
        return self.get_str(b"+")
161
178
 
162
179
 
163
180
class RemoveLine(HunkLine):
164
181
    def __init__(self, contents):
165
182
        HunkLine.__init__(self, contents)
166
183
 
167
 
    def __str__(self):
168
 
        return self.get_str("-")
 
184
    def as_bytes(self):
 
185
        return self.get_str(b"-")
169
186
 
170
 
NO_NL = '\\ No newline at end of file\n'
 
187
NO_NL = b'\\ No newline at end of file\n'
171
188
__pychecker__="no-returnvalues"
172
189
 
173
190
def parse_line(line):
174
 
    if line.startswith("\n"):
 
191
    if line.startswith(b"\n"):
175
192
        return ContextLine(line)
176
 
    elif line.startswith(" "):
 
193
    elif line.startswith(b" "):
177
194
        return ContextLine(line[1:])
178
 
    elif line.startswith("+"):
 
195
    elif line.startswith(b"+"):
179
196
        return InsertLine(line[1:])
180
 
    elif line.startswith("-"):
 
197
    elif line.startswith(b"-"):
181
198
        return RemoveLine(line[1:])
182
199
    else:
183
200
        raise MalformedLine("Unknown line type", line)
184
201
__pychecker__=""
185
202
 
186
203
 
187
 
class Hunk:
 
204
class Hunk(object):
 
205
 
188
206
    def __init__(self, orig_pos, orig_range, mod_pos, mod_range, tail=None):
189
207
        self.orig_pos = orig_pos
190
208
        self.orig_range = orig_range
195
213
 
196
214
    def get_header(self):
197
215
        if self.tail is None:
198
 
            tail_str = ''
 
216
            tail_str = b''
199
217
        else:
200
 
            tail_str = ' ' + self.tail
201
 
        return "@@ -%s +%s @@%s\n" % (self.range_str(self.orig_pos,
 
218
            tail_str = b' ' + self.tail
 
219
        return b"@@ -%s +%s @@%s\n" % (self.range_str(self.orig_pos,
202
220
                                                     self.orig_range),
203
221
                                      self.range_str(self.mod_pos,
204
222
                                                     self.mod_range),
214
232
        :return: a string in the format 1,4 except when range == pos == 1
215
233
        """
216
234
        if range == 1:
217
 
            return "%i" % pos
 
235
            return b"%i" % pos
218
236
        else:
219
 
            return "%i,%i" % (pos, range)
 
237
            return b"%i,%i" % (pos, range)
220
238
 
221
 
    def __str__(self):
 
239
    def as_bytes(self):
222
240
        lines = [self.get_header()]
223
241
        for line in self.lines:
224
 
            lines.append(str(line))
225
 
        return "".join(lines)
 
242
            lines.append(line.as_bytes())
 
243
        return b"".join(lines)
 
244
 
 
245
    __bytes__ = as_bytes
226
246
 
227
247
    def shift_to_mod(self, pos):
228
248
        if pos < self.orig_pos-1:
259
279
    '''
260
280
    hunk = None
261
281
    for line in iter_lines:
262
 
        if line == "\n":
 
282
        if line == b"\n":
263
283
            if hunk is not None:
264
284
                yield hunk
265
285
                hunk = None
278
298
        orig_size = 0
279
299
        mod_size = 0
280
300
        while orig_size < hunk.orig_range or mod_size < hunk.mod_range:
281
 
            hunk_line = parse_line(iter_lines.next())
 
301
            hunk_line = parse_line(next(iter_lines))
282
302
            hunk.lines.append(hunk_line)
283
303
            if isinstance(hunk_line, (RemoveLine, ContextLine)):
284
304
                orig_size += 1
289
309
 
290
310
 
291
311
class BinaryPatch(object):
 
312
 
292
313
    def __init__(self, oldname, newname):
293
314
        self.oldname = oldname
294
315
        self.newname = newname
295
316
 
296
 
    def __str__(self):
297
 
        return 'Binary files %s and %s differ\n' % (self.oldname, self.newname)
 
317
    def as_bytes(self):
 
318
        return b'Binary files %s and %s differ\n' % (self.oldname, self.newname)
298
319
 
299
320
 
300
321
class Patch(BinaryPatch):
303
324
        BinaryPatch.__init__(self, oldname, newname)
304
325
        self.hunks = []
305
326
 
306
 
    def __str__(self):
 
327
    def as_bytes(self):
307
328
        ret = self.get_header()
308
 
        ret += "".join([str(h) for h in self.hunks])
 
329
        ret += b"".join([h.as_bytes() for h in self.hunks])
309
330
        return ret
310
331
 
311
332
    def get_header(self):
312
 
        return "--- %s\n+++ %s\n" % (self.oldname, self.newname)
 
333
        return b"--- %s\n+++ %s\n" % (self.oldname, self.newname)
313
334
 
314
335
    def stats_values(self):
315
336
        """Calculate the number of inserts and removes."""
362
383
    iter_lines = iter_lines_handle_nl(iter_lines)
363
384
    try:
364
385
        (orig_name, mod_name) = get_patch_names(iter_lines)
365
 
    except BinaryFiles, e:
 
386
    except BinaryFiles as e:
366
387
        return BinaryPatch(e.orig_name, e.mod_name)
367
388
    else:
368
389
        patch = Patch(orig_name, mod_name)
371
392
        return patch
372
393
 
373
394
 
374
 
def iter_file_patch(iter_lines, allow_dirty=False):
 
395
def iter_file_patch(iter_lines, allow_dirty=False, keep_dirty=False):
375
396
    '''
376
397
    :arg iter_lines: iterable of lines to parse for patches
377
398
    :kwarg allow_dirty: If True, allow comments and other non-patch text
387
408
    # (as allow_dirty does).
388
409
    regex = re.compile(binary_files_re)
389
410
    saved_lines = []
 
411
    dirty_head = []
390
412
    orig_range = 0
391
413
    beginning = True
 
414
 
392
415
    for line in iter_lines:
393
 
        if line.startswith('=== ') or line.startswith('*** '):
394
 
            continue
395
 
        if line.startswith('#'):
 
416
        if line.startswith(b'=== '):
 
417
            if len(saved_lines) > 0:
 
418
                if keep_dirty and len(dirty_head) > 0:
 
419
                    yield {'saved_lines': saved_lines,
 
420
                           'dirty_head': dirty_head}
 
421
                    dirty_head = []
 
422
                else:
 
423
                    yield saved_lines
 
424
                saved_lines = []
 
425
            dirty_head.append(line)
 
426
            continue
 
427
        if line.startswith(b'*** '):
 
428
            continue
 
429
        if line.startswith(b'#'):
396
430
            continue
397
431
        elif orig_range > 0:
398
 
            if line.startswith('-') or line.startswith(' '):
 
432
            if line.startswith(b'-') or line.startswith(b' '):
399
433
                orig_range -= 1
400
 
        elif line.startswith('--- ') or regex.match(line):
 
434
        elif line.startswith(b'--- ') or regex.match(line):
401
435
            if allow_dirty and beginning:
402
436
                # Patches can have "junk" at the beginning
403
437
                # Stripping junk from the end of patches is handled when we
404
438
                # parse the patch
405
439
                beginning = False
406
440
            elif len(saved_lines) > 0:
407
 
                yield saved_lines
 
441
                if keep_dirty and len(dirty_head) > 0:
 
442
                    yield {'saved_lines': saved_lines,
 
443
                           'dirty_head': dirty_head}
 
444
                    dirty_head = []
 
445
                else:
 
446
                    yield saved_lines
408
447
            saved_lines = []
409
 
        elif line.startswith('@@'):
 
448
        elif line.startswith(b'@@'):
410
449
            hunk = hunk_from_header(line)
411
450
            orig_range = hunk.orig_range
412
451
        saved_lines.append(line)
413
452
    if len(saved_lines) > 0:
414
 
        yield saved_lines
 
453
        if keep_dirty and len(dirty_head) > 0:
 
454
            yield {'saved_lines': saved_lines,
 
455
                   'dirty_head': dirty_head}
 
456
        else:
 
457
            yield saved_lines
415
458
 
416
459
 
417
460
def iter_lines_handle_nl(iter_lines):
424
467
    last_line = None
425
468
    for line in iter_lines:
426
469
        if line == NO_NL:
427
 
            if not last_line.endswith('\n'):
 
470
            if not last_line.endswith(b'\n'):
428
471
                raise AssertionError()
429
472
            last_line = last_line[:-1]
430
473
            line = None
435
478
        yield last_line
436
479
 
437
480
 
438
 
def parse_patches(iter_lines, allow_dirty=False):
 
481
def parse_patches(iter_lines, allow_dirty=False, keep_dirty=False):
439
482
    '''
440
483
    :arg iter_lines: iterable of lines to parse for patches
441
484
    :kwarg allow_dirty: If True, allow text that's not part of the patch at
442
485
        selected places.  This includes comments before and after a patch
443
486
        for instance.  Default False.
 
487
    :kwarg keep_dirty: If True, returns a dict of patches with dirty headers.
 
488
        Default False.
444
489
    '''
445
 
    return [parse_patch(f.__iter__(), allow_dirty) for f in
446
 
                        iter_file_patch(iter_lines, allow_dirty)]
 
490
    for patch_lines in iter_file_patch(iter_lines, allow_dirty, keep_dirty):
 
491
        if 'dirty_head' in patch_lines:
 
492
            yield ({'patch': parse_patch(patch_lines['saved_lines'], allow_dirty),
 
493
                    'dirty_head': patch_lines['dirty_head']})
 
494
        else:
 
495
            yield parse_patch(patch_lines, allow_dirty)
447
496
 
448
497
 
449
498
def difference_index(atext, btext):
487
536
        orig_lines = iter(orig_lines)
488
537
    for hunk in hunks:
489
538
        while line_no < hunk.orig_pos:
490
 
            orig_line = orig_lines.next()
 
539
            orig_line = next(orig_lines)
491
540
            yield orig_line
492
541
            line_no += 1
493
542
        for hunk_line in hunk.lines:
495
544
            if isinstance(hunk_line, InsertLine):
496
545
                yield hunk_line.contents
497
546
            elif isinstance(hunk_line, (ContextLine, RemoveLine)):
498
 
                orig_line = orig_lines.next()
 
547
                orig_line = next(orig_lines)
499
548
                if orig_line != hunk_line.contents:
500
 
                    raise PatchConflict(line_no, orig_line, "".join(seen_patch))
 
549
                    raise PatchConflict(line_no, orig_line, b"".join(seen_patch))
501
550
                if isinstance(hunk_line, ContextLine):
502
551
                    yield orig_line
503
552
                else: