/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
3830.4.1 by Jelmer Vernooij
Add base classes for foreign branches.
1
# Copyright (C) 2008 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
3918.2.2 by Martin Pool
Add import statement
16
17
3830.4.1 by Jelmer Vernooij
Add base classes for foreign branches.
18
"""Foreign branch utilities."""
19
3918.2.2 by Martin Pool
Add import statement
20
3830.4.1 by Jelmer Vernooij
Add base classes for foreign branches.
21
from bzrlib.branch import Branch
22
from bzrlib.commands import Command, Option
3918.2.2 by Martin Pool
Add import statement
23
from bzrlib.repository import Repository
3830.4.1 by Jelmer Vernooij
Add base classes for foreign branches.
24
from bzrlib.revision import Revision
25
from bzrlib.lazy_import import lazy_import
26
lazy_import(globals(), """
27
from bzrlib import (
28
    errors,
3878.5.1 by Jelmer Vernooij
Add a ForeignRepository base class.
29
    osutils,
3830.4.1 by Jelmer Vernooij
Add base classes for foreign branches.
30
    registry,
31
    )
32
""")
33
34
class VcsMapping(object):
35
    """Describes the mapping between the semantics of Bazaar and a foreign vcs.
36
37
    """
38
    # Whether this is an experimental mapping that is still open to changes.
39
    experimental = False
40
41
    # Whether this mapping supports exporting and importing all bzr semantics.
42
    roundtripping = False
43
44
    # Prefix used when importing native foreign revisions (not roundtripped) 
45
    # using this mapping.
46
    revid_prefix = None
47
48
    def revision_id_bzr_to_foreign(self, bzr_revid):
49
        """Parse a bzr revision id and convert it to a foreign revid.
50
51
        :param bzr_revid: The bzr revision id (a string).
52
        :return: A foreign revision id, can be any sort of object.
53
        """
54
        raise NotImplementedError(self.revision_id_bzr_to_foreign)
55
56
    def revision_id_foreign_to_bzr(self, foreign_revid):
57
        """Parse a foreign revision id and convert it to a bzr revid.
58
59
        :param foreign_revid: Foreign revision id, can be any sort of object.
60
        :return: A bzr revision id.
61
        """
62
        raise NotImplementedError(self.revision_id_foreign_to_bzr)
63
64
    def show_foreign_revid(self, foreign_revid):
65
        """Prepare a foreign revision id for formatting using bzr log.
66
        
67
        :param foreign_revid: Foreign revision id.
68
        :return: Dictionary mapping string keys to string values.
69
        """
70
        # TODO: This could be on ForeignVcs instead
71
        return { }
72
73
74
class VcsMappingRegistry(registry.Registry):
75
    """Registry for Bazaar<->foreign VCS mappings.
76
    
77
    There should be one instance of this registry for every foreign VCS.
78
    """
79
80
    def register(self, key, factory, help):
81
        """Register a mapping between Bazaar and foreign VCS semantics.
82
83
        The factory must be a callable that takes one parameter: the key.
84
        It must produce an instance of VcsMapping when called.
85
        """
86
        if ":" in key:
87
            raise ValueError("mapping name can not contain colon (:)")
88
        registry.Registry.register(self, key, factory, help)
89
90
    def set_default(self, key):
91
        """Set the 'default' key to be a clone of the supplied key.
92
93
        This method must be called once and only once.
94
        """
95
        self._set_default_key(key)
96
97
    def get_default(self):
98
        """Convenience function for obtaining the default mapping to use."""
99
        return self.get(self._get_default_key())
100
101
    def revision_id_bzr_to_foreign(self, revid):
102
        """Convert a bzr revision id to a foreign revid."""
103
        raise NotImplementedError(self.revision_id_bzr_to_foreign)
104
105
106
class ForeignRevision(Revision):
107
    """A Revision from a Foreign repository. Remembers 
108
    information about foreign revision id and mapping.
109
110
    """
111
112
    def __init__(self, foreign_revid, mapping, *args, **kwargs):
3830.4.4 by Jelmer Vernooij
make inventory_sha1 default to an empty string.
113
        if not "inventory_sha1" in kwargs:
114
            kwargs["inventory_sha1"] = ""
3830.4.1 by Jelmer Vernooij
Add base classes for foreign branches.
115
        super(ForeignRevision, self).__init__(*args, **kwargs)
116
        self.foreign_revid = foreign_revid
117
        self.mapping = mapping
118
119
120
def show_foreign_properties(rev):
121
    """Custom log displayer for foreign revision identifiers.
122
123
    :param rev: Revision object.
124
    """
125
    # Revision comes directly from a foreign repository
126
    if isinstance(rev, ForeignRevision):
127
        return rev.mapping.show_foreign_revid(rev.foreign_revid)
128
129
    # Revision was once imported from a foreign repository
130
    try:
131
        foreign_revid, mapping = \
132
            foreign_vcs_registry.parse_revision_id(rev.revision_id)
133
    except errors.InvalidRevisionId:
134
        return {}
135
136
    return mapping.show_foreign_revid(foreign_revid)
137
138
139
class ForeignVcs(object):
140
    """A foreign version control system."""
141
142
    def __init__(self, mapping_registry):
143
        self.mapping_registry = mapping_registry
144
145
146
class ForeignVcsRegistry(registry.Registry):
147
    """Registry for Foreign VCSes.
148
149
    There should be one entry per foreign VCS. Example entries would be 
150
    "git", "svn", "hg", "darcs", etc.
151
    
152
    """
153
154
    def register(self, key, foreign_vcs, help):
155
        """Register a foreign VCS.
156
157
        :param key: Prefix of the foreign VCS in revision ids
158
        :param foreign_vcs: ForeignVCS instance
159
        :param help: Description of the foreign VCS
160
        """
161
        if ":" in key or "-" in key:
162
            raise ValueError("vcs name can not contain : or -")
163
        registry.Registry.register(self, key, foreign_vcs, help)
164
165
    def parse_revision_id(self, revid):
166
        """Parse a bzr revision and return the matching mapping and foreign 
167
        revid.
168
        
169
        :param revid: The bzr revision id
170
        :return: tuple with foreign revid and vcs mapping
171
        """
172
        if not "-" in revid:
173
            raise errors.InvalidRevisionId(revid, None)
174
        try:
175
            foreign_vcs = self.get(revid.split("-")[0])
176
        except KeyError:
177
            raise errors.InvalidRevisionId(revid, None)
178
        return foreign_vcs.mapping_registry.revision_id_bzr_to_foreign(revid)
179
180
181
foreign_vcs_registry = ForeignVcsRegistry()
3878.5.1 by Jelmer Vernooij
Add a ForeignRepository base class.
182
183
184
class ForeignRepository(Repository):
185
    """A Repository that exists in a foreign version control system.
186
187
    The data in this repository can not be represented natively using 
188
    Bazaars internal datastructures, but have to converted using a VcsMapping.
189
    """
190
191
    # This repository's native version control system
192
    vcs = None
193
194
    def has_foreign_revision(self, foreign_revid):
195
        """Check whether the specified foreign revision is present.
196
197
        :param foreign_revid: A foreign revision id, in the format used 
198
                              by this Repository's VCS.
199
        """
200
        raise NotImplementedError(self.has_foreign_revision)
201
202
    def lookup_bzr_revision_id(self, revid):
203
        """Lookup a mapped or roundtripped revision by revision id.
204
205
        :param revid: Bazaar revision id
206
        :return: Tuple with foreign revision id and mapping.
207
        """
208
        raise NotImplementedError(self.lookup_revision_id)
209
210
    def all_revision_ids(self, mapping=None):
211
        """See Repository.all_revision_ids()."""
212
        raise NotImplementedError(self.all_revision_ids)
213
214
    def get_default_mapping(self):
215
        """Get the default mapping for this repository."""
216
        raise NotImplementedError(self.get_default_mapping)
217
218
    def get_inventory_xml(self, revision_id):
219
        """See Repository.get_inventory_xml()."""
220
        return self.serialise_inventory(self.get_inventory(revision_id))
221
222
    def get_inventory_sha1(self, revision_id):
223
        """Get the sha1 for the XML representation of an inventory.
224
225
        :param revision_id: Revision id of the inventory for which to return 
226
         the SHA1.
227
        :return: XML string
228
        """
229
230
        return osutils.sha_string(self.get_inventory_xml(revision_id))
231
232
    def get_revision_xml(self, revision_id):
233
        """Return the XML representation of a revision.
234
235
        :param revision_id: Revision for which to return the XML.
236
        :return: XML string
237
        """
238
        return self._serializer.write_revision_to_string(
239
            self.get_revision(revision_id))
240
241
3920.2.1 by Jelmer Vernooij
Add ForeignBranch class.
242
class ForeignBranch(Branch):
243
    """Branch that exists in a foreign version control system."""
244
245
    def __init__(self, mapping):
246
        self.mapping = mapping
247
        super(ForeignBranch, self).__init__()
248
249
    def dpull(self, source, stop_revision=None):
250
        """Pull deltas from another branch.
251
252
        :note: This does not, like pull, retain the revision ids from 
253
            the source branch and will, rather than adding bzr-specific 
254
            metadata, push only those semantics of the revision that can be 
255
            natively represented by this branch' VCS.
256
257
        :param source: Source branch
258
        :param stop_revision: Revision to pull, defaults to last revision.
259
        """
260
        raise NotImplementedError(self.dpull)
3920.2.2 by Jelmer Vernooij
Import dpush command.
261
262
3920.2.3 by Jelmer Vernooij
Make determine_fileid_renames() return a dictionary.
263
def determine_fileid_renames(old_inv, new_inv):
264
    """Determine the file ids based on a old and a new inventory that 
265
    are equal in content.
266
267
    :param old_inv: Old inventory
268
    :param new_inv: New inventory
269
    :return: Dictionary a (old_id, new_id) tuple for each path in the 
270
        inventories.
271
    """
272
    ret = {}
273
    if len(old_inv) != len(new_inv):
274
        raise AssertionError("Inventories are not of the same size")
275
    for old_file_id in old_inv:
276
        new_file_id = new_inv.path2id(old_inv.id2path(old_file_id))
277
        if new_file_id is None:
278
            raise AssertionError(
279
                "Unable to find %s in new inventory" % old_file_id)
280
        if new_file_id != old_file_id:
281
            ret[new_inv.id2path(new_file_id)] = (old_file_id, new_file_id)
282
    return ret
283
284
285
def update_workinginv_fileids(wt, old_inv, new_inv):
3920.2.2 by Jelmer Vernooij
Import dpush command.
286
    """Update all file ids in wt according to old_tree/new_tree. 
287
288
    old_tree and new_tree should be two RevisionTree's that differ only
289
    in file ids.
290
    """
3920.2.3 by Jelmer Vernooij
Make determine_fileid_renames() return a dictionary.
291
    fileid_renames = determine_fileid_renames(old_tree.inventory, new_tree.inventory)
3920.2.2 by Jelmer Vernooij
Import dpush command.
292
    old_fileids = []
293
    new_fileids = []
294
    new_root_id = None
295
    # Adjust file ids in working tree
3920.2.3 by Jelmer Vernooij
Make determine_fileid_renames() return a dictionary.
296
    # Sorted, so we process parents before children
3920.2.2 by Jelmer Vernooij
Import dpush command.
297
    for path in sorted(fileid_renames.keys(), reverse=True):
298
        if path != "":
299
            old_fileids.append(fileid_renames[path][0])
300
            new_fileids.append((path, fileid_renames[path][1]))
301
        else:
302
            new_root_id = fileid_renames[path][1]
303
    new_fileids.reverse()
304
    wt.unversion(old_fileids)
305
    if new_root_id is not None:
306
        wt.set_root_id(new_root_id)
307
    wt.add([x[0] for x in new_fileids], [x[1] for x in new_fileids])
308
    wt.set_last_revision(new_tree.get_revision_id())
309
310
311
class cmd_dpush(Command):
312
    """Push diffs into a foreign version control system without any 
313
    Bazaar-specific metadata.
314
315
    This will afterwards rebase the local Bazaar branch on the remote
316
    branch unless the --no-rebase option is used, in which case 
317
    the two branches will be out of sync. 
318
    """
319
    takes_args = ['location?']
320
    takes_options = ['remember', Option('directory',
321
            help='Branch to push from, '
322
                 'rather than the one containing the working directory.',
323
            short_name='d',
324
            type=unicode,
325
            ),
326
            Option('no-rebase', help="Don't rebase after push")]
327
328
    def run(self, location=None, remember=False, directory=None, 
329
            no_rebase=False):
330
        from bzrlib import urlutils
331
        from bzrlib.bzrdir import BzrDir
332
        from bzrlib.errors import BzrCommandError, NoWorkingTree
333
        from bzrlib.trace import info
334
        from bzrlib.workingtree import WorkingTree
335
336
        if directory is None:
337
            directory = "."
338
        try:
339
            source_wt = WorkingTree.open_containing(directory)[0]
340
            source_branch = source_wt.branch
341
        except NoWorkingTree:
342
            source_branch = Branch.open_containing(directory)[0]
343
            source_wt = None
344
        stored_loc = source_branch.get_push_location()
345
        if location is None:
346
            if stored_loc is None:
347
                raise BzrCommandError("No push location known or specified.")
348
            else:
349
                display_url = urlutils.unescape_for_display(stored_loc,
350
                        self.outf.encoding)
351
                self.outf.write("Using saved location: %s\n" % display_url)
352
                location = stored_loc
353
354
        bzrdir = BzrDir.open(location)
355
        target_branch = bzrdir.open_branch()
356
        target_branch.lock_write()
357
        try:
358
            if not isinstance(target_branch, ForeignBranch):
359
                info("target branch is not a foreign branch, using regular push.")
360
                target_branch.pull(source_branch)
361
                no_rebase = True
362
            else:
363
                revid_map = target_branch.dpull(source_branch)
364
            # We successfully created the target, remember it
365
            if source_branch.get_push_location() is None or remember:
366
                source_branch.set_push_location(target_branch.base)
367
            if not no_rebase:
368
                _, old_last_revid = source_branch.last_revision_info()
369
                new_last_revid = revid_map[old_last_revid]
370
                if source_wt is not None:
371
                    source_wt.pull(target_branch, overwrite=True, 
372
                                   stop_revision=new_last_revid)
373
                    source_wt.lock_write()
374
                    try:
375
                        update_workingtree_fileids(source_wt, 
376
                            source_wt.branch.repository.revision_tree(old_last_revid),
377
                            source_wt.branch.repository.revision_tree(new_last_revid))
378
                    finally:
379
                        source_wt.unlock()
380
                else:
381
                    source_branch.pull(target_branch, overwrite=True, 
382
                                       stop_revision=new_last_revid)
383
        finally:
384
            target_branch.unlock()
385
386