1
# Copyright (C) 2009 Jelmer Vernooij <jelmer@samba.org>
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.
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.
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
17
"""Map from Git sha's to Bazaar objects."""
19
from dulwich.objects import (
24
from dulwich.object_store import (
35
from bzrlib.inventory import (
38
from bzrlib.revision import (
42
from bzrlib.plugins.git.mapping import (
45
extract_unusual_modes,
49
from bzrlib.plugins.git.shamap import (
50
from_repository as cache_from_repository,
57
def get_object_store(repo, mapping=None):
58
git = getattr(repo, "_git", None)
60
return git.object_store
61
return BazaarObjectStore(repo, mapping)
64
MAX_TREE_CACHE_SIZE = 50 * 1024 * 1024
67
class LRUTreeCache(object):
69
def __init__(self, repository):
70
def approx_tree_size(tree):
71
# Very rough estimate, 1k per inventory entry
72
return len(tree.inventory) * 1024
73
self.repository = repository
74
self._cache = lru_cache.LRUSizeCache(max_size=MAX_TREE_CACHE_SIZE,
75
after_cleanup_size=None, compute_size=approx_tree_size)
77
def revision_tree(self, revid):
79
return self._cache[revid]
81
tree = self.repository.revision_tree(revid)
85
def iter_revision_trees(self, revids):
86
trees = dict([(k, self._cache.get(k)) for k in revids])
87
for tree in self.repository.revision_trees(
88
[r for r, v in trees.iteritems() if v is None]):
89
trees[tree.get_revision_id()] = tree
91
return (trees[r] for r in revids)
93
def revision_trees(self, revids):
94
return list(self.iter_revision_trees(revids))
97
self._cache.add(tree.get_revision_id(), tree)
100
def _find_missing_bzr_revids(get_parent_map, want, have):
101
"""Find the revisions that have to be pushed.
103
:param get_parent_map: Function that returns the parents for a sequence
105
:param want: Revisions the target wants
106
:param have: Revisions the target already has
107
:return: Set of revisions to fetch
109
pending = want - have
113
processed.update(pending)
114
next_map = get_parent_map(pending)
116
for item in next_map.iteritems():
120
next_pending.update(p for p in item[1] if p not in processed)
121
pending = next_pending
122
if NULL_REVISION in todo:
123
todo.remove(NULL_REVISION)
127
def _check_expected_sha(expected_sha, object):
128
"""Check whether an object matches an expected SHA.
130
:param expected_sha: None or expected SHA as either binary or as hex digest
131
:param object: Object to verify
133
if expected_sha is None:
135
if len(expected_sha) == 40:
136
if expected_sha != object.sha().hexdigest():
137
raise AssertionError("Invalid sha for %r: %s" % (object,
139
elif len(expected_sha) == 20:
140
if expected_sha != object.sha().digest():
141
raise AssertionError("Invalid sha for %r: %s" % (object,
142
sha_to_hex(expected_sha)))
144
raise AssertionError("Unknown length %d for %r" % (len(expected_sha),
148
def _tree_to_objects(tree, parent_trees, idmap, unusual_modes):
149
"""Iterate over the objects that were introduced in a revision.
152
:param unusual_modes: Unusual file modes
153
:return: Yields (path, object, ie) entries
159
base_tree = parent_trees[0]
160
other_parent_trees = parent_trees[1:]
162
base_tree = tree._repository.revision_tree(NULL_REVISION)
163
other_parent_trees = []
164
def find_unchanged_parent_ie(ie, parent_trees):
165
assert ie.kind in ("symlink", "file")
166
for ptree in parent_trees:
168
pie = ptree.inventory[ie.file_id]
169
except errors.NoSuchId:
172
if (pie.text_sha1 == ie.text_sha1 and
173
pie.kind == ie.kind and
174
pie.symlink_target == ie.symlink_target):
177
for (file_id, path, changed_content, versioned, parent, name, kind,
178
executable) in tree.iter_changes(base_tree):
179
if kind[1] == "file":
180
ie = tree.inventory[file_id]
184
pie = find_unchanged_parent_ie(ie, other_parent_trees)
188
shamap[ie.file_id] = idmap.lookup_blob_id(
189
pie.file_id, pie.revision)
190
if not file_id in shamap:
191
new_blobs.append((path[1], ie))
192
new_trees[posixpath.dirname(path[1])] = parent[1]
193
elif kind[1] == "symlink":
194
ie = tree.inventory[file_id]
196
blob = symlink_to_blob(ie)
197
shamap[file_id] = blob.id
199
find_unchanged_parent_ie(ie, other_parent_trees)
201
yield path[1], blob, ie
202
new_trees[posixpath.dirname(path[1])] = parent[1]
203
elif kind[1] not in (None, "directory"):
204
raise AssertionError(kind[1])
205
if path[0] is not None:
206
new_trees[posixpath.dirname(path[0])] = parent[0]
208
for (path, ie), chunks in tree.iter_files_bytes(
209
[(ie.file_id, (path, ie)) for (path, ie) in new_blobs]):
213
shamap[ie.file_id] = obj.id
215
for path in unusual_modes:
216
parent_path = posixpath.dirname(path)
217
new_trees[parent_path] = tree.path2id(parent_path)
221
items = new_trees.items()
223
for path, file_id in items:
225
parent_id = tree.inventory[file_id].parent_id
226
except errors.NoSuchId:
227
# Directory was removed recursively perhaps ?
229
if parent_id is not None:
230
parent_path = urlutils.dirname(path)
231
new_trees[parent_path] = parent_id
232
trees[path] = file_id
234
def ie_to_hexsha(ie):
236
return shamap[ie.file_id]
238
# FIXME: Should be the same as in parent
239
if ie.kind in ("file", "symlink"):
241
return idmap.lookup_blob_id(ie.file_id, ie.revision)
245
blob.data = tree.get_file_text(ie.file_id)
247
elif ie.kind == "directory":
248
# Not all cache backends store the tree information,
249
# calculate again from scratch
250
ret = directory_to_tree(ie, ie_to_hexsha, unusual_modes)
257
for path in sorted(trees.keys(), reverse=True):
258
ie = tree.inventory[trees[path]]
259
assert ie.kind == "directory"
260
obj = directory_to_tree(ie, ie_to_hexsha, unusual_modes)
263
shamap[ie.file_id] = obj.id
266
class BazaarObjectStore(BaseObjectStore):
267
"""A Git-style object store backed onto a Bazaar repository."""
269
def __init__(self, repository, mapping=None):
270
self.repository = repository
272
self.mapping = default_mapping
274
self.mapping = mapping
275
self._cache = cache_from_repository(repository)
276
self._content_cache_types = ("tree")
277
self.start_write_group = self._cache.idmap.start_write_group
278
self.abort_write_group = self._cache.idmap.abort_write_group
279
self.commit_write_group = self._cache.idmap.commit_write_group
280
self.tree_cache = LRUTreeCache(self.repository)
282
def _update_sha_map(self, stop_revision=None):
283
graph = self.repository.get_graph()
284
if stop_revision is None:
285
heads = graph.heads(self.repository.all_revision_ids())
287
heads = set([stop_revision])
288
missing_revids = self._cache.idmap.missing_revisions(heads)
290
parents = graph.get_parent_map(heads)
292
for p in parents.values():
293
todo.update([x for x in p if x not in missing_revids])
294
heads = self._cache.idmap.missing_revisions(todo)
295
missing_revids.update(heads)
296
if NULL_REVISION in missing_revids:
297
missing_revids.remove(NULL_REVISION)
298
missing_revids = self.repository.has_revisions(missing_revids)
299
if not missing_revids:
301
self.start_write_group()
303
pb = ui.ui_factory.nested_progress_bar()
305
for i, revid in enumerate(graph.iter_topo_order(missing_revids)):
306
trace.mutter('processing %r', revid)
307
pb.update("updating git map", i, len(missing_revids))
308
self._update_sha_map_revision(revid)
312
self.abort_write_group()
315
self.commit_write_group()
318
self._update_sha_map()
319
return iter(self._cache.idmap.sha1s())
321
def _reconstruct_commit(self, rev, tree_sha, roundtrip):
322
def parent_lookup(revid):
324
return self._lookup_revision_sha1(revid)
325
except errors.NoSuchRevision:
326
trace.warning("Ignoring ghost parent %s", revid)
328
return self.mapping.export_commit(rev, tree_sha, parent_lookup,
331
def _revision_to_objects(self, rev, tree, roundtrip):
332
"""Convert a revision to a set of git objects.
334
:param rev: Bazaar revision object
335
:param tree: Bazaar revision tree
336
:param roundtrip: Whether to roundtrip all Bazaar revision data
338
unusual_modes = extract_unusual_modes(rev)
339
present_parents = self.repository.has_revisions(rev.parent_ids)
340
parent_trees = self.tree_cache.revision_trees(
341
[p for p in rev.parent_ids if p in present_parents])
343
for path, obj, ie in _tree_to_objects(tree, parent_trees,
344
self._cache.idmap, unusual_modes):
348
if root_tree is None:
349
# Pointless commit - get the tree sha elsewhere
350
if not rev.parent_ids:
353
base_sha1 = self._lookup_revision_sha1(rev.parent_ids[0])
354
root_tree = self[base_sha1]
356
b = self.mapping.export_fileid_map({}) # FIXME
358
root_tree[self.mapping.BZR_FILE_IDS_FILE] = ((stat.S_IFREG | 0644), b.id)
359
yield self.mapping.BZR_FILE_IDS_FILE, b, None
360
commit_obj = self._reconstruct_commit(rev, root_tree.id, roundtrip=roundtrip)
362
foreign_revid, mapping = mapping_registry.parse_revision_id(
364
except errors.InvalidRevisionId:
367
_check_expected_sha(foreign_revid, commit_obj)
368
yield None, commit_obj, None
370
def _get_updater(self, rev):
371
return self._cache.get_updater(rev)
373
def _update_sha_map_revision(self, revid):
374
rev = self.repository.get_revision(revid)
375
tree = self.tree_cache.revision_tree(rev.revision_id)
376
updater = self._get_updater(rev)
377
for path, obj, ie in self._revision_to_objects(rev, tree,
379
updater.add_object(obj, ie)
380
commit_obj = updater.finish()
383
def _reconstruct_blobs(self, keys):
384
"""Return a Git Blob object from a fileid and revision stored in bzr.
386
:param fileid: File id of the text
387
:param revision: Revision of the text
389
stream = self.repository.iter_files_bytes(
390
((key[0], key[1], key) for key in keys))
391
for (fileid, revision, expected_sha), chunks in stream:
393
blob.chunked = chunks
394
if blob.id != expected_sha and blob.data == "":
395
# Perhaps it's a symlink ?
396
tree = self.tree_cache.revision_tree(revision)
397
entry = tree.inventory[fileid]
398
if entry.kind == 'symlink':
399
blob = symlink_to_blob(entry)
400
_check_expected_sha(expected_sha, blob)
403
def _reconstruct_tree(self, fileid, revid, inv, unusual_modes,
405
"""Return a Git Tree object from a file id and a revision stored in bzr.
407
:param fileid: fileid in the tree.
408
:param revision: Revision of the tree.
410
def get_ie_sha1(entry):
411
if entry.kind == "directory":
413
return self._cache.idmap.lookup_tree_id(entry.file_id,
415
except (NotImplementedError, KeyError):
416
obj = self._reconstruct_tree(entry.file_id, revid, inv,
422
elif entry.kind in ("file", "symlink"):
424
return self._cache.idmap.lookup_blob_id(entry.file_id,
428
return self._reconstruct_blobs(
429
[(entry.file_id, entry.revision, None)]).next().id
431
raise AssertionError("unknown entry kind '%s'" % entry.kind)
432
tree = directory_to_tree(inv[fileid], get_ie_sha1, unusual_modes)
433
_check_expected_sha(expected_sha, tree)
436
def get_parents(self, sha):
437
"""Retrieve the parents of a Git commit by SHA1.
439
:param sha: SHA1 of the commit
440
:raises: KeyError, NotCommitError
442
return self[sha].parents
444
def _lookup_revision_sha1(self, revid):
445
"""Return the SHA1 matching a Bazaar revision."""
446
from dulwich.protocol import ZERO_SHA
447
if revid == NULL_REVISION:
450
return self._cache.idmap.lookup_commit(revid)
453
return mapping_registry.parse_revision_id(revid)[0]
454
except errors.InvalidRevisionId:
455
self._update_sha_map(revid)
456
return self._cache.idmap.lookup_commit(revid)
458
def get_raw(self, sha):
459
"""Get the raw representation of a Git object by SHA1.
461
:param sha: SHA1 of the git object
464
return (obj.type, obj.as_raw_string())
466
def __contains__(self, sha):
467
# See if sha is in map
469
(type, type_data) = self.lookup_git_sha(sha)
471
return self.repository.has_revision(type_data[0])
473
return self.repository.texts.has_version(type_data)
475
return self.repository.has_revision(type_data[1])
477
raise AssertionError("Unknown object type '%s'" % type)
481
def lookup_git_shas(self, shas, update_map=True):
485
ret[sha] = self._cache.idmap.lookup_git_sha(sha)
488
# if not, see if there are any unconverted revisions and add
489
# them to the map, search for sha in map again
490
self._update_sha_map()
493
ret[sha] = self._cache.idmap.lookup_git_sha(sha)
498
def lookup_git_sha(self, sha, update_map=True):
499
return self.lookup_git_shas([sha], update_map=update_map)[sha]
501
def __getitem__(self, sha):
502
if self._cache.content_cache is not None:
504
return self._cache.content_cache[sha]
507
(type, type_data) = self.lookup_git_sha(sha)
508
# convert object to git object
510
(revid, tree_sha) = type_data
512
rev = self.repository.get_revision(revid)
513
except errors.NoSuchRevision:
514
trace.mutter('entry for %s %s in shamap: %r, but not found in '
515
'repository', type, sha, type_data)
517
commit = self._reconstruct_commit(rev, tree_sha, roundtrip=True)
518
_check_expected_sha(sha, commit)
521
(fileid, revision) = type_data
522
return self._reconstruct_blobs([(fileid, revision, sha)]).next()
524
(fileid, revid) = type_data
526
tree = self.tree_cache.revision_tree(revid)
527
rev = self.repository.get_revision(revid)
528
except errors.NoSuchRevision:
529
trace.mutter('entry for %s %s in shamap: %r, but not found in repository', type, sha, type_data)
531
unusual_modes = extract_unusual_modes(rev)
533
return self._reconstruct_tree(fileid, revid, tree.inventory,
534
unusual_modes, expected_sha=sha)
535
except errors.NoSuchRevision:
538
raise AssertionError("Unknown object type '%s'" % type)
540
def generate_pack_contents(self, have, want, progress=None,
542
"""Iterate over the contents of a pack file.
544
:param have: List of SHA1s of objects that should not be sent
545
:param want: List of SHA1s of objects that should be sent
548
ret = self.lookup_git_shas(have + want)
549
for commit_sha in have:
551
(type, (revid, tree_sha)) = ret[commit_sha]
555
assert type == "commit"
558
for commit_sha in want:
559
if commit_sha in have:
562
(type, (revid, tree_sha)) = ret[commit_sha]
566
assert type == "commit"
569
todo = _find_missing_bzr_revids(self.repository.get_parent_map,
571
trace.mutter('sending revisions %r', todo)
573
pb = ui.ui_factory.nested_progress_bar()
575
for i, revid in enumerate(todo):
576
pb.update("generating git objects", i, len(todo))
577
rev = self.repository.get_revision(revid)
578
tree = self.tree_cache.revision_tree(revid)
579
for path, obj, ie in self._revision_to_objects(rev, tree):
580
ret.append((obj, path))
585
def add_thin_pack(self):
588
fd, path = tempfile.mkstemp(suffix=".pack")
589
f = os.fdopen(fd, 'wb')
591
from dulwich.pack import PackData, Pack
592
from bzrlib.plugins.git.fetch import import_git_objects
595
if os.path.getsize(path) == 0:
598
pd.create_index_v2(path[:-5]+".idx", self.object_store.get_raw)
601
self.repository.lock_write()
603
self.repository.start_write_group()
605
import_git_objects(self.repository, self.mapping,
606
p.iterobjects(get_raw=self.get_raw),
609
self.repository.abort_write_group()
612
self.repository.commit_write_group()
614
self.repository.unlock()
617
# The pack isn't kept around anyway, so no point
618
# in treating full packs different from thin packs
619
add_pack = add_thin_pack