/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
1551.12.36 by Aaron Bentley
Fix failing tests
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
1551.12.26 by Aaron Bentley
Get email working, with optional message
18
from email import Message
1551.12.2 by Aaron Bentley
Got directives round-tripping, with bundles and everything
19
from StringIO import StringIO
20
21
from bzrlib import (
1551.12.5 by Aaron Bentley
Get MergeDirective.from_objects working
22
    branch as _mod_branch,
23
    diff,
1551.12.2 by Aaron Bentley
Got directives round-tripping, with bundles and everything
24
    errors,
1551.12.16 by Aaron Bentley
Enable signing merge directives
25
    gpg,
1551.12.5 by Aaron Bentley
Get MergeDirective.from_objects working
26
    revision as _mod_revision,
1551.12.2 by Aaron Bentley
Got directives round-tripping, with bundles and everything
27
    rio,
1551.12.5 by Aaron Bentley
Get MergeDirective.from_objects working
28
    testament,
1551.12.30 by Aaron Bentley
Use patch-style dates for timestamps in merge directives
29
    timestamp,
1551.12.2 by Aaron Bentley
Got directives round-tripping, with bundles and everything
30
    )
31
from bzrlib.bundle import serializer as bundle_serializer
32
33
34
class MergeDirective(object):
35
1551.12.38 by Aaron Bentley
Add docs for MergeDirective and RIO-patch functions
36
    """A request to perform a merge into a branch.
37
38
    Designed to be serialized and mailed.  It provides all the information
39
    needed to perform a merge automatically, by providing at minimum a revision
40
    bundle or the location of a branch.
41
42
    The serialization format is robust against certain common forms of
43
    deterioration caused by mailing.
44
45
    The format is also designed to be patch-compatible.  If the directive
46
    includes a diff or revision bundle, it should be possible to apply it
47
    directly using the standard patch program.
48
    """
49
1551.12.45 by Aaron Bentley
Change format marker to not experimental
50
    _format_string = 'Bazaar merge directive format 1'
1551.12.12 by Aaron Bentley
Add format header
51
1551.12.4 by Aaron Bentley
Add failing test
52
    def __init__(self, revision_id, testament_sha1, time, timezone,
1551.12.13 by Aaron Bentley
Rename fields
53
                 target_branch, patch=None, patch_type=None,
1551.12.26 by Aaron Bentley
Get email working, with optional message
54
                 source_branch=None, message=None):
1551.12.38 by Aaron Bentley
Add docs for MergeDirective and RIO-patch functions
55
        """Constructor.
56
57
        :param revision_id: The revision to merge
58
        :param testament_sha1: The sha1 of the testament of the revision to
59
            merge.
60
        :param time: The current POSIX timestamp time
61
        :param timezone: The timezone offset
62
        :param target_branch: The branch to apply the merge to
63
        :param patch: The text of a diff or bundle
64
        :param patch_type: None, "diff" or "bundle", depending on the contents
65
            of patch
66
        :param source_branch: A public location to merge the revision from
67
        :param message: The message to use when committing this merge
68
        """
1551.12.2 by Aaron Bentley
Got directives round-tripping, with bundles and everything
69
        assert patch_type in (None, 'diff', 'bundle')
1551.12.13 by Aaron Bentley
Rename fields
70
        if patch_type != 'bundle' and source_branch is None:
1551.12.2 by Aaron Bentley
Got directives round-tripping, with bundles and everything
71
            raise errors.NoMergeSource()
72
        if patch_type is not None and patch is None:
73
            raise errors.PatchMissing(patch_type)
1551.12.4 by Aaron Bentley
Add failing test
74
        self.revision_id = revision_id
1551.12.2 by Aaron Bentley
Got directives round-tripping, with bundles and everything
75
        self.testament_sha1 = testament_sha1
1551.12.3 by Aaron Bentley
Add timestamps to merge directives
76
        self.time = time
77
        self.timezone = timezone
1551.12.13 by Aaron Bentley
Rename fields
78
        self.target_branch = target_branch
1551.12.2 by Aaron Bentley
Got directives round-tripping, with bundles and everything
79
        self.patch = patch
80
        self.patch_type = patch_type
1551.12.13 by Aaron Bentley
Rename fields
81
        self.source_branch = source_branch
1551.12.26 by Aaron Bentley
Get email working, with optional message
82
        self.message = message
1551.12.2 by Aaron Bentley
Got directives round-tripping, with bundles and everything
83
1551.12.12 by Aaron Bentley
Add format header
84
    @classmethod
85
    def from_lines(klass, lines):
1551.12.38 by Aaron Bentley
Add docs for MergeDirective and RIO-patch functions
86
        """Deserialize a MergeRequest from an iterable of lines
87
88
        :param lines: An iterable of lines
89
        :return: a MergeRequest
90
        """
1551.12.49 by Aaron Bentley
Proper error when deserializing junk
91
        if not lines[0].startswith('# ' + klass._format_string):
92
            raise errors.NotAMergeDirective(lines[0])
1551.12.12 by Aaron Bentley
Add format header
93
        line_iter = iter(lines[1:])
1551.12.2 by Aaron Bentley
Got directives round-tripping, with bundles and everything
94
        stanza = rio.read_patch_stanza(line_iter)
95
        patch_lines = list(line_iter)
96
        if len(patch_lines) == 0:
97
            patch = None
98
        else:
99
            patch = ''.join(patch_lines)
100
        try:
101
            bundle_serializer.read_bundle(StringIO(patch))
102
        except errors.NotABundle:
103
            patch_type = 'diff'
104
        else:
105
            patch_type = 'bundle'
1551.12.30 by Aaron Bentley
Use patch-style dates for timestamps in merge directives
106
        time, timezone = timestamp.parse_patch_date(stanza.get('timestamp'))
1551.12.2 by Aaron Bentley
Got directives round-tripping, with bundles and everything
107
        kwargs = {}
1551.12.13 by Aaron Bentley
Rename fields
108
        for key in ('revision_id', 'testament_sha1', 'target_branch',
1551.12.26 by Aaron Bentley
Get email working, with optional message
109
                    'source_branch', 'message'):
1551.12.2 by Aaron Bentley
Got directives round-tripping, with bundles and everything
110
            try:
111
                kwargs[key] = stanza.get(key)
112
            except KeyError:
113
                pass
1551.12.3 by Aaron Bentley
Add timestamps to merge directives
114
        return MergeDirective(time=time, timezone=timezone,
115
                              patch_type=patch_type, patch=patch, **kwargs)
1551.12.2 by Aaron Bentley
Got directives round-tripping, with bundles and everything
116
117
    def to_lines(self):
1551.12.38 by Aaron Bentley
Add docs for MergeDirective and RIO-patch functions
118
        """Serialize as a list of lines
119
120
        :return: a list of lines
121
        """
1551.12.30 by Aaron Bentley
Use patch-style dates for timestamps in merge directives
122
        time_str = timestamp.format_patch_date(self.time, self.timezone)
123
        stanza = rio.Stanza(revision_id=self.revision_id, timestamp=time_str,
1551.12.13 by Aaron Bentley
Rename fields
124
                            target_branch=self.target_branch,
1551.12.2 by Aaron Bentley
Got directives round-tripping, with bundles and everything
125
                            testament_sha1=self.testament_sha1)
1551.12.26 by Aaron Bentley
Get email working, with optional message
126
        for key in ('source_branch', 'message'):
1551.12.2 by Aaron Bentley
Got directives round-tripping, with bundles and everything
127
            if self.__dict__[key] is not None:
128
                stanza.add(key, self.__dict__[key])
1551.12.12 by Aaron Bentley
Add format header
129
        lines = ['# ' + self._format_string + '\n']
130
        lines.extend(rio.to_patch_lines(stanza))
1551.12.2 by Aaron Bentley
Got directives round-tripping, with bundles and everything
131
        lines.append('# \n')
132
        if self.patch is not None:
133
            lines.extend(self.patch.splitlines(True))
134
        return lines
135
1551.12.16 by Aaron Bentley
Enable signing merge directives
136
    def to_signed(self, branch):
1551.12.38 by Aaron Bentley
Add docs for MergeDirective and RIO-patch functions
137
        """Serialize as a signed string.
138
139
        :param branch: The source branch, to get the signing strategy
140
        :return: a string
141
        """
1551.12.16 by Aaron Bentley
Enable signing merge directives
142
        my_gpg = gpg.GPGStrategy(branch.get_config())
143
        return my_gpg.sign(''.join(self.to_lines()))
144
1551.12.26 by Aaron Bentley
Get email working, with optional message
145
    def to_email(self, mail_to, branch, sign=False):
1551.12.38 by Aaron Bentley
Add docs for MergeDirective and RIO-patch functions
146
        """Serialize as an email message.
147
148
        :param mail_to: The address to mail the message to
149
        :param branch: The source branch, to get the signing strategy and
150
            source email address
151
        :param sign: If True, gpg-sign the email
152
        :return: an email message
153
        """
1551.12.26 by Aaron Bentley
Get email working, with optional message
154
        mail_from = branch.get_config().username()
155
        message = Message.Message()
156
        message['To'] = mail_to
157
        message['From'] = mail_from
158
        if self.message is not None:
159
            message['Subject'] = self.message
160
        else:
161
            revision = branch.repository.get_revision(self.revision_id)
162
            message['Subject'] = revision.message
163
        if sign:
164
            body = self.to_signed(branch)
165
        else:
166
            body = ''.join(self.to_lines())
167
        message.set_payload(body)
168
        return message
169
1551.12.2 by Aaron Bentley
Got directives round-tripping, with bundles and everything
170
    @classmethod
1551.12.5 by Aaron Bentley
Get MergeDirective.from_objects working
171
    def from_objects(klass, repository, revision_id, time, timezone,
1551.12.13 by Aaron Bentley
Rename fields
172
                 target_branch, patch_type='bundle',
1551.12.27 by Aaron Bentley
support custom message everywhere
173
                 local_target_branch=None, public_branch=None, message=None):
1551.12.38 by Aaron Bentley
Add docs for MergeDirective and RIO-patch functions
174
        """Generate a merge directive from various objects
175
176
        :param repository: The repository containing the revision
177
        :param revision_id: The revision to merge
178
        :param time: The POSIX timestamp of the date the request was issued.
179
        :param timezone: The timezone of the request
180
        :param target_branch: The url of the branch to merge into
181
        :param patch_type: 'bundle', 'diff' or None, depending on the type of
182
            patch desired.
183
        :param local_target_branch: a local copy of the target branch
184
        :param public_branch: location of a public branch containing the target
185
            revision.
186
        :param message: Message to use when committing the merge
187
        :return: The merge directive
188
189
        The public branch is always used if supplied.  If the patch_type is
190
        not 'bundle', the public branch must be supplied, and will be verified.
191
192
        If the message is not supplied, the message from revision_id will be
193
        used for the commit.
194
        """
1551.12.5 by Aaron Bentley
Get MergeDirective.from_objects working
195
        t = testament.StrictTestament3.from_revision(repository, revision_id)
196
        if patch_type is None:
197
            patch = None
1551.12.2 by Aaron Bentley
Got directives round-tripping, with bundles and everything
198
        else:
1551.12.13 by Aaron Bentley
Rename fields
199
            submit_branch = _mod_branch.Branch.open(target_branch)
1551.12.5 by Aaron Bentley
Get MergeDirective.from_objects working
200
            submit_revision_id = submit_branch.last_revision()
201
            repository.fetch(submit_branch.repository, submit_revision_id)
202
            ancestor_id = _mod_revision.common_ancestor(revision_id,
203
                                                        submit_revision_id,
204
                                                        repository)
1551.12.39 by Aaron Bentley
Re-design patch handling to use a dict
205
            type_handler = {'bundle': klass._generate_bundle,
206
                            'diff': klass._generate_diff,
207
                            None: lambda x, y, z: None }
208
            patch = type_handler[patch_type](repository, revision_id,
209
                                             ancestor_id)
1551.12.5 by Aaron Bentley
Get MergeDirective.from_objects working
210
            if patch_type == 'bundle':
211
                s = StringIO()
212
                bundle_serializer.write_bundle(repository, revision_id,
213
                                               ancestor_id, s)
214
                patch = s.getvalue()
215
            elif patch_type == 'diff':
216
                patch = klass._generate_diff(repository, revision_id,
217
                                             ancestor_id)
1551.12.33 by Aaron Bentley
Take public_branch as a string, not object
218
1551.12.34 by Aaron Bentley
Check public branch only if not using a bundle
219
            if public_branch is not None and patch_type != 'bundle':
1551.12.33 by Aaron Bentley
Take public_branch as a string, not object
220
                public_branch_obj = _mod_branch.Branch.open(public_branch)
221
                if not public_branch_obj.repository.has_revision(revision_id):
222
                    raise errors.PublicBranchOutOfDate(public_branch,
223
                                                       revision_id)
224
1551.12.5 by Aaron Bentley
Get MergeDirective.from_objects working
225
        return MergeDirective(revision_id, t.as_sha1(), time, timezone,
1551.12.33 by Aaron Bentley
Take public_branch as a string, not object
226
                              target_branch, patch, patch_type, public_branch,
1551.12.27 by Aaron Bentley
support custom message everywhere
227
                              message)
1551.12.5 by Aaron Bentley
Get MergeDirective.from_objects working
228
229
    @staticmethod
230
    def _generate_diff(repository, revision_id, ancestor_id):
231
        tree_1 = repository.revision_tree(ancestor_id)
232
        tree_2 = repository.revision_tree(revision_id)
233
        s = StringIO()
1551.12.40 by Aaron Bentley
Do not show prefixes in diffs
234
        diff.show_diff_trees(tree_1, tree_2, s, old_label='', new_label='')
1551.12.5 by Aaron Bentley
Get MergeDirective.from_objects working
235
        return s.getvalue()
1551.12.39 by Aaron Bentley
Re-design patch handling to use a dict
236
237
    @staticmethod
238
    def _generate_bundle(repository, revision_id, ancestor_id):
239
        s = StringIO()
240
        bundle_serializer.write_bundle(repository, revision_id,
241
                                       ancestor_id, s)
242
        return s.getvalue()