/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/merge_directive.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:
1
 
# Copyright (C) 2007-2010 Canonical Ltd
 
1
# Copyright (C) 2007-2011 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
 
17
from __future__ import absolute_import
17
18
 
18
 
from StringIO import StringIO
 
19
import base64
19
20
import re
20
21
 
21
 
from bzrlib import (
 
22
from . import lazy_import
 
23
lazy_import.lazy_import(globals(), """
 
24
from breezy import (
22
25
    branch as _mod_branch,
23
26
    diff,
 
27
    email_message,
24
28
    errors,
25
29
    gpg,
26
30
    hooks,
31
35
    timestamp,
32
36
    trace,
33
37
    )
34
 
from bzrlib.bundle import (
 
38
from breezy.bundle import (
35
39
    serializer as bundle_serializer,
36
40
    )
37
 
from bzrlib.email_message import EmailMessage
 
41
""")
 
42
from .sixish import (
 
43
    BytesIO,
 
44
    )
38
45
 
39
46
 
40
47
class MergeRequestBodyParams(object):
56
63
    """Hooks for MergeDirective classes."""
57
64
 
58
65
    def __init__(self):
59
 
        hooks.Hooks.__init__(self)
60
 
        self.create_hook(hooks.HookPoint('merge_request_body',
 
66
        hooks.Hooks.__init__(self, "breezy.merge_directive", "BaseMergeDirective.hooks")
 
67
        self.add_hook('merge_request_body',
61
68
            "Called with a MergeRequestBodyParams when a body is needed for"
62
69
            " a merge request.  Callbacks must return a body.  If more"
63
70
            " than one callback is registered, the output of one callback is"
64
 
            " provided to the next.", (1, 15, 0), False))
 
71
            " provided to the next.", (1, 15, 0))
65
72
 
66
73
 
67
74
class BaseMergeDirective(object):
79
86
    multiple_output_files = False
80
87
 
81
88
    def __init__(self, revision_id, testament_sha1, time, timezone,
82
 
                 target_branch, patch=None, source_branch=None, message=None,
83
 
                 bundle=None):
 
89
                 target_branch, patch=None, source_branch=None,
 
90
                 message=None, bundle=None):
84
91
        """Constructor.
85
92
 
86
93
        :param revision_id: The revision to merge
88
95
            merge.
89
96
        :param time: The current POSIX timestamp time
90
97
        :param timezone: The timezone offset
91
 
        :param target_branch: The branch to apply the merge to
 
98
        :param target_branch: Location of branch to apply the merge to
92
99
        :param patch: The text of a diff or bundle
93
100
        :param source_branch: A public location to merge the revision from
94
101
        :param message: The message to use when committing this merge
137
144
                stanza.add(key, self.__dict__[key])
138
145
        if base_revision:
139
146
            stanza.add('base_revision_id', self.base_revision_id)
140
 
        lines = ['# ' + self._format_string + '\n']
 
147
        lines = [b'# ' + self._format_string + b'\n']
141
148
        lines.extend(rio.to_patch_lines(stanza))
142
 
        lines.append('# \n')
 
149
        lines.append(b'# \n')
143
150
        return lines
144
151
 
145
152
    def write_to_directory(self, path):
162
169
        :param target_branch: The url of the branch to merge into
163
170
        :param patch_type: 'bundle', 'diff' or None, depending on the type of
164
171
            patch desired.
165
 
        :param local_target_branch: a local copy of the target branch
166
 
        :param public_branch: location of a public branch containing the target
167
 
            revision.
 
172
        :param local_target_branch: the submit branch, either itself or a local copy
 
173
        :param public_branch: location of a public branch containing
 
174
            the target revision.
168
175
        :param message: Message to use when committing the merge
169
176
        :return: The merge directive
170
177
 
178
185
        if revision_id == _mod_revision.NULL_REVISION:
179
186
            t_revision_id = None
180
187
        t = testament.StrictTestament3.from_revision(repository, t_revision_id)
181
 
        submit_branch = _mod_branch.Branch.open(target_branch)
 
188
        if local_target_branch is None:
 
189
            submit_branch = _mod_branch.Branch.open(target_branch)
 
190
        else:
 
191
            submit_branch = local_target_branch
182
192
        if submit_branch.get_public_branch() is not None:
183
193
            target_branch = submit_branch.get_public_branch()
184
194
        if patch_type is None:
215
225
        if self.revision_id == revision_id:
216
226
            revno = [revno]
217
227
        else:
218
 
            revno = branch.get_revision_id_to_revno_map().get(self.revision_id,
219
 
                ['merge'])
220
 
        nick = re.sub('(\W+)', '-', branch.nick).strip('-')
 
228
            try:
 
229
                revno = branch.revision_id_to_dotted_revno(self.revision_id)
 
230
            except errors.NoSuchRevision:
 
231
                revno = ['merge']
 
232
        nick = re.sub('(\\W+)', '-', branch.nick).strip('-')
221
233
        return '%s-%s' % (nick, '.'.join(str(n) for n in revno))
222
234
 
223
235
    @staticmethod
224
236
    def _generate_diff(repository, revision_id, ancestor_id):
225
237
        tree_1 = repository.revision_tree(ancestor_id)
226
238
        tree_2 = repository.revision_tree(revision_id)
227
 
        s = StringIO()
 
239
        s = BytesIO()
228
240
        diff.show_diff_trees(tree_1, tree_2, s, old_label='', new_label='')
229
241
        return s.getvalue()
230
242
 
231
243
    @staticmethod
232
244
    def _generate_bundle(repository, revision_id, ancestor_id):
233
 
        s = StringIO()
 
245
        s = BytesIO()
234
246
        bundle_serializer.write_bundle(repository, revision_id,
235
247
                                       ancestor_id, s)
236
248
        return s.getvalue()
241
253
        :param branch: The source branch, to get the signing strategy
242
254
        :return: a string
243
255
        """
244
 
        my_gpg = gpg.GPGStrategy(branch.get_config())
245
 
        return my_gpg.sign(''.join(self.to_lines()))
 
256
        my_gpg = gpg.GPGStrategy(branch.get_config_stack())
 
257
        return my_gpg.sign(b''.join(self.to_lines()), gpg.MODE_CLEAR)
246
258
 
247
259
    def to_email(self, mail_to, branch, sign=False):
248
260
        """Serialize as an email message.
253
265
        :param sign: If True, gpg-sign the email
254
266
        :return: an email message
255
267
        """
256
 
        mail_from = branch.get_config().username()
 
268
        mail_from = branch.get_config_stack().get('email')
257
269
        if self.message is not None:
258
270
            subject = self.message
259
271
        else:
262
274
        if sign:
263
275
            body = self.to_signed(branch)
264
276
        else:
265
 
            body = ''.join(self.to_lines())
266
 
        message = EmailMessage(mail_from, mail_to, subject, body)
 
277
            body = b''.join(self.to_lines())
 
278
        message = email_message.EmailMessage(mail_from, mail_to, subject,
 
279
            body)
267
280
        return message
268
281
 
269
282
    def install_revisions(self, target_repo):
271
284
        if not target_repo.has_revision(self.revision_id):
272
285
            if self.patch_type == 'bundle':
273
286
                info = bundle_serializer.read_bundle(
274
 
                    StringIO(self.get_raw_bundle()))
 
287
                    BytesIO(self.get_raw_bundle()))
275
288
                # We don't use the bundle's target revision, because
276
289
                # MergeDirective.revision_id is authoritative.
277
290
                try:
337
350
                          ' client %s does not support message bodies.',
338
351
                        mail_client.__class__.__name__)
339
352
        mail_client.compose_merge_request(to, subject,
340
 
                                          ''.join(self.to_lines()),
 
353
                                          b''.join(self.to_lines()),
341
354
                                          basename, body)
342
355
 
343
356
 
357
370
    directly using the standard patch program.
358
371
    """
359
372
 
360
 
    _format_string = 'Bazaar merge directive format 1'
 
373
    _format_string = b'Bazaar merge directive format 1'
361
374
 
362
375
    def __init__(self, revision_id, testament_sha1, time, timezone,
363
376
                 target_branch, patch=None, patch_type=None,
369
382
            merge.
370
383
        :param time: The current POSIX timestamp time
371
384
        :param timezone: The timezone offset
372
 
        :param target_branch: The branch to apply the merge to
 
385
        :param target_branch: Location of the branch to apply the merge to
373
386
        :param patch: The text of a diff or bundle
374
387
        :param patch_type: None, "diff" or "bundle", depending on the contents
375
388
            of patch
409
422
        :return: a MergeRequest
410
423
        """
411
424
        line_iter = iter(lines)
412
 
        firstline = ""
 
425
        firstline = b""
413
426
        for line in line_iter:
414
 
            if line.startswith('# Bazaar merge directive format '):
 
427
            if line.startswith(b'# Bazaar merge directive format '):
415
428
                return _format_registry.get(line[2:].rstrip())._from_lines(
416
429
                    line_iter)
417
430
            firstline = firstline or line.strip()
425
438
            patch = None
426
439
            patch_type = None
427
440
        else:
428
 
            patch = ''.join(patch_lines)
 
441
            patch = b''.join(patch_lines)
429
442
            try:
430
 
                bundle_serializer.read_bundle(StringIO(patch))
 
443
                bundle_serializer.read_bundle(BytesIO(patch))
431
444
            except (errors.NotABundle, errors.BundleNotSupported,
432
445
                    errors.BadBundle):
433
446
                patch_type = 'diff'
442
455
            except KeyError:
443
456
                pass
444
457
        kwargs['revision_id'] = kwargs['revision_id'].encode('utf-8')
 
458
        if 'testament_sha1' in kwargs:
 
459
            kwargs['testament_sha1'] = kwargs['testament_sha1'].encode('ascii')
445
460
        return MergeDirective(time=time, timezone=timezone,
446
461
                              patch_type=patch_type, patch=patch, **kwargs)
447
462
 
453
468
 
454
469
    @staticmethod
455
470
    def _generate_bundle(repository, revision_id, ancestor_id):
456
 
        s = StringIO()
 
471
        s = BytesIO()
457
472
        bundle_serializer.write_bundle(repository, revision_id,
458
473
                                       ancestor_id, s, '0.9')
459
474
        return s.getvalue()
468
483
 
469
484
class MergeDirective2(BaseMergeDirective):
470
485
 
471
 
    _format_string = 'Bazaar merge directive format 2 (Bazaar 0.90)'
 
486
    _format_string = b'Bazaar merge directive format 2 (Bazaar 0.90)'
472
487
 
473
488
    def __init__(self, revision_id, testament_sha1, time, timezone,
474
489
                 target_branch, patch=None, source_branch=None, message=None,
498
513
        if self.bundle is None:
499
514
            return None
500
515
        else:
501
 
            return self.bundle.decode('base-64')
 
516
            return base64.b64decode(self.bundle)
502
517
 
503
518
    @classmethod
504
519
    def _from_lines(klass, line_iter):
506
521
        patch = None
507
522
        bundle = None
508
523
        try:
509
 
            start = line_iter.next()
 
524
            start = next(line_iter)
510
525
        except StopIteration:
511
526
            pass
512
527
        else:
513
 
            if start.startswith('# Begin patch'):
 
528
            if start.startswith(b'# Begin patch'):
514
529
                patch_lines = []
515
530
                for line in line_iter:
516
 
                    if line.startswith('# Begin bundle'):
 
531
                    if line.startswith(b'# Begin bundle'):
517
532
                        start = line
518
533
                        break
519
534
                    patch_lines.append(line)
520
535
                else:
521
536
                    start = None
522
 
                patch = ''.join(patch_lines)
 
537
                patch = b''.join(patch_lines)
523
538
            if start is not None:
524
 
                if start.startswith('# Begin bundle'):
525
 
                    bundle = ''.join(line_iter)
 
539
                if start.startswith(b'# Begin bundle'):
 
540
                    bundle = b''.join(line_iter)
526
541
                else:
527
542
                    raise errors.IllegalMergeDirectivePayload(start)
528
543
        time, timezone = timestamp.parse_patch_date(stanza.get('timestamp'))
536
551
        kwargs['revision_id'] = kwargs['revision_id'].encode('utf-8')
537
552
        kwargs['base_revision_id'] =\
538
553
            kwargs['base_revision_id'].encode('utf-8')
 
554
        if 'testament_sha1' in kwargs:
 
555
            kwargs['testament_sha1'] = kwargs['testament_sha1'].encode('ascii')
539
556
        return klass(time=time, timezone=timezone, patch=patch, bundle=bundle,
540
557
                     **kwargs)
541
558
 
542
559
    def to_lines(self):
543
560
        lines = self._to_lines(base_revision=True)
544
561
        if self.patch is not None:
545
 
            lines.append('# Begin patch\n')
 
562
            lines.append(b'# Begin patch\n')
546
563
            lines.extend(self.patch.splitlines(True))
547
564
        if self.bundle is not None:
548
 
            lines.append('# Begin bundle\n')
 
565
            lines.append(b'# Begin bundle\n')
549
566
            lines.extend(self.bundle.splitlines(True))
550
567
        return lines
551
568
 
563
580
        :param target_branch: The url of the branch to merge into
564
581
        :param include_patch: If true, include a preview patch
565
582
        :param include_bundle: If true, include a bundle
566
 
        :param local_target_branch: a local copy of the target branch
567
 
        :param public_branch: location of a public branch containing the target
568
 
            revision.
 
583
        :param local_target_branch: the target branch, either itself or a local copy
 
584
        :param public_branch: location of a public branch containing
 
585
            the target revision.
569
586
        :param message: Message to use when committing the merge
570
587
        :return: The merge directive
571
588
 
580
597
            repository.lock_write()
581
598
            locked.append(repository)
582
599
            t_revision_id = revision_id
583
 
            if revision_id == 'null:':
 
600
            if revision_id == b'null:':
584
601
                t_revision_id = None
585
602
            t = testament.StrictTestament3.from_revision(repository,
586
603
                t_revision_id)
587
 
            submit_branch = _mod_branch.Branch.open(target_branch)
 
604
            if local_target_branch is None:
 
605
                submit_branch = _mod_branch.Branch.open(target_branch)
 
606
            else:
 
607
                submit_branch = local_target_branch
588
608
            submit_branch.lock_read()
589
609
            locked.append(submit_branch)
590
610
            if submit_branch.get_public_branch() is not None:
605
625
                patch = None
606
626
 
607
627
            if include_bundle:
608
 
                bundle = klass._generate_bundle(repository, revision_id,
609
 
                    ancestor_id).encode('base-64')
 
628
                bundle = base64.b64encode(klass._generate_bundle(repository, revision_id,
 
629
                    ancestor_id))
610
630
            else:
611
631
                bundle = None
612
632
 
630
650
        calculated_patch = self._generate_diff(repository, self.revision_id,
631
651
                                               self.base_revision_id)
632
652
        # Convert line-endings to UNIX
633
 
        stored_patch = re.sub('\r\n?', '\n', self.patch)
634
 
        calculated_patch = re.sub('\r\n?', '\n', calculated_patch)
 
653
        stored_patch = re.sub(b'\r\n?', b'\n', self.patch)
 
654
        calculated_patch = re.sub(b'\r\n?', b'\n', calculated_patch)
635
655
        # Strip trailing whitespace
636
 
        calculated_patch = re.sub(' *\n', '\n', calculated_patch)
637
 
        stored_patch = re.sub(' *\n', '\n', stored_patch)
 
656
        calculated_patch = re.sub(b' *\n', b'\n', calculated_patch)
 
657
        stored_patch = re.sub(b' *\n', b'\n', stored_patch)
638
658
        return (calculated_patch == stored_patch)
639
659
 
640
660
    def get_merge_request(self, repository):
670
690
# already merge directives in the wild that used 0.19. Registering with the old
671
691
# format string to retain compatibility with those merge directives.
672
692
_format_registry.register(MergeDirective2,
673
 
                          'Bazaar merge directive format 2 (Bazaar 0.19)')
 
693
                          b'Bazaar merge directive format 2 (Bazaar 0.19)')