~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/merge_directive.py

NEWS section template into a separate file

Show diffs side-by-side

added added

removed removed

Lines of Context:
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
17
 
18
18
from StringIO import StringIO
23
23
    diff,
24
24
    errors,
25
25
    gpg,
 
26
    hooks,
26
27
    registry,
27
28
    revision as _mod_revision,
28
29
    rio,
29
30
    testament,
30
31
    timestamp,
 
32
    trace,
31
33
    )
32
34
from bzrlib.bundle import (
33
35
    serializer as bundle_serializer,
35
37
from bzrlib.email_message import EmailMessage
36
38
 
37
39
 
 
40
class MergeRequestBodyParams(object):
 
41
    """Parameter object for the merge_request_body hook."""
 
42
 
 
43
    def __init__(self, body, orig_body, directive, to, basename, subject,
 
44
                 branch, tree=None):
 
45
        self.body = body
 
46
        self.orig_body = orig_body
 
47
        self.directive = directive
 
48
        self.branch = branch
 
49
        self.tree = tree
 
50
        self.to = to
 
51
        self.basename = basename
 
52
        self.subject = subject
 
53
 
 
54
 
 
55
class MergeDirectiveHooks(hooks.Hooks):
 
56
    """Hooks for MergeDirective classes."""
 
57
 
 
58
    def __init__(self):
 
59
        hooks.Hooks.__init__(self)
 
60
        self.create_hook(hooks.HookPoint('merge_request_body',
 
61
            "Called with a MergeRequestBodyParams when a body is needed for"
 
62
            " a merge request.  Callbacks must return a body.  If more"
 
63
            " than one callback is registered, the output of one callback is"
 
64
            " provided to the next.", (1, 15, 0), False))
 
65
 
 
66
 
38
67
class _BaseMergeDirective(object):
39
68
 
 
69
    hooks = MergeDirectiveHooks()
 
70
 
40
71
    def __init__(self, revision_id, testament_sha1, time, timezone,
41
72
                 target_branch, patch=None, source_branch=None, message=None,
42
73
                 bundle=None):
136
167
        return klass(revision_id, t.as_sha1(), time, timezone, target_branch,
137
168
            patch, patch_type, public_branch, message)
138
169
 
 
170
    def get_disk_name(self, branch):
 
171
        """Generate a suitable basename for storing this directive on disk
 
172
 
 
173
        :param branch: The Branch this merge directive was generated fro
 
174
        :return: A string
 
175
        """
 
176
        revno, revision_id = branch.last_revision_info()
 
177
        if self.revision_id == revision_id:
 
178
            revno = [revno]
 
179
        else:
 
180
            revno = branch.get_revision_id_to_revno_map().get(self.revision_id,
 
181
                ['merge'])
 
182
        nick = re.sub('(\W+)', '-', branch.nick).strip('-')
 
183
        return '%s-%s' % (nick, '.'.join(str(n) for n in revno))
 
184
 
139
185
    @staticmethod
140
186
    def _generate_diff(repository, revision_id, ancestor_id):
141
187
        tree_1 = repository.revision_tree(ancestor_id)
190
236
                    StringIO(self.get_raw_bundle()))
191
237
                # We don't use the bundle's target revision, because
192
238
                # MergeDirective.revision_id is authoritative.
193
 
                info.install_revisions(target_repo, stream_input=False)
 
239
                try:
 
240
                    info.install_revisions(target_repo, stream_input=False)
 
241
                except errors.RevisionNotPresent:
 
242
                    # At least one dependency isn't present.  Try installing
 
243
                    # missing revisions from the submit branch
 
244
                    try:
 
245
                        submit_branch = \
 
246
                            _mod_branch.Branch.open(self.target_branch)
 
247
                    except errors.NotBranchError:
 
248
                        raise errors.TargetNotBranch(self.target_branch)
 
249
                    missing_revisions = []
 
250
                    bundle_revisions = set(r.revision_id for r in
 
251
                                           info.real_revisions)
 
252
                    for revision in info.real_revisions:
 
253
                        for parent_id in revision.parent_ids:
 
254
                            if (parent_id not in bundle_revisions and
 
255
                                not target_repo.has_revision(parent_id)):
 
256
                                missing_revisions.append(parent_id)
 
257
                    # reverse missing revisions to try to get heads first
 
258
                    unique_missing = []
 
259
                    unique_missing_set = set()
 
260
                    for revision in reversed(missing_revisions):
 
261
                        if revision in unique_missing_set:
 
262
                            continue
 
263
                        unique_missing.append(revision)
 
264
                        unique_missing_set.add(revision)
 
265
                    for missing_revision in unique_missing:
 
266
                        target_repo.fetch(submit_branch.repository,
 
267
                                          missing_revision)
 
268
                    info.install_revisions(target_repo, stream_input=False)
194
269
            else:
195
270
                source_branch = _mod_branch.Branch.open(self.source_branch)
196
271
                target_repo.fetch(source_branch.repository, self.revision_id)
197
272
        return self.revision_id
198
273
 
 
274
    def compose_merge_request(self, mail_client, to, body, branch, tree=None):
 
275
        """Compose a request to merge this directive.
 
276
 
 
277
        :param mail_client: The mail client to use for composing this request.
 
278
        :param to: The address to compose the request to.
 
279
        :param branch: The Branch that was used to produce this directive.
 
280
        :param tree: The Tree (if any) for the Branch used to produce this
 
281
            directive.
 
282
        """
 
283
        basename = self.get_disk_name(branch)
 
284
        subject = '[MERGE] '
 
285
        if self.message is not None:
 
286
            subject += self.message
 
287
        else:
 
288
            revision = branch.repository.get_revision(self.revision_id)
 
289
            subject += revision.get_summary()
 
290
        if getattr(mail_client, 'supports_body', False):
 
291
            orig_body = body
 
292
            for hook in self.hooks['merge_request_body']:
 
293
                params = MergeRequestBodyParams(body, orig_body, self,
 
294
                                                to, basename, subject, branch,
 
295
                                                tree)
 
296
                body = hook(params)
 
297
        elif len(self.hooks['merge_request_body']) > 0:
 
298
            trace.warning('Cannot run merge_request_body hooks because mail'
 
299
                          ' client %s does not support message bodies.',
 
300
                        mail_client.__class__.__name__)
 
301
        mail_client.compose_merge_request(to, subject,
 
302
                                          ''.join(self.to_lines()),
 
303
                                          basename, body)
 
304
 
199
305
 
200
306
class MergeDirective(_BaseMergeDirective):
201
307
 
234
340
        """
235
341
        _BaseMergeDirective.__init__(self, revision_id, testament_sha1, time,
236
342
            timezone, target_branch, patch, source_branch, message)
237
 
        assert patch_type in (None, 'diff', 'bundle'), patch_type
 
343
        if patch_type not in (None, 'diff', 'bundle'):
 
344
            raise ValueError(patch_type)
238
345
        if patch_type != 'bundle' and source_branch is None:
239
346
            raise errors.NoMergeSource()
240
347
        if patch_type is not None and patch is None:
475
582
                    revision_id):
476
583
                    raise errors.PublicBranchOutOfDate(public_branch,
477
584
                                                       revision_id)
 
585
            testament_sha1 = t.as_sha1()
478
586
        finally:
479
587
            for entry in reversed(locked):
480
588
                entry.unlock()
481
 
        return klass(revision_id, t.as_sha1(), time, timezone, target_branch,
482
 
            patch, public_branch, message, bundle, base_revision_id)
 
589
        return klass(revision_id, testament_sha1, time, timezone,
 
590
            target_branch, patch, public_branch, message, bundle,
 
591
            base_revision_id)
483
592
 
484
593
    def _verify_patch(self, repository):
485
594
        calculated_patch = self._generate_diff(repository, self.revision_id,
521
630
_format_registry = MergeDirectiveFormatRegistry()
522
631
_format_registry.register(MergeDirective)
523
632
_format_registry.register(MergeDirective2)
 
633
# 0.19 never existed.  It got renamed to 0.90.  But by that point, there were
 
634
# already merge directives in the wild that used 0.19. Registering with the old
 
635
# format string to retain compatibility with those merge directives.
524
636
_format_registry.register(MergeDirective2,
525
637
                          'Bazaar merge directive format 2 (Bazaar 0.19)')