/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: Aaron Bentley
  • Date: 2007-06-26 19:31:00 UTC
  • mto: (2520.5.2 bzr.mpbundle)
  • mto: This revision was merged to the branch mainline in revision 2631.
  • Revision ID: abentley@panoramicfeedback.com-20070626193100-d6lhaut5mixlzw5r
Use a registry to look up xml serializers by format

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2007 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
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
 
16
 
 
17
 
 
18
from email import Message
 
19
from StringIO import StringIO
 
20
 
 
21
from bzrlib import (
 
22
    branch as _mod_branch,
 
23
    diff,
 
24
    errors,
 
25
    gpg,
 
26
    registry,
 
27
    revision as _mod_revision,
 
28
    rio,
 
29
    testament,
 
30
    timestamp,
 
31
    )
 
32
from bzrlib.bundle import (
 
33
    serializer as bundle_serializer,
 
34
    )
 
35
 
 
36
 
 
37
class _BaseMergeDirective(object):
 
38
 
 
39
    def __init__(self, revision_id, testament_sha1, time, timezone,
 
40
                 target_branch, patch=None, source_branch=None, message=None,
 
41
                 bundle=None):
 
42
        """Constructor.
 
43
 
 
44
        :param revision_id: The revision to merge
 
45
        :param testament_sha1: The sha1 of the testament of the revision to
 
46
            merge.
 
47
        :param time: The current POSIX timestamp time
 
48
        :param timezone: The timezone offset
 
49
        :param target_branch: The branch to apply the merge to
 
50
        :param patch: The text of a diff or bundle
 
51
        :param source_branch: A public location to merge the revision from
 
52
        :param message: The message to use when committing this merge
 
53
        """
 
54
        self.revision_id = revision_id
 
55
        self.testament_sha1 = testament_sha1
 
56
        self.time = time
 
57
        self.timezone = timezone
 
58
        self.target_branch = target_branch
 
59
        self.patch = patch
 
60
        self.source_branch = source_branch
 
61
        self.message = message
 
62
 
 
63
    def _to_lines(self):
 
64
        """Serialize as a list of lines
 
65
 
 
66
        :return: a list of lines
 
67
        """
 
68
        time_str = timestamp.format_patch_date(self.time, self.timezone)
 
69
        stanza = rio.Stanza(revision_id=self.revision_id, timestamp=time_str,
 
70
                            target_branch=self.target_branch,
 
71
                            testament_sha1=self.testament_sha1)
 
72
        for key in ('source_branch', 'message'):
 
73
            if self.__dict__[key] is not None:
 
74
                stanza.add(key, self.__dict__[key])
 
75
        lines = ['# ' + self._format_string + '\n']
 
76
        lines.extend(rio.to_patch_lines(stanza))
 
77
        lines.append('# \n')
 
78
        return lines
 
79
 
 
80
    @classmethod
 
81
    def from_objects(klass, repository, revision_id, time, timezone,
 
82
                 target_branch, patch_type='bundle',
 
83
                 local_target_branch=None, public_branch=None, message=None):
 
84
        """Generate a merge directive from various objects
 
85
 
 
86
        :param repository: The repository containing the revision
 
87
        :param revision_id: The revision to merge
 
88
        :param time: The POSIX timestamp of the date the request was issued.
 
89
        :param timezone: The timezone of the request
 
90
        :param target_branch: The url of the branch to merge into
 
91
        :param patch_type: 'bundle', 'diff' or None, depending on the type of
 
92
            patch desired.
 
93
        :param local_target_branch: a local copy of the target branch
 
94
        :param public_branch: location of a public branch containing the target
 
95
            revision.
 
96
        :param message: Message to use when committing the merge
 
97
        :return: The merge directive
 
98
 
 
99
        The public branch is always used if supplied.  If the patch_type is
 
100
        not 'bundle', the public branch must be supplied, and will be verified.
 
101
 
 
102
        If the message is not supplied, the message from revision_id will be
 
103
        used for the commit.
 
104
        """
 
105
        t_revision_id = revision_id
 
106
        if revision_id == _mod_revision.NULL_REVISION:
 
107
            t_revision_id = None
 
108
        t = testament.StrictTestament3.from_revision(repository, t_revision_id)
 
109
        submit_branch = _mod_branch.Branch.open(target_branch)
 
110
        if submit_branch.get_public_branch() is not None:
 
111
            target_branch = submit_branch.get_public_branch()
 
112
        if patch_type is None:
 
113
            patch = None
 
114
        else:
 
115
            submit_revision_id = submit_branch.last_revision()
 
116
            submit_revision_id = _mod_revision.ensure_null(submit_revision_id)
 
117
            repository.fetch(submit_branch.repository, submit_revision_id)
 
118
            graph = repository.get_graph()
 
119
            ancestor_id = graph.find_unique_lca(revision_id,
 
120
                                                submit_revision_id)
 
121
            type_handler = {'bundle': klass._generate_bundle,
 
122
                            'diff': klass._generate_diff,
 
123
                            None: lambda x, y, z: None }
 
124
            patch = type_handler[patch_type](repository, revision_id,
 
125
                                             ancestor_id)
 
126
 
 
127
            if public_branch is not None and patch_type != 'bundle':
 
128
                public_branch_obj = _mod_branch.Branch.open(public_branch)
 
129
                if not public_branch_obj.repository.has_revision(revision_id):
 
130
                    raise errors.PublicBranchOutOfDate(public_branch,
 
131
                                                       revision_id)
 
132
 
 
133
        return klass(revision_id, t.as_sha1(), time, timezone, target_branch,
 
134
            patch, patch_type, public_branch, message)
 
135
 
 
136
    @staticmethod
 
137
    def _generate_diff(repository, revision_id, ancestor_id):
 
138
        tree_1 = repository.revision_tree(ancestor_id)
 
139
        tree_2 = repository.revision_tree(revision_id)
 
140
        s = StringIO()
 
141
        diff.show_diff_trees(tree_1, tree_2, s, old_label='', new_label='')
 
142
        return s.getvalue()
 
143
 
 
144
    @staticmethod
 
145
    def _generate_bundle(repository, revision_id, ancestor_id):
 
146
        s = StringIO()
 
147
        bundle_serializer.write_bundle(repository, revision_id,
 
148
                                       ancestor_id, s)
 
149
        return s.getvalue()
 
150
 
 
151
    def to_signed(self, branch):
 
152
        """Serialize as a signed string.
 
153
 
 
154
        :param branch: The source branch, to get the signing strategy
 
155
        :return: a string
 
156
        """
 
157
        my_gpg = gpg.GPGStrategy(branch.get_config())
 
158
        return my_gpg.sign(''.join(self.to_lines()))
 
159
 
 
160
    def to_email(self, mail_to, branch, sign=False):
 
161
        """Serialize as an email message.
 
162
 
 
163
        :param mail_to: The address to mail the message to
 
164
        :param branch: The source branch, to get the signing strategy and
 
165
            source email address
 
166
        :param sign: If True, gpg-sign the email
 
167
        :return: an email message
 
168
        """
 
169
        mail_from = branch.get_config().username()
 
170
        message = Message.Message()
 
171
        message['To'] = mail_to
 
172
        message['From'] = mail_from
 
173
        if self.message is not None:
 
174
            message['Subject'] = self.message
 
175
        else:
 
176
            revision = branch.repository.get_revision(self.revision_id)
 
177
            message['Subject'] = revision.message
 
178
        if sign:
 
179
            body = self.to_signed(branch)
 
180
        else:
 
181
            body = ''.join(self.to_lines())
 
182
        message.set_payload(body)
 
183
        return message
 
184
 
 
185
    def install_revisions(self, target_repo):
 
186
        """Install revisions and return the target revision"""
 
187
        if not target_repo.has_revision(self.revision_id):
 
188
            if self.patch_type == 'bundle':
 
189
                info = bundle_serializer.read_bundle(
 
190
                    StringIO(self.get_raw_bundle()))
 
191
                # We don't use the bundle's target revision, because
 
192
                # MergeDirective.revision_id is authoritative.
 
193
                info.install_revisions(target_repo)
 
194
            else:
 
195
                source_branch = _mod_branch.Branch.open(self.source_branch)
 
196
                target_repo.fetch(source_branch.repository, self.revision_id)
 
197
        return self.revision_id
 
198
 
 
199
 
 
200
class MergeDirective(_BaseMergeDirective):
 
201
 
 
202
    """A request to perform a merge into a branch.
 
203
 
 
204
    Designed to be serialized and mailed.  It provides all the information
 
205
    needed to perform a merge automatically, by providing at minimum a revision
 
206
    bundle or the location of a branch.
 
207
 
 
208
    The serialization format is robust against certain common forms of
 
209
    deterioration caused by mailing.
 
210
 
 
211
    The format is also designed to be patch-compatible.  If the directive
 
212
    includes a diff or revision bundle, it should be possible to apply it
 
213
    directly using the standard patch program.
 
214
    """
 
215
 
 
216
    _format_string = 'Bazaar merge directive format 1'
 
217
 
 
218
    def __init__(self, revision_id, testament_sha1, time, timezone,
 
219
                 target_branch, patch=None, patch_type=None,
 
220
                 source_branch=None, message=None, bundle=None):
 
221
        """Constructor.
 
222
 
 
223
        :param revision_id: The revision to merge
 
224
        :param testament_sha1: The sha1 of the testament of the revision to
 
225
            merge.
 
226
        :param time: The current POSIX timestamp time
 
227
        :param timezone: The timezone offset
 
228
        :param target_branch: The branch to apply the merge to
 
229
        :param patch: The text of a diff or bundle
 
230
        :param patch_type: None, "diff" or "bundle", depending on the contents
 
231
            of patch
 
232
        :param source_branch: A public location to merge the revision from
 
233
        :param message: The message to use when committing this merge
 
234
        """
 
235
        _BaseMergeDirective.__init__(self, revision_id, testament_sha1, time,
 
236
            timezone, target_branch, patch, source_branch, message)
 
237
        assert patch_type in (None, 'diff', 'bundle'), patch_type
 
238
        if patch_type != 'bundle' and source_branch is None:
 
239
            raise errors.NoMergeSource()
 
240
        if patch_type is not None and patch is None:
 
241
            raise errors.PatchMissing(patch_type)
 
242
        self.patch_type = patch_type
 
243
 
 
244
    def clear_payload(self):
 
245
        self.patch = None
 
246
        self.patch_type = None
 
247
 
 
248
    def get_raw_bundle(self):
 
249
        return self.bundle
 
250
 
 
251
    def _bundle(self):
 
252
        if self.patch_type == 'bundle':
 
253
            return self.patch
 
254
        else:
 
255
            return None
 
256
 
 
257
    bundle = property(_bundle)
 
258
 
 
259
    @classmethod
 
260
    def from_lines(klass, lines):
 
261
        """Deserialize a MergeRequest from an iterable of lines
 
262
 
 
263
        :param lines: An iterable of lines
 
264
        :return: a MergeRequest
 
265
        """
 
266
        line_iter = iter(lines)
 
267
        for line in line_iter:
 
268
            if line.startswith('# Bazaar merge directive format '):
 
269
                break
 
270
        else:
 
271
            if len(lines) > 0:
 
272
                raise errors.NotAMergeDirective(lines[0])
 
273
            else:
 
274
                raise errors.NotAMergeDirective('')
 
275
        return _format_registry.get(line[2:].rstrip())._from_lines(line_iter)
 
276
 
 
277
    @classmethod
 
278
    def _from_lines(klass, line_iter):
 
279
        stanza = rio.read_patch_stanza(line_iter)
 
280
        patch_lines = list(line_iter)
 
281
        if len(patch_lines) == 0:
 
282
            patch = None
 
283
            patch_type = None
 
284
        else:
 
285
            patch = ''.join(patch_lines)
 
286
            try:
 
287
                bundle_serializer.read_bundle(StringIO(patch))
 
288
            except (errors.NotABundle, errors.BundleNotSupported,
 
289
                    errors.BadBundle):
 
290
                patch_type = 'diff'
 
291
            else:
 
292
                patch_type = 'bundle'
 
293
        time, timezone = timestamp.parse_patch_date(stanza.get('timestamp'))
 
294
        kwargs = {}
 
295
        for key in ('revision_id', 'testament_sha1', 'target_branch',
 
296
                    'source_branch', 'message'):
 
297
            try:
 
298
                kwargs[key] = stanza.get(key)
 
299
            except KeyError:
 
300
                pass
 
301
        kwargs['revision_id'] = kwargs['revision_id'].encode('utf-8')
 
302
        return MergeDirective(time=time, timezone=timezone,
 
303
                              patch_type=patch_type, patch=patch, **kwargs)
 
304
 
 
305
    def to_lines(self):
 
306
        lines = self._to_lines()
 
307
        if self.patch is not None:
 
308
            lines.extend(self.patch.splitlines(True))
 
309
        return lines
 
310
 
 
311
    @staticmethod
 
312
    def _generate_bundle(repository, revision_id, ancestor_id):
 
313
        s = StringIO()
 
314
        bundle_serializer.write_bundle(repository, revision_id,
 
315
                                       ancestor_id, s, '0.9')
 
316
        return s.getvalue()
 
317
 
 
318
 
 
319
class MergeDirective2(_BaseMergeDirective):
 
320
 
 
321
    _format_string = 'Bazaar merge directive format 2 (Bazaar 0.18)'
 
322
 
 
323
    def __init__(self, revision_id, testament_sha1, time, timezone,
 
324
                 target_branch, patch=None, source_branch=None, message=None,
 
325
                 bundle=None):
 
326
        if source_branch is None and bundle is None:
 
327
            raise errors.NoMergeSource()
 
328
        _BaseMergeDirective.__init__(self, revision_id, testament_sha1, time,
 
329
            timezone, target_branch, patch, source_branch, message)
 
330
        self.bundle = bundle
 
331
 
 
332
    def _patch_type(self):
 
333
        if self.bundle is not None:
 
334
            return 'bundle'
 
335
        elif self.patch is not None:
 
336
            return 'diff'
 
337
        else:
 
338
            return None
 
339
 
 
340
    patch_type = property(_patch_type)
 
341
 
 
342
    def clear_payload(self):
 
343
        self.patch = None
 
344
        self.bundle = None
 
345
 
 
346
    def get_raw_bundle(self):
 
347
        if self.bundle is None:
 
348
            return None
 
349
        else:
 
350
            return self.bundle.decode('base-64')
 
351
 
 
352
    @classmethod
 
353
    def _from_lines(klass, line_iter):
 
354
        stanza = rio.read_patch_stanza(line_iter)
 
355
        patch = None
 
356
        bundle = None
 
357
        try:
 
358
            start = line_iter.next()
 
359
        except StopIteration:
 
360
            pass
 
361
        else:
 
362
            if start.startswith('# Begin patch'):
 
363
                patch_lines = []
 
364
                for line in line_iter:
 
365
                    if line.startswith('# Begin bundle'):
 
366
                        start = line
 
367
                        break
 
368
                    patch_lines.append(line)
 
369
                else:
 
370
                    start = None
 
371
                patch = ''.join(patch_lines)
 
372
            if start is not None:
 
373
                if start.startswith('# Begin bundle'):
 
374
                    bundle = ''.join(line_iter)
 
375
                else:
 
376
                    raise errors.IllegalMergeDirectivePayload(start)
 
377
        time, timezone = timestamp.parse_patch_date(stanza.get('timestamp'))
 
378
        kwargs = {}
 
379
        for key in ('revision_id', 'testament_sha1', 'target_branch',
 
380
                    'source_branch', 'message'):
 
381
            try:
 
382
                kwargs[key] = stanza.get(key)
 
383
            except KeyError:
 
384
                pass
 
385
        kwargs['revision_id'] = kwargs['revision_id'].encode('utf-8')
 
386
        return klass(time=time, timezone=timezone, patch=patch, bundle=bundle,
 
387
                     **kwargs)
 
388
 
 
389
    def to_lines(self):
 
390
        lines = self._to_lines()
 
391
        if self.patch is not None:
 
392
            lines.append('# Begin patch\n')
 
393
            lines.extend(self.patch.splitlines(True))
 
394
        if self.bundle is not None:
 
395
            lines.append('# Begin bundle\n')
 
396
            lines.extend(self.bundle.splitlines(True))
 
397
        return lines
 
398
 
 
399
    @classmethod
 
400
    def from_objects(klass, repository, revision_id, time, timezone,
 
401
                 target_branch, patch_type='bundle',
 
402
                 local_target_branch=None, public_branch=None, message=None):
 
403
        """Generate a merge directive from various objects
 
404
 
 
405
        :param repository: The repository containing the revision
 
406
        :param revision_id: The revision to merge
 
407
        :param time: The POSIX timestamp of the date the request was issued.
 
408
        :param timezone: The timezone of the request
 
409
        :param target_branch: The url of the branch to merge into
 
410
        :param patch_type: 'bundle', 'diff' or None, depending on the type of
 
411
            patch desired.
 
412
        :param local_target_branch: a local copy of the target branch
 
413
        :param public_branch: location of a public branch containing the target
 
414
            revision.
 
415
        :param message: Message to use when committing the merge
 
416
        :return: The merge directive
 
417
 
 
418
        The public branch is always used if supplied.  If the patch_type is
 
419
        not 'bundle', the public branch must be supplied, and will be verified.
 
420
 
 
421
        If the message is not supplied, the message from revision_id will be
 
422
        used for the commit.
 
423
        """
 
424
        locked = []
 
425
        try:
 
426
            repository.lock_write()
 
427
            locked.append(repository)
 
428
            t_revision_id = revision_id
 
429
            if revision_id == 'null:':
 
430
                t_revision_id = None
 
431
            t = testament.StrictTestament3.from_revision(repository,
 
432
                t_revision_id)
 
433
            submit_branch = _mod_branch.Branch.open(target_branch)
 
434
            submit_branch.lock_read()
 
435
            locked.append(submit_branch)
 
436
            if submit_branch.get_public_branch() is not None:
 
437
                target_branch = submit_branch.get_public_branch()
 
438
            if patch_type is None:
 
439
                patch = None
 
440
                bundle = None
 
441
            else:
 
442
                submit_revision_id = submit_branch.last_revision()
 
443
                submit_revision_id = _mod_revision.ensure_null(
 
444
                    submit_revision_id)
 
445
                repository.fetch(submit_branch.repository, submit_revision_id)
 
446
                graph = repository.get_graph()
 
447
                ancestor_id = graph.find_unique_lca(revision_id,
 
448
                                                    submit_revision_id)
 
449
                if patch_type in ('bundle', 'diff'):
 
450
                    patch = klass._generate_diff(repository, revision_id,
 
451
                                                 ancestor_id)
 
452
                if patch_type == 'bundle':
 
453
                    bundle = klass._generate_bundle(repository, revision_id,
 
454
                        ancestor_id).encode('base-64')
 
455
                else:
 
456
                    bundle = None
 
457
 
 
458
                if public_branch is not None and patch_type != 'bundle':
 
459
                    public_branch_obj = _mod_branch.Branch.open(public_branch)
 
460
                    public_branch_obj.lock_read()
 
461
                    locked.append(public_branch_obj)
 
462
                    if not public_branch_obj.repository.has_revision(
 
463
                        revision_id):
 
464
                        raise errors.PublicBranchOutOfDate(public_branch,
 
465
                                                           revision_id)
 
466
        finally:
 
467
            for entry in reversed(locked):
 
468
                entry.unlock()
 
469
        return klass(revision_id, t.as_sha1(), time, timezone, target_branch,
 
470
            patch, public_branch, message, bundle)
 
471
 
 
472
class MergeDirectiveFormatRegistry(registry.Registry):
 
473
 
 
474
    def register(self, directive):
 
475
        registry.Registry.register(self, directive._format_string, directive)
 
476
 
 
477
 
 
478
_format_registry = MergeDirectiveFormatRegistry()
 
479
_format_registry.register(MergeDirective)
 
480
_format_registry.register(MergeDirective2)