/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 bzrlib/merge_directive.py

  • Committer: Richard Wilbur
  • Date: 2016-02-04 19:07:28 UTC
  • mto: This revision was merged to the branch mainline in revision 6618.
  • Revision ID: richard.wilbur@gmail.com-20160204190728-p0zvfii6zase0fw7
Update COPYING.txt from the original http://www.gnu.org/licenses/gpl-2.0.txt  (Only differences were in whitespace.)  Thanks to Petr Stodulka for pointing out the discrepancy.

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