/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: Jelmer Vernooij
  • Date: 2018-06-14 17:59:16 UTC
  • mto: This revision was merged to the branch mainline in revision 7065.
  • Revision ID: jelmer@jelmer.uk-20180614175916-a2e2xh5k533guq1x
Move breezy.plugins.git to breezy.git.

Show diffs side-by-side

added added

removed removed

Lines of Context:
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
 
import base64
18
 
import contextlib
19
 
from io import BytesIO
 
17
from __future__ import absolute_import
 
18
 
20
19
import re
21
20
 
22
21
from . import lazy_import
25
24
    branch as _mod_branch,
26
25
    diff,
27
26
    email_message,
 
27
    errors,
28
28
    gpg,
29
29
    hooks,
30
30
    registry,
31
31
    revision as _mod_revision,
32
32
    rio,
 
33
    testament,
33
34
    timestamp,
34
35
    trace,
35
36
    )
36
 
from breezy.bzr import (
37
 
    testament,
38
 
    )
39
 
from breezy.bzr.bundle import (
 
37
from breezy.bundle import (
40
38
    serializer as bundle_serializer,
41
39
    )
42
40
""")
43
 
from . import (
44
 
    errors,
 
41
from .sixish import (
 
42
    BytesIO,
45
43
    )
46
44
 
47
45
 
48
 
class IllegalMergeDirectivePayload(errors.BzrError):
49
 
    """A merge directive contained something other than a patch or bundle"""
50
 
 
51
 
    _fmt = "Bad merge directive payload %(start)r"
52
 
 
53
 
    def __init__(self, start):
54
 
        errors.BzrError(self)
55
 
        self.start = start
56
 
 
57
 
 
58
46
class MergeRequestBodyParams(object):
59
47
    """Parameter object for the merge_request_body hook."""
60
48
 
74
62
    """Hooks for MergeDirective classes."""
75
63
 
76
64
    def __init__(self):
77
 
        hooks.Hooks.__init__(self, "breezy.merge_directive",
78
 
                             "BaseMergeDirective.hooks")
79
 
        self.add_hook(
80
 
            'merge_request_body',
 
65
        hooks.Hooks.__init__(self, "breezy.merge_directive", "BaseMergeDirective.hooks")
 
66
        self.add_hook('merge_request_body',
81
67
            "Called with a MergeRequestBodyParams when a body is needed for"
82
68
            " a merge request.  Callbacks must return a body.  If more"
83
69
            " than one callback is registered, the output of one callback is"
87
73
class BaseMergeDirective(object):
88
74
    """A request to perform a merge into a branch.
89
75
 
90
 
    This is the base class that all merge directive implementations
 
76
    This is the base class that all merge directive implementations 
91
77
    should derive from.
92
78
 
93
 
    :cvar multiple_output_files: Whether or not this merge directive
 
79
    :cvar multiple_output_files: Whether or not this merge directive 
94
80
        stores a set of revisions in more than one file
95
81
    """
96
82
 
157
143
                stanza.add(key, self.__dict__[key])
158
144
        if base_revision:
159
145
            stanza.add('base_revision_id', self.base_revision_id)
160
 
        lines = [b'# ' + self._format_string + b'\n']
 
146
        lines = ['# ' + self._format_string + '\n']
161
147
        lines.extend(rio.to_patch_lines(stanza))
162
 
        lines.append(b'# \n')
 
148
        lines.append('# \n')
163
149
        return lines
164
150
 
165
151
    def write_to_directory(self, path):
171
157
 
172
158
    @classmethod
173
159
    def from_objects(klass, repository, revision_id, time, timezone,
174
 
                     target_branch, patch_type='bundle',
175
 
                     local_target_branch=None, public_branch=None, message=None):
 
160
                 target_branch, patch_type='bundle',
 
161
                 local_target_branch=None, public_branch=None, message=None):
176
162
        """Generate a merge directive from various objects
177
163
 
178
164
        :param repository: The repository containing the revision
215
201
                                                submit_revision_id)
216
202
            type_handler = {'bundle': klass._generate_bundle,
217
203
                            'diff': klass._generate_diff,
218
 
                            None: lambda x, y, z: None}
 
204
                            None: lambda x, y, z: None }
219
205
            patch = type_handler[patch_type](repository, revision_id,
220
206
                                             ancestor_id)
221
207
 
226
212
                                                   revision_id)
227
213
 
228
214
        return klass(revision_id, t.as_sha1(), time, timezone, target_branch,
229
 
                     patch, patch_type, public_branch, message)
 
215
            patch, patch_type, public_branch, message)
230
216
 
231
217
    def get_disk_name(self, branch):
232
218
        """Generate a suitable basename for storing this directive on disk
238
224
        if self.revision_id == revision_id:
239
225
            revno = [revno]
240
226
        else:
241
 
            try:
242
 
                revno = branch.revision_id_to_dotted_revno(self.revision_id)
243
 
            except errors.NoSuchRevision:
244
 
                revno = ['merge']
 
227
            revno = branch.get_revision_id_to_revno_map().get(self.revision_id,
 
228
                ['merge'])
245
229
        nick = re.sub('(\\W+)', '-', branch.nick).strip('-')
246
230
        return '%s-%s' % (nick, '.'.join(str(n) for n in revno))
247
231
 
267
251
        :return: a string
268
252
        """
269
253
        my_gpg = gpg.GPGStrategy(branch.get_config_stack())
270
 
        return my_gpg.sign(b''.join(self.to_lines()), gpg.MODE_CLEAR)
 
254
        return my_gpg.sign(''.join(self.to_lines()), gpg.MODE_CLEAR)
271
255
 
272
256
    def to_email(self, mail_to, branch, sign=False):
273
257
        """Serialize as an email message.
287
271
        if sign:
288
272
            body = self.to_signed(branch)
289
273
        else:
290
 
            body = b''.join(self.to_lines())
 
274
            body = ''.join(self.to_lines())
291
275
        message = email_message.EmailMessage(mail_from, mail_to, subject,
292
 
                                             body)
 
276
            body)
293
277
        return message
294
278
 
295
279
    def install_revisions(self, target_repo):
315
299
                                           info.real_revisions)
316
300
                    for revision in info.real_revisions:
317
301
                        for parent_id in revision.parent_ids:
318
 
                            if (parent_id not in bundle_revisions
319
 
                                    and not target_repo.has_revision(parent_id)):
 
302
                            if (parent_id not in bundle_revisions and
 
303
                                not target_repo.has_revision(parent_id)):
320
304
                                missing_revisions.append(parent_id)
321
305
                    # reverse missing revisions to try to get heads first
322
306
                    unique_missing = []
361
345
        elif len(self.hooks['merge_request_body']) > 0:
362
346
            trace.warning('Cannot run merge_request_body hooks because mail'
363
347
                          ' client %s does not support message bodies.',
364
 
                          mail_client.__class__.__name__)
 
348
                        mail_client.__class__.__name__)
365
349
        mail_client.compose_merge_request(to, subject,
366
 
                                          b''.join(self.to_lines()),
 
350
                                          ''.join(self.to_lines()),
367
351
                                          basename, body)
368
352
 
369
353
 
383
367
    directly using the standard patch program.
384
368
    """
385
369
 
386
 
    _format_string = b'Bazaar merge directive format 1'
 
370
    _format_string = 'Bazaar merge directive format 1'
387
371
 
388
372
    def __init__(self, revision_id, testament_sha1, time, timezone,
389
373
                 target_branch, patch=None, patch_type=None,
403
387
        :param message: The message to use when committing this merge
404
388
        """
405
389
        BaseMergeDirective.__init__(self, revision_id, testament_sha1, time,
406
 
                                    timezone, target_branch, patch, source_branch, message)
 
390
            timezone, target_branch, patch, source_branch, message)
407
391
        if patch_type not in (None, 'diff', 'bundle'):
408
392
            raise ValueError(patch_type)
409
393
        if patch_type != 'bundle' and source_branch is None:
435
419
        :return: a MergeRequest
436
420
        """
437
421
        line_iter = iter(lines)
438
 
        firstline = b""
 
422
        firstline = ""
439
423
        for line in line_iter:
440
 
            if line.startswith(b'# Bazaar merge directive format '):
 
424
            if line.startswith('# Bazaar merge directive format '):
441
425
                return _format_registry.get(line[2:].rstrip())._from_lines(
442
426
                    line_iter)
443
427
            firstline = firstline or line.strip()
451
435
            patch = None
452
436
            patch_type = None
453
437
        else:
454
 
            patch = b''.join(patch_lines)
 
438
            patch = ''.join(patch_lines)
455
439
            try:
456
440
                bundle_serializer.read_bundle(BytesIO(patch))
457
441
            except (errors.NotABundle, errors.BundleNotSupported,
468
452
            except KeyError:
469
453
                pass
470
454
        kwargs['revision_id'] = kwargs['revision_id'].encode('utf-8')
471
 
        if 'testament_sha1' in kwargs:
472
 
            kwargs['testament_sha1'] = kwargs['testament_sha1'].encode('ascii')
473
455
        return MergeDirective(time=time, timezone=timezone,
474
456
                              patch_type=patch_type, patch=patch, **kwargs)
475
457
 
496
478
 
497
479
class MergeDirective2(BaseMergeDirective):
498
480
 
499
 
    _format_string = b'Bazaar merge directive format 2 (Bazaar 0.90)'
 
481
    _format_string = 'Bazaar merge directive format 2 (Bazaar 0.90)'
500
482
 
501
483
    def __init__(self, revision_id, testament_sha1, time, timezone,
502
484
                 target_branch, patch=None, source_branch=None, message=None,
504
486
        if source_branch is None and bundle is None:
505
487
            raise errors.NoMergeSource()
506
488
        BaseMergeDirective.__init__(self, revision_id, testament_sha1, time,
507
 
                                    timezone, target_branch, patch, source_branch, message)
 
489
            timezone, target_branch, patch, source_branch, message)
508
490
        self.bundle = bundle
509
491
        self.base_revision_id = base_revision_id
510
492
 
526
508
        if self.bundle is None:
527
509
            return None
528
510
        else:
529
 
            return base64.b64decode(self.bundle)
 
511
            return self.bundle.decode('base-64')
530
512
 
531
513
    @classmethod
532
514
    def _from_lines(klass, line_iter):
538
520
        except StopIteration:
539
521
            pass
540
522
        else:
541
 
            if start.startswith(b'# Begin patch'):
 
523
            if start.startswith('# Begin patch'):
542
524
                patch_lines = []
543
525
                for line in line_iter:
544
 
                    if line.startswith(b'# Begin bundle'):
 
526
                    if line.startswith('# Begin bundle'):
545
527
                        start = line
546
528
                        break
547
529
                    patch_lines.append(line)
548
530
                else:
549
531
                    start = None
550
 
                patch = b''.join(patch_lines)
 
532
                patch = ''.join(patch_lines)
551
533
            if start is not None:
552
 
                if start.startswith(b'# Begin bundle'):
553
 
                    bundle = b''.join(line_iter)
 
534
                if start.startswith('# Begin bundle'):
 
535
                    bundle = ''.join(line_iter)
554
536
                else:
555
 
                    raise IllegalMergeDirectivePayload(start)
 
537
                    raise errors.IllegalMergeDirectivePayload(start)
556
538
        time, timezone = timestamp.parse_patch_date(stanza.get('timestamp'))
557
539
        kwargs = {}
558
540
        for key in ('revision_id', 'testament_sha1', 'target_branch',
564
546
        kwargs['revision_id'] = kwargs['revision_id'].encode('utf-8')
565
547
        kwargs['base_revision_id'] =\
566
548
            kwargs['base_revision_id'].encode('utf-8')
567
 
        if 'testament_sha1' in kwargs:
568
 
            kwargs['testament_sha1'] = kwargs['testament_sha1'].encode('ascii')
569
549
        return klass(time=time, timezone=timezone, patch=patch, bundle=bundle,
570
550
                     **kwargs)
571
551
 
572
552
    def to_lines(self):
573
553
        lines = self._to_lines(base_revision=True)
574
554
        if self.patch is not None:
575
 
            lines.append(b'# Begin patch\n')
 
555
            lines.append('# Begin patch\n')
576
556
            lines.extend(self.patch.splitlines(True))
577
557
        if self.bundle is not None:
578
 
            lines.append(b'# Begin bundle\n')
 
558
            lines.append('# Begin bundle\n')
579
559
            lines.extend(self.bundle.splitlines(True))
580
560
        return lines
581
561
 
582
562
    @classmethod
583
563
    def from_objects(klass, repository, revision_id, time, timezone,
584
 
                     target_branch, include_patch=True, include_bundle=True,
585
 
                     local_target_branch=None, public_branch=None, message=None,
586
 
                     base_revision_id=None):
 
564
                 target_branch, include_patch=True, include_bundle=True,
 
565
                 local_target_branch=None, public_branch=None, message=None,
 
566
                 base_revision_id=None):
587
567
        """Generate a merge directive from various objects
588
568
 
589
569
        :param repository: The repository containing the revision
605
585
        If the message is not supplied, the message from revision_id will be
606
586
        used for the commit.
607
587
        """
608
 
        with contextlib.ExitStack() as exit_stack:
609
 
            exit_stack.enter_context(repository.lock_write())
 
588
        locked = []
 
589
        try:
 
590
            repository.lock_write()
 
591
            locked.append(repository)
610
592
            t_revision_id = revision_id
611
 
            if revision_id == b'null:':
 
593
            if revision_id == 'null:':
612
594
                t_revision_id = None
613
595
            t = testament.StrictTestament3.from_revision(repository,
614
 
                                                         t_revision_id)
 
596
                t_revision_id)
615
597
            if local_target_branch is None:
616
598
                submit_branch = _mod_branch.Branch.open(target_branch)
617
599
            else:
618
600
                submit_branch = local_target_branch
619
 
            exit_stack.enter_context(submit_branch.lock_read())
 
601
            submit_branch.lock_read()
 
602
            locked.append(submit_branch)
620
603
            if submit_branch.get_public_branch() is not None:
621
604
                target_branch = submit_branch.get_public_branch()
622
605
            submit_revision_id = submit_branch.last_revision()
635
618
                patch = None
636
619
 
637
620
            if include_bundle:
638
 
                bundle = base64.b64encode(klass._generate_bundle(repository, revision_id,
639
 
                                                                 ancestor_id))
 
621
                bundle = klass._generate_bundle(repository, revision_id,
 
622
                    ancestor_id).encode('base-64')
640
623
            else:
641
624
                bundle = None
642
625
 
643
626
            if public_branch is not None and not include_bundle:
644
627
                public_branch_obj = _mod_branch.Branch.open(public_branch)
645
 
                exit_stack.enter_context(public_branch_obj.lock_read())
 
628
                public_branch_obj.lock_read()
 
629
                locked.append(public_branch_obj)
646
630
                if not public_branch_obj.repository.has_revision(
647
 
                        revision_id):
 
631
                    revision_id):
648
632
                    raise errors.PublicBranchOutOfDate(public_branch,
649
633
                                                       revision_id)
650
634
            testament_sha1 = t.as_sha1()
 
635
        finally:
 
636
            for entry in reversed(locked):
 
637
                entry.unlock()
651
638
        return klass(revision_id, testament_sha1, time, timezone,
652
 
                     target_branch, patch, public_branch, message, bundle,
653
 
                     base_revision_id)
 
639
            target_branch, patch, public_branch, message, bundle,
 
640
            base_revision_id)
654
641
 
655
642
    def _verify_patch(self, repository):
656
643
        calculated_patch = self._generate_diff(repository, self.revision_id,
657
644
                                               self.base_revision_id)
658
645
        # Convert line-endings to UNIX
659
 
        stored_patch = re.sub(b'\r\n?', b'\n', self.patch)
660
 
        calculated_patch = re.sub(b'\r\n?', b'\n', calculated_patch)
 
646
        stored_patch = re.sub('\r\n?', '\n', self.patch)
 
647
        calculated_patch = re.sub('\r\n?', '\n', calculated_patch)
661
648
        # Strip trailing whitespace
662
 
        calculated_patch = re.sub(b' *\n', b'\n', calculated_patch)
663
 
        stored_patch = re.sub(b' *\n', b'\n', stored_patch)
 
649
        calculated_patch = re.sub(' *\n', '\n', calculated_patch)
 
650
        stored_patch = re.sub(' *\n', '\n', stored_patch)
664
651
        return (calculated_patch == stored_patch)
665
652
 
666
653
    def get_merge_request(self, repository):
696
683
# already merge directives in the wild that used 0.19. Registering with the old
697
684
# format string to retain compatibility with those merge directives.
698
685
_format_registry.register(MergeDirective2,
699
 
                          b'Bazaar merge directive format 2 (Bazaar 0.19)')
 
686
                          'Bazaar merge directive format 2 (Bazaar 0.19)')