~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/merge_directive.py

  • Committer: Aaron Bentley
  • Date: 2012-07-19 16:57:16 UTC
  • mto: This revision was merged to the branch mainline in revision 6540.
  • Revision ID: aaron@aaronbentley.com-20120719165716-b4iupzkb17b9l9wx
Avoid branch write lock to preserve VFS call count.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2007 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
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
 
17
from __future__ import absolute_import
17
18
 
18
19
from StringIO import StringIO
19
20
import re
20
21
 
 
22
from bzrlib import lazy_import
 
23
lazy_import.lazy_import(globals(), """
21
24
from bzrlib import (
22
25
    branch as _mod_branch,
23
26
    diff,
 
27
    email_message,
24
28
    errors,
25
29
    gpg,
 
30
    hooks,
26
31
    registry,
27
32
    revision as _mod_revision,
28
33
    rio,
29
34
    testament,
30
35
    timestamp,
 
36
    trace,
31
37
    )
32
38
from bzrlib.bundle import (
33
39
    serializer as bundle_serializer,
34
40
    )
35
 
from bzrlib.email_message import EmailMessage
36
 
 
37
 
 
38
 
class _BaseMergeDirective(object):
 
41
""")
 
42
 
 
43
 
 
44
class MergeRequestBodyParams(object):
 
45
    """Parameter object for the merge_request_body hook."""
 
46
 
 
47
    def __init__(self, body, orig_body, directive, to, basename, subject,
 
48
                 branch, tree=None):
 
49
        self.body = body
 
50
        self.orig_body = orig_body
 
51
        self.directive = directive
 
52
        self.branch = branch
 
53
        self.tree = tree
 
54
        self.to = to
 
55
        self.basename = basename
 
56
        self.subject = subject
 
57
 
 
58
 
 
59
class MergeDirectiveHooks(hooks.Hooks):
 
60
    """Hooks for MergeDirective classes."""
 
61
 
 
62
    def __init__(self):
 
63
        hooks.Hooks.__init__(self, "bzrlib.merge_directive", "BaseMergeDirective.hooks")
 
64
        self.add_hook('merge_request_body',
 
65
            "Called with a MergeRequestBodyParams when a body is needed for"
 
66
            " a merge request.  Callbacks must return a body.  If more"
 
67
            " than one callback is registered, the output of one callback is"
 
68
            " provided to the next.", (1, 15, 0))
 
69
 
 
70
 
 
71
class BaseMergeDirective(object):
 
72
    """A request to perform a merge into a branch.
 
73
 
 
74
    This is the base class that all merge directive implementations 
 
75
    should derive from.
 
76
 
 
77
    :cvar multiple_output_files: Whether or not this merge directive 
 
78
        stores a set of revisions in more than one file
 
79
    """
 
80
 
 
81
    hooks = MergeDirectiveHooks()
 
82
 
 
83
    multiple_output_files = False
39
84
 
40
85
    def __init__(self, revision_id, testament_sha1, time, timezone,
41
 
                 target_branch, patch=None, source_branch=None, message=None,
42
 
                 bundle=None):
 
86
                 target_branch, patch=None, source_branch=None,
 
87
                 message=None, bundle=None):
43
88
        """Constructor.
44
89
 
45
90
        :param revision_id: The revision to merge
47
92
            merge.
48
93
        :param time: The current POSIX timestamp time
49
94
        :param timezone: The timezone offset
50
 
        :param target_branch: The branch to apply the merge to
 
95
        :param target_branch: Location of branch to apply the merge to
51
96
        :param patch: The text of a diff or bundle
52
97
        :param source_branch: A public location to merge the revision from
53
98
        :param message: The message to use when committing this merge
61
106
        self.source_branch = source_branch
62
107
        self.message = message
63
108
 
 
109
    def to_lines(self):
 
110
        """Serialize as a list of lines
 
111
 
 
112
        :return: a list of lines
 
113
        """
 
114
        raise NotImplementedError(self.to_lines)
 
115
 
 
116
    def to_files(self):
 
117
        """Serialize as a set of files.
 
118
 
 
119
        :return: List of tuples with filename and contents as lines
 
120
        """
 
121
        raise NotImplementedError(self.to_files)
 
122
 
 
123
    def get_raw_bundle(self):
 
124
        """Return the bundle for this merge directive.
 
125
 
 
126
        :return: bundle text or None if there is no bundle
 
127
        """
 
128
        return None
 
129
 
64
130
    def _to_lines(self, base_revision=False):
65
131
        """Serialize as a list of lines
66
132
 
80
146
        lines.append('# \n')
81
147
        return lines
82
148
 
 
149
    def write_to_directory(self, path):
 
150
        """Write this merge directive to a series of files in a directory.
 
151
 
 
152
        :param path: Filesystem path to write to
 
153
        """
 
154
        raise NotImplementedError(self.write_to_directory)
 
155
 
83
156
    @classmethod
84
157
    def from_objects(klass, repository, revision_id, time, timezone,
85
158
                 target_branch, patch_type='bundle',
93
166
        :param target_branch: The url of the branch to merge into
94
167
        :param patch_type: 'bundle', 'diff' or None, depending on the type of
95
168
            patch desired.
96
 
        :param local_target_branch: a local copy of the target branch
97
 
        :param public_branch: location of a public branch containing the target
98
 
            revision.
 
169
        :param local_target_branch: the submit branch, either itself or a local copy
 
170
        :param public_branch: location of a public branch containing
 
171
            the target revision.
99
172
        :param message: Message to use when committing the merge
100
173
        :return: The merge directive
101
174
 
109
182
        if revision_id == _mod_revision.NULL_REVISION:
110
183
            t_revision_id = None
111
184
        t = testament.StrictTestament3.from_revision(repository, t_revision_id)
112
 
        submit_branch = _mod_branch.Branch.open(target_branch)
 
185
        if local_target_branch is None:
 
186
            submit_branch = _mod_branch.Branch.open(target_branch)
 
187
        else:
 
188
            submit_branch = local_target_branch
113
189
        if submit_branch.get_public_branch() is not None:
114
190
            target_branch = submit_branch.get_public_branch()
115
191
        if patch_type is None:
148
224
        else:
149
225
            revno = branch.get_revision_id_to_revno_map().get(self.revision_id,
150
226
                ['merge'])
151
 
        return '%s-%s' % (branch.nick, '.'.join(str(n) for n in revno))
 
227
        nick = re.sub('(\W+)', '-', branch.nick).strip('-')
 
228
        return '%s-%s' % (nick, '.'.join(str(n) for n in revno))
152
229
 
153
230
    @staticmethod
154
231
    def _generate_diff(repository, revision_id, ancestor_id):
171
248
        :param branch: The source branch, to get the signing strategy
172
249
        :return: a string
173
250
        """
174
 
        my_gpg = gpg.GPGStrategy(branch.get_config())
 
251
        my_gpg = gpg.GPGStrategy(branch.get_config_stack())
175
252
        return my_gpg.sign(''.join(self.to_lines()))
176
253
 
177
254
    def to_email(self, mail_to, branch, sign=False):
183
260
        :param sign: If True, gpg-sign the email
184
261
        :return: an email message
185
262
        """
186
 
        mail_from = branch.get_config().username()
 
263
        mail_from = branch.get_config_stack().get('email')
187
264
        if self.message is not None:
188
265
            subject = self.message
189
266
        else:
193
270
            body = self.to_signed(branch)
194
271
        else:
195
272
            body = ''.join(self.to_lines())
196
 
        message = EmailMessage(mail_from, mail_to, subject, body)
 
273
        message = email_message.EmailMessage(mail_from, mail_to, subject,
 
274
            body)
197
275
        return message
198
276
 
199
277
    def install_revisions(self, target_repo):
209
287
                except errors.RevisionNotPresent:
210
288
                    # At least one dependency isn't present.  Try installing
211
289
                    # missing revisions from the submit branch
212
 
                    submit_branch = _mod_branch.Branch.open(self.target_branch)
 
290
                    try:
 
291
                        submit_branch = \
 
292
                            _mod_branch.Branch.open(self.target_branch)
 
293
                    except errors.NotBranchError:
 
294
                        raise errors.TargetNotBranch(self.target_branch)
213
295
                    missing_revisions = []
214
296
                    bundle_revisions = set(r.revision_id for r in
215
297
                                           info.real_revisions)
235
317
                target_repo.fetch(source_branch.repository, self.revision_id)
236
318
        return self.revision_id
237
319
 
238
 
 
239
 
class MergeDirective(_BaseMergeDirective):
 
320
    def compose_merge_request(self, mail_client, to, body, branch, tree=None):
 
321
        """Compose a request to merge this directive.
 
322
 
 
323
        :param mail_client: The mail client to use for composing this request.
 
324
        :param to: The address to compose the request to.
 
325
        :param branch: The Branch that was used to produce this directive.
 
326
        :param tree: The Tree (if any) for the Branch used to produce this
 
327
            directive.
 
328
        """
 
329
        basename = self.get_disk_name(branch)
 
330
        subject = '[MERGE] '
 
331
        if self.message is not None:
 
332
            subject += self.message
 
333
        else:
 
334
            revision = branch.repository.get_revision(self.revision_id)
 
335
            subject += revision.get_summary()
 
336
        if getattr(mail_client, 'supports_body', False):
 
337
            orig_body = body
 
338
            for hook in self.hooks['merge_request_body']:
 
339
                params = MergeRequestBodyParams(body, orig_body, self,
 
340
                                                to, basename, subject, branch,
 
341
                                                tree)
 
342
                body = hook(params)
 
343
        elif len(self.hooks['merge_request_body']) > 0:
 
344
            trace.warning('Cannot run merge_request_body hooks because mail'
 
345
                          ' client %s does not support message bodies.',
 
346
                        mail_client.__class__.__name__)
 
347
        mail_client.compose_merge_request(to, subject,
 
348
                                          ''.join(self.to_lines()),
 
349
                                          basename, body)
 
350
 
 
351
 
 
352
class MergeDirective(BaseMergeDirective):
240
353
 
241
354
    """A request to perform a merge into a branch.
242
355
 
264
377
            merge.
265
378
        :param time: The current POSIX timestamp time
266
379
        :param timezone: The timezone offset
267
 
        :param target_branch: The branch to apply the merge to
 
380
        :param target_branch: Location of the branch to apply the merge to
268
381
        :param patch: The text of a diff or bundle
269
382
        :param patch_type: None, "diff" or "bundle", depending on the contents
270
383
            of patch
271
384
        :param source_branch: A public location to merge the revision from
272
385
        :param message: The message to use when committing this merge
273
386
        """
274
 
        _BaseMergeDirective.__init__(self, revision_id, testament_sha1, time,
 
387
        BaseMergeDirective.__init__(self, revision_id, testament_sha1, time,
275
388
            timezone, target_branch, patch, source_branch, message)
276
389
        if patch_type not in (None, 'diff', 'bundle'):
277
390
            raise ValueError(patch_type)
304
417
        :return: a MergeRequest
305
418
        """
306
419
        line_iter = iter(lines)
 
420
        firstline = ""
307
421
        for line in line_iter:
308
422
            if line.startswith('# Bazaar merge directive format '):
309
 
                break
310
 
        else:
311
 
            if len(lines) > 0:
312
 
                raise errors.NotAMergeDirective(lines[0])
313
 
            else:
314
 
                raise errors.NotAMergeDirective('')
315
 
        return _format_registry.get(line[2:].rstrip())._from_lines(line_iter)
 
423
                return _format_registry.get(line[2:].rstrip())._from_lines(
 
424
                    line_iter)
 
425
            firstline = firstline or line.strip()
 
426
        raise errors.NotAMergeDirective(firstline)
316
427
 
317
428
    @classmethod
318
429
    def _from_lines(klass, line_iter):
363
474
        return None, self.revision_id, 'inapplicable'
364
475
 
365
476
 
366
 
class MergeDirective2(_BaseMergeDirective):
 
477
class MergeDirective2(BaseMergeDirective):
367
478
 
368
479
    _format_string = 'Bazaar merge directive format 2 (Bazaar 0.90)'
369
480
 
372
483
                 bundle=None, base_revision_id=None):
373
484
        if source_branch is None and bundle is None:
374
485
            raise errors.NoMergeSource()
375
 
        _BaseMergeDirective.__init__(self, revision_id, testament_sha1, time,
 
486
        BaseMergeDirective.__init__(self, revision_id, testament_sha1, time,
376
487
            timezone, target_branch, patch, source_branch, message)
377
488
        self.bundle = bundle
378
489
        self.base_revision_id = base_revision_id
460
571
        :param target_branch: The url of the branch to merge into
461
572
        :param include_patch: If true, include a preview patch
462
573
        :param include_bundle: If true, include a bundle
463
 
        :param local_target_branch: a local copy of the target branch
464
 
        :param public_branch: location of a public branch containing the target
465
 
            revision.
 
574
        :param local_target_branch: the target branch, either itself or a local copy
 
575
        :param public_branch: location of a public branch containing
 
576
            the target revision.
466
577
        :param message: Message to use when committing the merge
467
578
        :return: The merge directive
468
579
 
481
592
                t_revision_id = None
482
593
            t = testament.StrictTestament3.from_revision(repository,
483
594
                t_revision_id)
484
 
            submit_branch = _mod_branch.Branch.open(target_branch)
 
595
            if local_target_branch is None:
 
596
                submit_branch = _mod_branch.Branch.open(target_branch)
 
597
            else:
 
598
                submit_branch = local_target_branch
485
599
            submit_branch.lock_read()
486
600
            locked.append(submit_branch)
487
601
            if submit_branch.get_public_branch() is not None:
515
629
                    revision_id):
516
630
                    raise errors.PublicBranchOutOfDate(public_branch,
517
631
                                                       revision_id)
 
632
            testament_sha1 = t.as_sha1()
518
633
        finally:
519
634
            for entry in reversed(locked):
520
635
                entry.unlock()
521
 
        return klass(revision_id, t.as_sha1(), time, timezone, target_branch,
522
 
            patch, public_branch, message, bundle, base_revision_id)
 
636
        return klass(revision_id, testament_sha1, time, timezone,
 
637
            target_branch, patch, public_branch, message, bundle,
 
638
            base_revision_id)
523
639
 
524
640
    def _verify_patch(self, repository):
525
641
        calculated_patch = self._generate_diff(repository, self.revision_id,
561
677
_format_registry = MergeDirectiveFormatRegistry()
562
678
_format_registry.register(MergeDirective)
563
679
_format_registry.register(MergeDirective2)
 
680
# 0.19 never existed.  It got renamed to 0.90.  But by that point, there were
 
681
# already merge directives in the wild that used 0.19. Registering with the old
 
682
# format string to retain compatibility with those merge directives.
564
683
_format_registry.register(MergeDirective2,
565
684
                          'Bazaar merge directive format 2 (Bazaar 0.19)')