/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 fetch.py

Use BazaarObjectStore to find matching SHA1s for bzr revisions.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2008 Jelmer Vernooij <jelmer@samba.org>
 
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
from cStringIO import (
 
18
    StringIO,
 
19
    )
 
20
import dulwich as git
 
21
from dulwich.client import (
 
22
    SimpleFetchGraphWalker,
 
23
    )
 
24
from dulwich.objects import (
 
25
    Commit,
 
26
    Tag,
 
27
    )
 
28
from dulwich.object_store import (
 
29
    tree_lookup_path,
 
30
    )
 
31
import stat
 
32
 
 
33
from bzrlib import (
 
34
    debug,
 
35
    osutils,
 
36
    trace,
 
37
    ui,
 
38
    urlutils,
 
39
    )
 
40
from bzrlib.errors import (
 
41
    InvalidRevisionId,
 
42
    NoSuchId,
 
43
    NoSuchRevision,
 
44
    )
 
45
from bzrlib.inventory import (
 
46
    Inventory,
 
47
    InventoryDirectory,
 
48
    InventoryFile,
 
49
    InventoryLink,
 
50
    )
 
51
from bzrlib.lru_cache import (
 
52
    LRUCache,
 
53
    )
 
54
from bzrlib.repository import (
 
55
    InterRepository,
 
56
    )
 
57
from bzrlib.revision import (
 
58
    NULL_REVISION,
 
59
    )
 
60
from bzrlib.tsort import (
 
61
    topo_sort,
 
62
    )
 
63
from bzrlib.versionedfile import (
 
64
    FulltextContentFactory,
 
65
    )
 
66
 
 
67
from bzrlib.plugins.git.converter import (
 
68
    BazaarObjectStore,
 
69
    )
 
70
from bzrlib.plugins.git.mapping import (
 
71
    DEFAULT_FILE_MODE,
 
72
    inventory_to_tree_and_blobs,
 
73
    text_to_blob,
 
74
    )
 
75
from bzrlib.plugins.git.remote import (
 
76
    RemoteGitRepository,
 
77
    )
 
78
from bzrlib.plugins.git.repository import (
 
79
    GitRepository, 
 
80
    GitRepositoryFormat,
 
81
    LocalGitRepository,
 
82
    )
 
83
 
 
84
 
 
85
class BzrFetchGraphWalker(object):
 
86
    """GraphWalker implementation that uses a Bazaar repository."""
 
87
 
 
88
    def __init__(self, repository, mapping):
 
89
        self.repository = repository
 
90
        self.mapping = mapping
 
91
        self.done = set()
 
92
        self.heads = set(repository.all_revision_ids())
 
93
        self.parents = {}
 
94
 
 
95
    def __iter__(self):
 
96
        return iter(self.next, None)
 
97
 
 
98
    def ack(self, sha):
 
99
        revid = self.mapping.revision_id_foreign_to_bzr(sha)
 
100
        self.remove(revid)
 
101
 
 
102
    def remove(self, revid):
 
103
        self.done.add(revid)
 
104
        if revid in self.heads:
 
105
            self.heads.remove(revid)
 
106
        if revid in self.parents:
 
107
            for p in self.parents[revid]:
 
108
                self.remove(p)
 
109
 
 
110
    def next(self):
 
111
        while self.heads:
 
112
            ret = self.heads.pop()
 
113
            ps = self.repository.get_parent_map([ret])[ret]
 
114
            self.parents[ret] = ps
 
115
            self.heads.update([p for p in ps if not p in self.done])
 
116
            try:
 
117
                self.done.add(ret)
 
118
                return self.mapping.revision_id_bzr_to_foreign(ret)[0]
 
119
            except InvalidRevisionId:
 
120
                pass
 
121
        return None
 
122
 
 
123
 
 
124
def import_git_blob(texts, mapping, path, hexsha, base_inv, parent_id, 
 
125
    revision_id, parent_invs, shagitmap, lookup_object, executable, symlink):
 
126
    """Import a git blob object into a bzr repository.
 
127
 
 
128
    :param texts: VersionedFiles to add to
 
129
    :param path: Path in the tree
 
130
    :param blob: A git blob
 
131
    :return: Inventory delta for this file
 
132
    """
 
133
    file_id = mapping.generate_file_id(path)
 
134
    if symlink:
 
135
        cls = InventoryLink
 
136
    else:
 
137
        cls = InventoryFile
 
138
    # We just have to hope this is indeed utf-8:
 
139
    ie = cls(file_id, urlutils.basename(path).decode("utf-8"), parent_id)
 
140
    ie.executable = executable
 
141
    ie.text_id = hexsha
 
142
    # See if this has changed at all
 
143
    try:
 
144
        base_ie = base_inv[file_id]
 
145
    except NoSuchId:
 
146
        base_ie = None
 
147
        base_sha = None
 
148
    else:
 
149
        base_sha = base_ie.text_id
 
150
        try:
 
151
            if base_sha is None:
 
152
                base_sha = shagitmap.lookup_blob(file_id, base_ie.revision)
 
153
        except KeyError:
 
154
            base_sha = None
 
155
        else:
 
156
            if (base_sha == hexsha and base_ie.executable == ie.executable
 
157
                and base_ie.kind == ie.kind):
 
158
                # If nothing has changed since the base revision, we're done
 
159
                return [], []
 
160
    if base_sha == hexsha:
 
161
        ie.text_size = base_ie.text_size
 
162
        ie.text_sha1 = base_ie.text_sha1
 
163
        ie.symlink_target = base_ie.symlink_target
 
164
        ie.revision = base_ie.revision
 
165
    else:
 
166
        blob = lookup_object(hexsha)
 
167
        if ie.kind == "symlink":
 
168
            ie.symlink_target = blob.data
 
169
            ie.text_size = None
 
170
            ie.text_sha1 = None
 
171
        else:
 
172
            ie.text_size = len(blob.data)
 
173
            ie.text_sha1 = osutils.sha_string(blob.data)
 
174
    # Check what revision we should store
 
175
    parent_keys = []
 
176
    for pinv in parent_invs:
 
177
        if pinv.revision_id == base_inv.revision_id:
 
178
            pie = base_ie
 
179
            if pie is None:
 
180
                continue
 
181
        else:
 
182
            try:
 
183
                pie = pinv[file_id]
 
184
            except NoSuchId:
 
185
                continue
 
186
        if pie.text_sha1 == ie.text_sha1:
 
187
            # found a revision in one of the parents to use
 
188
            ie.revision = pie.revision
 
189
            break
 
190
        parent_keys.append((file_id, pie.revision))
 
191
    if ie.revision is None:
 
192
        # Need to store a new revision
 
193
        ie.revision = revision_id
 
194
        assert file_id is not None
 
195
        assert ie.revision is not None
 
196
        texts.insert_record_stream([FulltextContentFactory((file_id, ie.revision), tuple(parent_keys), ie.text_sha1, blob.data)])
 
197
        shamap = [(hexsha, "blob", (ie.file_id, ie.revision))]
 
198
    else:
 
199
        shamap = []
 
200
    if file_id in base_inv:
 
201
        old_path = base_inv.id2path(file_id)
 
202
    else:
 
203
        old_path = None
 
204
    return ([(old_path, path, file_id, ie)], shamap)
 
205
 
 
206
 
 
207
def import_git_tree(texts, mapping, path, hexsha, base_inv, parent_id, 
 
208
    revision_id, parent_invs, shagitmap, lookup_object):
 
209
    """Import a git tree object into a bzr repository.
 
210
 
 
211
    :param texts: VersionedFiles object to add to
 
212
    :param path: Path in the tree
 
213
    :param tree: A git tree object
 
214
    :param base_inv: Base inventory against which to return inventory delta
 
215
    :return: Inventory delta for this subtree
 
216
    """
 
217
    invdelta = []
 
218
    file_id = mapping.generate_file_id(path)
 
219
    # We just have to hope this is indeed utf-8:
 
220
    ie = InventoryDirectory(file_id, urlutils.basename(path.decode("utf-8")), 
 
221
        parent_id)
 
222
    ie.text_id = hexsha
 
223
    try:
 
224
        base_ie = base_inv[file_id]
 
225
    except NoSuchId:
 
226
        # Newly appeared here
 
227
        base_ie = None
 
228
        ie.revision = revision_id
 
229
        texts.add_lines((file_id, ie.revision), (), [])
 
230
        invdelta.append((None, path, file_id, ie))
 
231
    else:
 
232
        base_sha = base_ie.text_id
 
233
        # See if this has changed at all
 
234
        try:
 
235
            if base_sha is None:
 
236
                base_sha = shagitmap.lookup_tree(file_id, base_inv.revision_id)
 
237
        except KeyError:
 
238
            pass
 
239
        else:
 
240
            if base_sha == hexsha:
 
241
                # If nothing has changed since the base revision, we're done
 
242
                return [], {}, []
 
243
    # Remember for next time
 
244
    existing_children = set()
 
245
    child_modes = {}
 
246
    shamap = []
 
247
    tree = lookup_object(hexsha)
 
248
    for mode, name, child_hexsha in tree.entries():
 
249
        basename = name.decode("utf-8")
 
250
        existing_children.add(basename)
 
251
        child_path = osutils.pathjoin(path, name)
 
252
        if stat.S_ISDIR(mode):
 
253
            subinvdelta, grandchildmodes, subshamap = import_git_tree(texts, 
 
254
                    mapping, child_path, child_hexsha, base_inv, file_id, 
 
255
                    revision_id, parent_invs, shagitmap, lookup_object)
 
256
            invdelta.extend(subinvdelta)
 
257
            child_modes.update(grandchildmodes)
 
258
            shamap.extend(subshamap)
 
259
        else:
 
260
            fs_mode = stat.S_IMODE(mode)
 
261
            symlink = stat.S_ISLNK(mode)
 
262
            subinvdelta, subshamap = import_git_blob(texts, mapping, 
 
263
                    child_path, child_hexsha, base_inv, file_id, revision_id, 
 
264
                    parent_invs, shagitmap, lookup_object, 
 
265
                    bool(fs_mode & 0111), symlink)
 
266
            invdelta.extend(subinvdelta)
 
267
            shamap.extend(subshamap)
 
268
        if mode not in (stat.S_IFDIR, DEFAULT_FILE_MODE,
 
269
                        stat.S_IFLNK, DEFAULT_FILE_MODE|0111):
 
270
            child_modes[child_path] = mode
 
271
    # Remove any children that have disappeared
 
272
    if base_ie is not None:
 
273
        deletable = [v for k,v in base_ie.children.iteritems() if k not in existing_children]
 
274
        while deletable:
 
275
            ie = deletable.pop()
 
276
            invdelta.append((base_inv.id2path(ie.file_id), None, ie.file_id, None))
 
277
            if ie.kind == "directory":
 
278
                deletable.extend(ie.children.values())
 
279
    shamap.append((hexsha, "tree", (file_id, revision_id)))
 
280
    return invdelta, child_modes, shamap
 
281
 
 
282
 
 
283
def import_git_objects(repo, mapping, object_iter, target_git_object_retriever, 
 
284
        heads, pb=None):
 
285
    """Import a set of git objects into a bzr repository.
 
286
 
 
287
    :param repo: Bazaar repository
 
288
    :param mapping: Mapping to use
 
289
    :param object_iter: Iterator over Git objects.
 
290
    """
 
291
    # TODO: a more (memory-)efficient implementation of this
 
292
    graph = []
 
293
    root_trees = {}
 
294
    revisions = {}
 
295
    checked = set()
 
296
    heads = list(heads)
 
297
    parent_invs_cache = LRUCache(50)
 
298
    # Find and convert commit objects
 
299
    while heads:
 
300
        if pb is not None:
 
301
            pb.update("finding revisions to fetch", len(graph), None)
 
302
        head = heads.pop()
 
303
        assert isinstance(head, str)
 
304
        try:
 
305
            o = object_iter[head]
 
306
        except KeyError:
 
307
            continue
 
308
        if isinstance(o, Commit):
 
309
            rev = mapping.import_commit(o)
 
310
            if repo.has_revision(rev.revision_id):
 
311
                continue
 
312
            root_trees[rev.revision_id] = o.tree
 
313
            revisions[rev.revision_id] = rev
 
314
            graph.append((rev.revision_id, rev.parent_ids))
 
315
            target_git_object_retriever._idmap.add_entry(o.id, "commit", 
 
316
                    (rev.revision_id, o.tree))
 
317
            heads.extend([p for p in o.parents if p not in checked])
 
318
        elif isinstance(o, Tag):
 
319
            heads.append(o.object[1])
 
320
        else:
 
321
            trace.warning("Unable to import head object %r" % o)
 
322
        checked.add(head)
 
323
    # Order the revisions
 
324
    # Create the inventory objects
 
325
    for i, revid in enumerate(topo_sort(graph)):
 
326
        if pb is not None:
 
327
            pb.update("fetching revisions", i, len(graph))
 
328
        rev = revisions[revid]
 
329
        # We have to do this here, since we have to walk the tree and 
 
330
        # we need to make sure to import the blobs / trees with the right 
 
331
        # path; this may involve adding them more than once.
 
332
        def lookup_object(sha):
 
333
            try:
 
334
                return object_iter[sha]
 
335
            except KeyError:
 
336
                return target_git_object_retriever[sha]
 
337
        parent_invs = []
 
338
        for parent_id in rev.parent_ids:
 
339
            try:
 
340
                parent_invs.append(parent_invs_cache[parent_id])
 
341
            except KeyError:
 
342
                parent_inv = repo.get_inventory(parent_id)
 
343
                parent_invs.append(parent_inv)
 
344
                parent_invs_cache[parent_id] = parent_inv
 
345
        if parent_invs == []:
 
346
            base_inv = Inventory(root_id=None)
 
347
        else:
 
348
            base_inv = parent_invs[0]
 
349
        inv_delta, unusual_modes, shamap = import_git_tree(repo.texts, 
 
350
                mapping, "", root_trees[revid], base_inv, None, revid, 
 
351
                parent_invs, target_git_object_retriever._idmap, lookup_object)
 
352
        target_git_object_retriever._idmap.add_entries(shamap)
 
353
        if unusual_modes != {}:
 
354
            ret = "unusual modes: \n"
 
355
            for item in unusual_modes.iteritems():
 
356
                ret += "\t%s: %o\n" % item
 
357
            raise AssertionError(ret)
 
358
        try:
 
359
            basis_id = rev.parent_ids[0]
 
360
        except IndexError:
 
361
            basis_id = NULL_REVISION
 
362
        rev.inventory_sha1, inv = repo.add_inventory_by_delta(basis_id,
 
363
                  inv_delta, rev.revision_id, rev.parent_ids)
 
364
        parent_invs_cache[rev.revision_id] = inv
 
365
        repo.add_revision(rev.revision_id, rev)
 
366
        if "verify" in debug.debug_flags:
 
367
            objs = inventory_to_tree_and_blobs(inv, repo.texts, mapping)
 
368
            for sha1, newobj, path in objs:
 
369
                assert path is not None
 
370
                oldobj = tree_lookup_path(lookup_object, root_trees[revid], path)
 
371
                assert oldobj == newobj, "%r != %r in %s" % (oldobj, newobj, path)
 
372
 
 
373
    target_git_object_retriever._idmap.commit()
 
374
 
 
375
 
 
376
class InterGitNonGitRepository(InterRepository):
 
377
    """Base InterRepository that copies revisions from a Git into a non-Git 
 
378
    repository."""
 
379
 
 
380
    _matching_repo_format = GitRepositoryFormat()
 
381
 
 
382
    @staticmethod
 
383
    def _get_repo_format_to_test():
 
384
        return None
 
385
 
 
386
    def copy_content(self, revision_id=None, pb=None):
 
387
        """See InterRepository.copy_content."""
 
388
        self.fetch(revision_id, pb, find_ghosts=False)
 
389
 
 
390
    def fetch(self, revision_id=None, pb=None, find_ghosts=False, mapping=None,
 
391
            fetch_spec=None):
 
392
        self.fetch_refs(revision_id=revision_id, pb=pb, find_ghosts=find_ghosts,
 
393
                mapping=mapping, fetch_spec=fetch_spec)
 
394
 
 
395
    def fetch_refs(self, revision_id=None, pb=None, find_ghosts=False, 
 
396
              mapping=None, fetch_spec=None):
 
397
        if mapping is None:
 
398
            mapping = self.source.get_mapping()
 
399
        if revision_id is not None:
 
400
            interesting_heads = [revision_id]
 
401
        elif fetch_spec is not None:
 
402
            interesting_heads = fetch_spec.heads
 
403
        else:
 
404
            interesting_heads = None
 
405
        self._refs = {}
 
406
        def determine_wants(refs):
 
407
            self._refs = refs
 
408
            if interesting_heads is None:
 
409
                ret = [sha for (ref, sha) in refs.iteritems() if not ref.endswith("^{}")]
 
410
            else:
 
411
                ret = [mapping.revision_id_bzr_to_foreign(revid)[0] for revid in interesting_heads if revid != NULL_REVISION]
 
412
            return [rev for rev in ret if not self.target.has_revision(mapping.revision_id_foreign_to_bzr(rev))]
 
413
        self.fetch_objects(determine_wants, mapping, pb)
 
414
        return self._refs
 
415
 
 
416
 
 
417
 
 
418
class InterRemoteGitNonGitRepository(InterGitNonGitRepository):
 
419
    """InterRepository that copies revisions from a remote Git into a non-Git 
 
420
    repository."""
 
421
 
 
422
    def fetch_objects(self, determine_wants, mapping, pb=None):
 
423
        def progress(text):
 
424
            pb.update("git: %s" % text.rstrip("\r\n"), 0, 0)
 
425
        graph_walker = BzrFetchGraphWalker(self.target, mapping)
 
426
        create_pb = None
 
427
        if pb is None:
 
428
            create_pb = pb = ui.ui_factory.nested_progress_bar()
 
429
        target_git_object_retriever = BazaarObjectStore(self.target, mapping)
 
430
        recorded_wants = []
 
431
 
 
432
        def record_determine_wants(heads):
 
433
            wants = determine_wants(heads)
 
434
            recorded_wants.extend(wants)
 
435
            return wants
 
436
        
 
437
        try:
 
438
            self.target.lock_write()
 
439
            try:
 
440
                self.target.start_write_group()
 
441
                try:
 
442
                    objects_iter = self.source.fetch_objects(
 
443
                                record_determine_wants, 
 
444
                                graph_walker, 
 
445
                                target_git_object_retriever.get_raw, 
 
446
                                progress)
 
447
                    import_git_objects(self.target, mapping, objects_iter, 
 
448
                            target_git_object_retriever, recorded_wants, pb)
 
449
                finally:
 
450
                    self.target.commit_write_group()
 
451
            finally:
 
452
                self.target.unlock()
 
453
        finally:
 
454
            if create_pb:
 
455
                create_pb.finished()
 
456
 
 
457
    @staticmethod
 
458
    def is_compatible(source, target):
 
459
        """Be compatible with GitRepository."""
 
460
        # FIXME: Also check target uses VersionedFile
 
461
        return (isinstance(source, RemoteGitRepository) and 
 
462
                target.supports_rich_root() and
 
463
                not isinstance(target, GitRepository))
 
464
 
 
465
 
 
466
class InterLocalGitNonGitRepository(InterGitNonGitRepository):
 
467
    """InterRepository that copies revisions from a remote Git into a non-Git 
 
468
    repository."""
 
469
 
 
470
    def fetch_objects(self, determine_wants, mapping, pb=None):
 
471
        wants = determine_wants(self.source._git.get_refs())
 
472
        create_pb = None
 
473
        if pb is None:
 
474
            create_pb = pb = ui.ui_factory.nested_progress_bar()
 
475
        target_git_object_retriever = BazaarObjectStore(self.target, mapping)
 
476
        try:
 
477
            self.target.lock_write()
 
478
            try:
 
479
                self.target.start_write_group()
 
480
                try:
 
481
                    import_git_objects(self.target, mapping, 
 
482
                            self.source._git.object_store, 
 
483
                            target_git_object_retriever, wants, pb)
 
484
                finally:
 
485
                    self.target.commit_write_group()
 
486
            finally:
 
487
                self.target.unlock()
 
488
        finally:
 
489
            if create_pb:
 
490
                create_pb.finished()
 
491
 
 
492
    @staticmethod
 
493
    def is_compatible(source, target):
 
494
        """Be compatible with GitRepository."""
 
495
        # FIXME: Also check target uses VersionedFile
 
496
        return (isinstance(source, LocalGitRepository) and 
 
497
                target.supports_rich_root() and
 
498
                not isinstance(target, GitRepository))
 
499
 
 
500
 
 
501
class InterGitRepository(InterRepository):
 
502
    """InterRepository that copies between Git repositories."""
 
503
 
 
504
    _matching_repo_format = GitRepositoryFormat()
 
505
 
 
506
    @staticmethod
 
507
    def _get_repo_format_to_test():
 
508
        return None
 
509
 
 
510
    def copy_content(self, revision_id=None, pb=None):
 
511
        """See InterRepository.copy_content."""
 
512
        self.fetch(revision_id, pb, find_ghosts=False)
 
513
 
 
514
    def fetch(self, revision_id=None, pb=None, find_ghosts=False, 
 
515
              mapping=None, fetch_spec=None):
 
516
        if mapping is None:
 
517
            mapping = self.source.get_mapping()
 
518
        def progress(text):
 
519
            trace.info("git: %s", text)
 
520
        r = self.target._git
 
521
        if revision_id is not None:
 
522
            args = [mapping.revision_id_bzr_to_foreign(revision_id)[0]]
 
523
        elif fetch_spec is not None:
 
524
            args = [mapping.revision_id_bzr_to_foreign(revid)[0] for revid in fetch_spec.heads]
 
525
        if fetch_spec is None and revision_id is None:
 
526
            determine_wants = r.object_store.determine_wants_all
 
527
        else:
 
528
            determine_wants = lambda x: [y for y in args if not y in r.object_store]
 
529
 
 
530
        graphwalker = SimpleFetchGraphWalker(r.heads().values(), r.get_parents)
 
531
        f, commit = r.object_store.add_thin_pack()
 
532
        try:
 
533
            self.source.fetch_pack(determine_wants, graphwalker, f.write, progress)
 
534
            commit()
 
535
        except:
 
536
            f.close()
 
537
            raise
 
538
 
 
539
    @staticmethod
 
540
    def is_compatible(source, target):
 
541
        """Be compatible with GitRepository."""
 
542
        return (isinstance(source, GitRepository) and 
 
543
                isinstance(target, GitRepository))