~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/foreign.py

(vila) Make all transport put_bytes() raises TypeError when given unicode
 strings rather than bytes (Vincent Ladeuil)

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2008-2012 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
"""Foreign branch utilities."""
 
18
 
 
19
from __future__ import absolute_import
 
20
 
 
21
 
 
22
from bzrlib.branch import (
 
23
    Branch,
 
24
    )
 
25
from bzrlib.commands import Command, Option
 
26
from bzrlib.repository import Repository
 
27
from bzrlib.revision import Revision
 
28
from bzrlib.lazy_import import lazy_import
 
29
lazy_import(globals(), """
 
30
from bzrlib import (
 
31
    errors,
 
32
    registry,
 
33
    transform,
 
34
    )
 
35
from bzrlib.i18n import gettext
 
36
""")
 
37
 
 
38
class VcsMapping(object):
 
39
    """Describes the mapping between the semantics of Bazaar and a foreign VCS.
 
40
 
 
41
    """
 
42
    # Whether this is an experimental mapping that is still open to changes.
 
43
    experimental = False
 
44
 
 
45
    # Whether this mapping supports exporting and importing all bzr semantics.
 
46
    roundtripping = False
 
47
 
 
48
    # Prefix used when importing revisions native to the foreign VCS (as
 
49
    # opposed to roundtripping bzr-native revisions) using this mapping.
 
50
    revid_prefix = None
 
51
 
 
52
    def __init__(self, vcs):
 
53
        """Create a new VcsMapping.
 
54
 
 
55
        :param vcs: VCS that this mapping maps to Bazaar
 
56
        """
 
57
        self.vcs = vcs
 
58
 
 
59
    def revision_id_bzr_to_foreign(self, bzr_revid):
 
60
        """Parse a bzr revision id and convert it to a foreign revid.
 
61
 
 
62
        :param bzr_revid: The bzr revision id (a string).
 
63
        :return: A foreign revision id, can be any sort of object.
 
64
        """
 
65
        raise NotImplementedError(self.revision_id_bzr_to_foreign)
 
66
 
 
67
    def revision_id_foreign_to_bzr(self, foreign_revid):
 
68
        """Parse a foreign revision id and convert it to a bzr revid.
 
69
 
 
70
        :param foreign_revid: Foreign revision id, can be any sort of object.
 
71
        :return: A bzr revision id.
 
72
        """
 
73
        raise NotImplementedError(self.revision_id_foreign_to_bzr)
 
74
 
 
75
 
 
76
class VcsMappingRegistry(registry.Registry):
 
77
    """Registry for Bazaar<->foreign VCS mappings.
 
78
 
 
79
    There should be one instance of this registry for every foreign VCS.
 
80
    """
 
81
 
 
82
    def register(self, key, factory, help):
 
83
        """Register a mapping between Bazaar and foreign VCS semantics.
 
84
 
 
85
        The factory must be a callable that takes one parameter: the key.
 
86
        It must produce an instance of VcsMapping when called.
 
87
        """
 
88
        if ":" in key:
 
89
            raise ValueError("mapping name can not contain colon (:)")
 
90
        registry.Registry.register(self, key, factory, help)
 
91
 
 
92
    def set_default(self, key):
 
93
        """Set the 'default' key to be a clone of the supplied key.
 
94
 
 
95
        This method must be called once and only once.
 
96
        """
 
97
        self._set_default_key(key)
 
98
 
 
99
    def get_default(self):
 
100
        """Convenience function for obtaining the default mapping to use."""
 
101
        return self.get(self._get_default_key())
 
102
 
 
103
    def revision_id_bzr_to_foreign(self, revid):
 
104
        """Convert a bzr revision id to a foreign revid."""
 
105
        raise NotImplementedError(self.revision_id_bzr_to_foreign)
 
106
 
 
107
 
 
108
class ForeignRevision(Revision):
 
109
    """A Revision from a Foreign repository. Remembers
 
110
    information about foreign revision id and mapping.
 
111
 
 
112
    """
 
113
 
 
114
    def __init__(self, foreign_revid, mapping, *args, **kwargs):
 
115
        if not "inventory_sha1" in kwargs:
 
116
            kwargs["inventory_sha1"] = ""
 
117
        super(ForeignRevision, self).__init__(*args, **kwargs)
 
118
        self.foreign_revid = foreign_revid
 
119
        self.mapping = mapping
 
120
 
 
121
 
 
122
class ForeignVcs(object):
 
123
    """A foreign version control system."""
 
124
 
 
125
    branch_format = None
 
126
 
 
127
    repository_format = None
 
128
 
 
129
    def __init__(self, mapping_registry, abbreviation=None):
 
130
        """Create a new foreign vcs instance.
 
131
 
 
132
        :param mapping_registry: Registry with mappings for this VCS.
 
133
        :param abbreviation: Optional abbreviation ('bzr', 'svn', 'git', etc)
 
134
        """
 
135
        self.abbreviation = abbreviation
 
136
        self.mapping_registry = mapping_registry
 
137
 
 
138
    def show_foreign_revid(self, foreign_revid):
 
139
        """Prepare a foreign revision id for formatting using bzr log.
 
140
 
 
141
        :param foreign_revid: Foreign revision id.
 
142
        :return: Dictionary mapping string keys to string values.
 
143
        """
 
144
        return { }
 
145
 
 
146
    def serialize_foreign_revid(self, foreign_revid):
 
147
        """Serialize a foreign revision id for this VCS.
 
148
 
 
149
        :param foreign_revid: Foreign revision id
 
150
        :return: Bytestring with serialized revid, will not contain any 
 
151
            newlines.
 
152
        """
 
153
        raise NotImplementedError(self.serialize_foreign_revid)
 
154
 
 
155
 
 
156
class ForeignVcsRegistry(registry.Registry):
 
157
    """Registry for Foreign VCSes.
 
158
 
 
159
    There should be one entry per foreign VCS. Example entries would be
 
160
    "git", "svn", "hg", "darcs", etc.
 
161
 
 
162
    """
 
163
 
 
164
    def register(self, key, foreign_vcs, help):
 
165
        """Register a foreign VCS.
 
166
 
 
167
        :param key: Prefix of the foreign VCS in revision ids
 
168
        :param foreign_vcs: ForeignVCS instance
 
169
        :param help: Description of the foreign VCS
 
170
        """
 
171
        if ":" in key or "-" in key:
 
172
            raise ValueError("vcs name can not contain : or -")
 
173
        registry.Registry.register(self, key, foreign_vcs, help)
 
174
 
 
175
    def parse_revision_id(self, revid):
 
176
        """Parse a bzr revision and return the matching mapping and foreign
 
177
        revid.
 
178
 
 
179
        :param revid: The bzr revision id
 
180
        :return: tuple with foreign revid and vcs mapping
 
181
        """
 
182
        if not ":" in revid or not "-" in revid:
 
183
            raise errors.InvalidRevisionId(revid, None)
 
184
        try:
 
185
            foreign_vcs = self.get(revid.split("-")[0])
 
186
        except KeyError:
 
187
            raise errors.InvalidRevisionId(revid, None)
 
188
        return foreign_vcs.mapping_registry.revision_id_bzr_to_foreign(revid)
 
189
 
 
190
 
 
191
foreign_vcs_registry = ForeignVcsRegistry()
 
192
 
 
193
 
 
194
class ForeignRepository(Repository):
 
195
    """A Repository that exists in a foreign version control system.
 
196
 
 
197
    The data in this repository can not be represented natively using
 
198
    Bazaars internal datastructures, but have to converted using a VcsMapping.
 
199
    """
 
200
 
 
201
    # This repository's native version control system
 
202
    vcs = None
 
203
 
 
204
    def has_foreign_revision(self, foreign_revid):
 
205
        """Check whether the specified foreign revision is present.
 
206
 
 
207
        :param foreign_revid: A foreign revision id, in the format used
 
208
                              by this Repository's VCS.
 
209
        """
 
210
        raise NotImplementedError(self.has_foreign_revision)
 
211
 
 
212
    def lookup_bzr_revision_id(self, revid):
 
213
        """Lookup a mapped or roundtripped revision by revision id.
 
214
 
 
215
        :param revid: Bazaar revision id
 
216
        :return: Tuple with foreign revision id and mapping.
 
217
        """
 
218
        raise NotImplementedError(self.lookup_revision_id)
 
219
 
 
220
    def all_revision_ids(self, mapping=None):
 
221
        """See Repository.all_revision_ids()."""
 
222
        raise NotImplementedError(self.all_revision_ids)
 
223
 
 
224
    def get_default_mapping(self):
 
225
        """Get the default mapping for this repository."""
 
226
        raise NotImplementedError(self.get_default_mapping)
 
227
 
 
228
 
 
229
class ForeignBranch(Branch):
 
230
    """Branch that exists in a foreign version control system."""
 
231
 
 
232
    def __init__(self, mapping):
 
233
        self.mapping = mapping
 
234
        super(ForeignBranch, self).__init__()
 
235
 
 
236
 
 
237
def update_workingtree_fileids(wt, target_tree):
 
238
    """Update the file ids in a working tree based on another tree.
 
239
 
 
240
    :param wt: Working tree in which to update file ids
 
241
    :param target_tree: Tree to retrieve new file ids from, based on path
 
242
    """
 
243
    tt = transform.TreeTransform(wt)
 
244
    try:
 
245
        for f, p, c, v, d, n, k, e in target_tree.iter_changes(wt):
 
246
            if v == (True, False):
 
247
                trans_id = tt.trans_id_tree_path(p[0])
 
248
                tt.unversion_file(trans_id)
 
249
            elif v == (False, True):
 
250
                trans_id = tt.trans_id_tree_path(p[1])
 
251
                tt.version_file(f, trans_id)
 
252
        tt.apply()
 
253
    finally:
 
254
        tt.finalize()
 
255
    if len(wt.get_parent_ids()) == 1:
 
256
        wt.set_parent_trees([(target_tree.get_revision_id(), target_tree)])
 
257
    else:
 
258
        wt.set_last_revision(target_tree.get_revision_id())
 
259
 
 
260
 
 
261
class cmd_dpush(Command):
 
262
    __doc__ = """Push into a different VCS without any custom bzr metadata.
 
263
 
 
264
    This will afterwards rebase the local branch on the remote
 
265
    branch unless the --no-rebase option is used, in which case 
 
266
    the two branches will be out of sync after the push. 
 
267
    """
 
268
    takes_args = ['location?']
 
269
    takes_options = [
 
270
        'remember',
 
271
        Option('directory',
 
272
               help='Branch to push from, '
 
273
               'rather than the one containing the working directory.',
 
274
               short_name='d',
 
275
               type=unicode,
 
276
               ),
 
277
        Option('no-rebase', help="Do not rebase after push."),
 
278
        Option('strict',
 
279
               help='Refuse to push if there are uncommitted changes in'
 
280
               ' the working tree, --no-strict disables the check.'),
 
281
        ]
 
282
 
 
283
    def run(self, location=None, remember=False, directory=None,
 
284
            no_rebase=False, strict=None):
 
285
        from bzrlib import urlutils
 
286
        from bzrlib.controldir import ControlDir
 
287
        from bzrlib.errors import BzrCommandError, NoWorkingTree
 
288
        from bzrlib.workingtree import WorkingTree
 
289
 
 
290
        if directory is None:
 
291
            directory = "."
 
292
        try:
 
293
            source_wt = WorkingTree.open_containing(directory)[0]
 
294
            source_branch = source_wt.branch
 
295
        except NoWorkingTree:
 
296
            source_branch = Branch.open(directory)
 
297
            source_wt = None
 
298
        if source_wt is not None:
 
299
            source_wt.check_changed_or_out_of_date(
 
300
                strict, 'dpush_strict',
 
301
                more_error='Use --no-strict to force the push.',
 
302
                more_warning='Uncommitted changes will not be pushed.')
 
303
        stored_loc = source_branch.get_push_location()
 
304
        if location is None:
 
305
            if stored_loc is None:
 
306
                raise BzrCommandError(gettext("No push location known or specified."))
 
307
            else:
 
308
                display_url = urlutils.unescape_for_display(stored_loc,
 
309
                        self.outf.encoding)
 
310
                self.outf.write(
 
311
                       gettext("Using saved location: %s\n") % display_url)
 
312
                location = stored_loc
 
313
 
 
314
        controldir = ControlDir.open(location)
 
315
        target_branch = controldir.open_branch()
 
316
        target_branch.lock_write()
 
317
        try:
 
318
            try:
 
319
                push_result = source_branch.push(target_branch, lossy=True)
 
320
            except errors.LossyPushToSameVCS:
 
321
                raise BzrCommandError(gettext("{0!r} and {1!r} are in the same VCS, lossy "
 
322
                    "push not necessary. Please use regular push.").format(
 
323
                    source_branch, target_branch))
 
324
            # We successfully created the target, remember it
 
325
            if source_branch.get_push_location() is None or remember:
 
326
                # FIXME: Should be done only if we succeed ? -- vila 2012-01-18
 
327
                source_branch.set_push_location(target_branch.base)
 
328
            if not no_rebase:
 
329
                old_last_revid = source_branch.last_revision()
 
330
                source_branch.pull(target_branch, overwrite=True)
 
331
                new_last_revid = source_branch.last_revision()
 
332
                if source_wt is not None and old_last_revid != new_last_revid:
 
333
                    source_wt.lock_write()
 
334
                    try:
 
335
                        target = source_wt.branch.repository.revision_tree(
 
336
                            new_last_revid)
 
337
                        update_workingtree_fileids(source_wt, target)
 
338
                    finally:
 
339
                        source_wt.unlock()
 
340
            push_result.report(self.outf)
 
341
        finally:
 
342
            target_branch.unlock()