/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: Robert Collins
  • Date: 2010-05-06 11:08:10 UTC
  • mto: This revision was merged to the branch mainline in revision 5223.
  • Revision ID: robertc@robertcollins.net-20100506110810-h3j07fh5gmw54s25
Cleaner matcher matching revised unlocking protocol.

Show diffs side-by-side

added added

removed removed

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