/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-05-06 11:48:54 UTC
  • mto: This revision was merged to the branch mainline in revision 6960.
  • Revision ID: jelmer@jelmer.uk-20180506114854-h4qd9ojaqy8wxjsd
Move .mailmap to root.

Show diffs side-by-side

added added

removed removed

Lines of Context:
16
16
 
17
17
from __future__ import absolute_import
18
18
 
19
 
import base64
20
19
import re
21
20
 
22
21
from . import lazy_import
23
22
lazy_import.lazy_import(globals(), """
24
23
from breezy import (
25
24
    branch as _mod_branch,
26
 
    cleanup,
27
25
    diff,
28
26
    email_message,
 
27
    errors,
29
28
    gpg,
30
29
    hooks,
31
30
    registry,
32
31
    revision as _mod_revision,
33
32
    rio,
 
33
    testament,
34
34
    timestamp,
35
35
    trace,
36
36
    )
37
 
from breezy.bzr import (
38
 
    testament,
39
 
    )
40
 
from breezy.bzr.bundle import (
 
37
from breezy.bundle import (
41
38
    serializer as bundle_serializer,
42
39
    )
43
40
""")
44
 
from . import (
45
 
    errors,
46
 
    )
47
41
from .sixish import (
48
42
    BytesIO,
49
43
    )
68
62
    """Hooks for MergeDirective classes."""
69
63
 
70
64
    def __init__(self):
71
 
        hooks.Hooks.__init__(self, "breezy.merge_directive",
72
 
                             "BaseMergeDirective.hooks")
73
 
        self.add_hook(
74
 
            'merge_request_body',
 
65
        hooks.Hooks.__init__(self, "breezy.merge_directive", "BaseMergeDirective.hooks")
 
66
        self.add_hook('merge_request_body',
75
67
            "Called with a MergeRequestBodyParams when a body is needed for"
76
68
            " a merge request.  Callbacks must return a body.  If more"
77
69
            " than one callback is registered, the output of one callback is"
81
73
class BaseMergeDirective(object):
82
74
    """A request to perform a merge into a branch.
83
75
 
84
 
    This is the base class that all merge directive implementations
 
76
    This is the base class that all merge directive implementations 
85
77
    should derive from.
86
78
 
87
 
    :cvar multiple_output_files: Whether or not this merge directive
 
79
    :cvar multiple_output_files: Whether or not this merge directive 
88
80
        stores a set of revisions in more than one file
89
81
    """
90
82
 
151
143
                stanza.add(key, self.__dict__[key])
152
144
        if base_revision:
153
145
            stanza.add('base_revision_id', self.base_revision_id)
154
 
        lines = [b'# ' + self._format_string + b'\n']
 
146
        lines = ['# ' + self._format_string + '\n']
155
147
        lines.extend(rio.to_patch_lines(stanza))
156
 
        lines.append(b'# \n')
 
148
        lines.append('# \n')
157
149
        return lines
158
150
 
159
151
    def write_to_directory(self, path):
165
157
 
166
158
    @classmethod
167
159
    def from_objects(klass, repository, revision_id, time, timezone,
168
 
                     target_branch, patch_type='bundle',
169
 
                     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):
170
162
        """Generate a merge directive from various objects
171
163
 
172
164
        :param repository: The repository containing the revision
209
201
                                                submit_revision_id)
210
202
            type_handler = {'bundle': klass._generate_bundle,
211
203
                            'diff': klass._generate_diff,
212
 
                            None: lambda x, y, z: None}
 
204
                            None: lambda x, y, z: None }
213
205
            patch = type_handler[patch_type](repository, revision_id,
214
206
                                             ancestor_id)
215
207
 
220
212
                                                   revision_id)
221
213
 
222
214
        return klass(revision_id, t.as_sha1(), time, timezone, target_branch,
223
 
                     patch, patch_type, public_branch, message)
 
215
            patch, patch_type, public_branch, message)
224
216
 
225
217
    def get_disk_name(self, branch):
226
218
        """Generate a suitable basename for storing this directive on disk
232
224
        if self.revision_id == revision_id:
233
225
            revno = [revno]
234
226
        else:
235
 
            try:
236
 
                revno = branch.revision_id_to_dotted_revno(self.revision_id)
237
 
            except errors.NoSuchRevision:
238
 
                revno = ['merge']
 
227
            revno = branch.get_revision_id_to_revno_map().get(self.revision_id,
 
228
                ['merge'])
239
229
        nick = re.sub('(\\W+)', '-', branch.nick).strip('-')
240
230
        return '%s-%s' % (nick, '.'.join(str(n) for n in revno))
241
231
 
261
251
        :return: a string
262
252
        """
263
253
        my_gpg = gpg.GPGStrategy(branch.get_config_stack())
264
 
        return my_gpg.sign(b''.join(self.to_lines()), gpg.MODE_CLEAR)
 
254
        return my_gpg.sign(''.join(self.to_lines()), gpg.MODE_CLEAR)
265
255
 
266
256
    def to_email(self, mail_to, branch, sign=False):
267
257
        """Serialize as an email message.
281
271
        if sign:
282
272
            body = self.to_signed(branch)
283
273
        else:
284
 
            body = b''.join(self.to_lines())
 
274
            body = ''.join(self.to_lines())
285
275
        message = email_message.EmailMessage(mail_from, mail_to, subject,
286
 
                                             body)
 
276
            body)
287
277
        return message
288
278
 
289
279
    def install_revisions(self, target_repo):
309
299
                                           info.real_revisions)
310
300
                    for revision in info.real_revisions:
311
301
                        for parent_id in revision.parent_ids:
312
 
                            if (parent_id not in bundle_revisions
313
 
                                    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)):
314
304
                                missing_revisions.append(parent_id)
315
305
                    # reverse missing revisions to try to get heads first
316
306
                    unique_missing = []
355
345
        elif len(self.hooks['merge_request_body']) > 0:
356
346
            trace.warning('Cannot run merge_request_body hooks because mail'
357
347
                          ' client %s does not support message bodies.',
358
 
                          mail_client.__class__.__name__)
 
348
                        mail_client.__class__.__name__)
359
349
        mail_client.compose_merge_request(to, subject,
360
 
                                          b''.join(self.to_lines()),
 
350
                                          ''.join(self.to_lines()),
361
351
                                          basename, body)
362
352
 
363
353
 
377
367
    directly using the standard patch program.
378
368
    """
379
369
 
380
 
    _format_string = b'Bazaar merge directive format 1'
 
370
    _format_string = 'Bazaar merge directive format 1'
381
371
 
382
372
    def __init__(self, revision_id, testament_sha1, time, timezone,
383
373
                 target_branch, patch=None, patch_type=None,
397
387
        :param message: The message to use when committing this merge
398
388
        """
399
389
        BaseMergeDirective.__init__(self, revision_id, testament_sha1, time,
400
 
                                    timezone, target_branch, patch, source_branch, message)
 
390
            timezone, target_branch, patch, source_branch, message)
401
391
        if patch_type not in (None, 'diff', 'bundle'):
402
392
            raise ValueError(patch_type)
403
393
        if patch_type != 'bundle' and source_branch is None:
429
419
        :return: a MergeRequest
430
420
        """
431
421
        line_iter = iter(lines)
432
 
        firstline = b""
 
422
        firstline = ""
433
423
        for line in line_iter:
434
 
            if line.startswith(b'# Bazaar merge directive format '):
 
424
            if line.startswith('# Bazaar merge directive format '):
435
425
                return _format_registry.get(line[2:].rstrip())._from_lines(
436
426
                    line_iter)
437
427
            firstline = firstline or line.strip()
445
435
            patch = None
446
436
            patch_type = None
447
437
        else:
448
 
            patch = b''.join(patch_lines)
 
438
            patch = ''.join(patch_lines)
449
439
            try:
450
440
                bundle_serializer.read_bundle(BytesIO(patch))
451
441
            except (errors.NotABundle, errors.BundleNotSupported,
462
452
            except KeyError:
463
453
                pass
464
454
        kwargs['revision_id'] = kwargs['revision_id'].encode('utf-8')
465
 
        if 'testament_sha1' in kwargs:
466
 
            kwargs['testament_sha1'] = kwargs['testament_sha1'].encode('ascii')
467
455
        return MergeDirective(time=time, timezone=timezone,
468
456
                              patch_type=patch_type, patch=patch, **kwargs)
469
457
 
490
478
 
491
479
class MergeDirective2(BaseMergeDirective):
492
480
 
493
 
    _format_string = b'Bazaar merge directive format 2 (Bazaar 0.90)'
 
481
    _format_string = 'Bazaar merge directive format 2 (Bazaar 0.90)'
494
482
 
495
483
    def __init__(self, revision_id, testament_sha1, time, timezone,
496
484
                 target_branch, patch=None, source_branch=None, message=None,
498
486
        if source_branch is None and bundle is None:
499
487
            raise errors.NoMergeSource()
500
488
        BaseMergeDirective.__init__(self, revision_id, testament_sha1, time,
501
 
                                    timezone, target_branch, patch, source_branch, message)
 
489
            timezone, target_branch, patch, source_branch, message)
502
490
        self.bundle = bundle
503
491
        self.base_revision_id = base_revision_id
504
492
 
520
508
        if self.bundle is None:
521
509
            return None
522
510
        else:
523
 
            return base64.b64decode(self.bundle)
 
511
            return self.bundle.decode('base-64')
524
512
 
525
513
    @classmethod
526
514
    def _from_lines(klass, line_iter):
532
520
        except StopIteration:
533
521
            pass
534
522
        else:
535
 
            if start.startswith(b'# Begin patch'):
 
523
            if start.startswith('# Begin patch'):
536
524
                patch_lines = []
537
525
                for line in line_iter:
538
 
                    if line.startswith(b'# Begin bundle'):
 
526
                    if line.startswith('# Begin bundle'):
539
527
                        start = line
540
528
                        break
541
529
                    patch_lines.append(line)
542
530
                else:
543
531
                    start = None
544
 
                patch = b''.join(patch_lines)
 
532
                patch = ''.join(patch_lines)
545
533
            if start is not None:
546
 
                if start.startswith(b'# Begin bundle'):
547
 
                    bundle = b''.join(line_iter)
 
534
                if start.startswith('# Begin bundle'):
 
535
                    bundle = ''.join(line_iter)
548
536
                else:
549
537
                    raise errors.IllegalMergeDirectivePayload(start)
550
538
        time, timezone = timestamp.parse_patch_date(stanza.get('timestamp'))
558
546
        kwargs['revision_id'] = kwargs['revision_id'].encode('utf-8')
559
547
        kwargs['base_revision_id'] =\
560
548
            kwargs['base_revision_id'].encode('utf-8')
561
 
        if 'testament_sha1' in kwargs:
562
 
            kwargs['testament_sha1'] = kwargs['testament_sha1'].encode('ascii')
563
549
        return klass(time=time, timezone=timezone, patch=patch, bundle=bundle,
564
550
                     **kwargs)
565
551
 
566
552
    def to_lines(self):
567
553
        lines = self._to_lines(base_revision=True)
568
554
        if self.patch is not None:
569
 
            lines.append(b'# Begin patch\n')
 
555
            lines.append('# Begin patch\n')
570
556
            lines.extend(self.patch.splitlines(True))
571
557
        if self.bundle is not None:
572
 
            lines.append(b'# Begin bundle\n')
 
558
            lines.append('# Begin bundle\n')
573
559
            lines.extend(self.bundle.splitlines(True))
574
560
        return lines
575
561
 
576
562
    @classmethod
577
563
    def from_objects(klass, repository, revision_id, time, timezone,
578
 
                     target_branch, include_patch=True, include_bundle=True,
579
 
                     local_target_branch=None, public_branch=None, message=None,
580
 
                     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):
581
567
        """Generate a merge directive from various objects
582
568
 
583
569
        :param repository: The repository containing the revision
599
585
        If the message is not supplied, the message from revision_id will be
600
586
        used for the commit.
601
587
        """
602
 
        with cleanup.ExitStack() as exit_stack:
603
 
            exit_stack.enter_context(repository.lock_write())
 
588
        locked = []
 
589
        try:
 
590
            repository.lock_write()
 
591
            locked.append(repository)
604
592
            t_revision_id = revision_id
605
 
            if revision_id == b'null:':
 
593
            if revision_id == 'null:':
606
594
                t_revision_id = None
607
595
            t = testament.StrictTestament3.from_revision(repository,
608
 
                                                         t_revision_id)
 
596
                t_revision_id)
609
597
            if local_target_branch is None:
610
598
                submit_branch = _mod_branch.Branch.open(target_branch)
611
599
            else:
612
600
                submit_branch = local_target_branch
613
 
            exit_stack.enter_context(submit_branch.lock_read())
 
601
            submit_branch.lock_read()
 
602
            locked.append(submit_branch)
614
603
            if submit_branch.get_public_branch() is not None:
615
604
                target_branch = submit_branch.get_public_branch()
616
605
            submit_revision_id = submit_branch.last_revision()
629
618
                patch = None
630
619
 
631
620
            if include_bundle:
632
 
                bundle = base64.b64encode(klass._generate_bundle(repository, revision_id,
633
 
                                                                 ancestor_id))
 
621
                bundle = klass._generate_bundle(repository, revision_id,
 
622
                    ancestor_id).encode('base-64')
634
623
            else:
635
624
                bundle = None
636
625
 
637
626
            if public_branch is not None and not include_bundle:
638
627
                public_branch_obj = _mod_branch.Branch.open(public_branch)
639
 
                exit_stack.enter_context(public_branch_obj.lock_read())
 
628
                public_branch_obj.lock_read()
 
629
                locked.append(public_branch_obj)
640
630
                if not public_branch_obj.repository.has_revision(
641
 
                        revision_id):
 
631
                    revision_id):
642
632
                    raise errors.PublicBranchOutOfDate(public_branch,
643
633
                                                       revision_id)
644
634
            testament_sha1 = t.as_sha1()
 
635
        finally:
 
636
            for entry in reversed(locked):
 
637
                entry.unlock()
645
638
        return klass(revision_id, testament_sha1, time, timezone,
646
 
                     target_branch, patch, public_branch, message, bundle,
647
 
                     base_revision_id)
 
639
            target_branch, patch, public_branch, message, bundle,
 
640
            base_revision_id)
648
641
 
649
642
    def _verify_patch(self, repository):
650
643
        calculated_patch = self._generate_diff(repository, self.revision_id,
651
644
                                               self.base_revision_id)
652
645
        # Convert line-endings to UNIX
653
 
        stored_patch = re.sub(b'\r\n?', b'\n', self.patch)
654
 
        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)
655
648
        # Strip trailing whitespace
656
 
        calculated_patch = re.sub(b' *\n', b'\n', calculated_patch)
657
 
        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)
658
651
        return (calculated_patch == stored_patch)
659
652
 
660
653
    def get_merge_request(self, repository):
690
683
# already merge directives in the wild that used 0.19. Registering with the old
691
684
# format string to retain compatibility with those merge directives.
692
685
_format_registry.register(MergeDirective2,
693
 
                          b'Bazaar merge directive format 2 (Bazaar 0.19)')
 
686
                          'Bazaar merge directive format 2 (Bazaar 0.19)')