19
19
from dulwich.objects import (
24
from dulwich.object_store import (
25
28
from bzrlib import (
35
from bzrlib.revision import (
30
39
from bzrlib.plugins.git.mapping import (
42
extract_unusual_modes,
35
46
from bzrlib.plugins.git.shamap import (
47
from_repository as cache_from_repository,
40
class BazaarObjectStore(object):
53
def get_object_store(repo, mapping=None):
54
git = getattr(repo, "_git", None)
56
return git.object_store
57
return BazaarObjectStore(repo, mapping)
60
MAX_TREE_CACHE_SIZE = 50 * 1024 * 1024
63
class LRUTreeCache(object):
65
def __init__(self, repository):
66
def approx_tree_size(tree):
67
# Very rough estimate, 1k per inventory entry
68
return len(tree.inventory) * 1024
69
self.repository = repository
70
self._cache = lru_cache.LRUSizeCache(max_size=MAX_TREE_CACHE_SIZE,
71
after_cleanup_size=None, compute_size=approx_tree_size)
73
def revision_tree(self, revid):
75
return self._cache[revid]
77
tree = self.repository.revision_tree(revid)
81
def iter_revision_trees(self, revids):
82
trees = dict([(k, self._cache.get(k)) for k in revids])
83
for tree in self.repository.revision_trees(
84
[r for r, v in trees.iteritems() if v is None]):
85
trees[tree.get_revision_id()] = tree
87
return (trees[r] for r in revids)
89
def revision_trees(self, revids):
90
return list(self.iter_revision_trees(revids))
93
self._cache.add(tree.get_revision_id(), tree)
96
def _find_missing_bzr_revids(get_parent_map, want, have):
97
"""Find the revisions that have to be pushed.
99
:param get_parent_map: Function that returns the parents for a sequence
101
:param want: Revisions the target wants
102
:param have: Revisions the target already has
103
:return: Set of revisions to fetch
105
pending = want - have
109
processed.update(pending)
110
next_map = get_parent_map(pending)
112
for item in next_map.iteritems():
116
next_pending.update(p for p in item[1] if p not in processed)
117
pending = next_pending
118
if NULL_REVISION in todo:
119
todo.remove(NULL_REVISION)
123
def _check_expected_sha(expected_sha, object):
124
"""Check whether an object matches an expected SHA.
126
:param expected_sha: None or expected SHA as either binary or as hex digest
127
:param object: Object to verify
129
if expected_sha is None:
131
if len(expected_sha) == 40:
132
if expected_sha != object.sha().hexdigest():
133
raise AssertionError("Invalid sha for %r: %s" % (object,
135
elif len(expected_sha) == 20:
136
if expected_sha != object.sha().digest():
137
raise AssertionError("Invalid sha for %r: %s" % (object,
138
sha_to_hex(expected_sha)))
140
raise AssertionError("Unknown length %d for %r" % (len(expected_sha),
144
def _tree_to_objects(tree, parent_trees, idmap, unusual_modes):
145
"""Iterate over the objects that were introduced in a revision.
148
:param unusual_modes: Unusual file modes
149
:return: Yields (path, object, ie) entries
155
base_tree = parent_trees[0]
156
other_parent_trees = parent_trees[1:]
158
base_tree = tree._repository.revision_tree(NULL_REVISION)
159
other_parent_trees = []
160
def find_unchanged_parent_ie(ie, parent_trees):
161
assert ie.kind in ("symlink", "file")
162
for ptree in parent_trees:
164
pie = ptree.inventory[ie.file_id]
165
except errors.NoSuchId:
168
if (pie.text_sha1 == ie.text_sha1 and
169
pie.kind == ie.kind and
170
pie.symlink_target == ie.symlink_target):
173
for (file_id, path, changed_content, versioned, parent, name, kind,
174
executable) in tree.iter_changes(base_tree):
175
if kind[1] == "file":
176
ie = tree.inventory[file_id]
180
pie = find_unchanged_parent_ie(ie, other_parent_trees)
184
shamap[ie.file_id] = idmap.lookup_blob_id(
185
pie.file_id, pie.revision)
186
if not file_id in shamap:
187
new_blobs.append((path[1], ie))
188
new_trees[posixpath.dirname(path[1])] = parent[1]
189
elif kind[1] == "symlink":
190
ie = tree.inventory[file_id]
192
blob = symlink_to_blob(ie)
193
shamap[file_id] = blob.id
195
find_unchanged_parent_ie(ie, other_parent_trees)
197
yield path[1], blob, ie
198
new_trees[posixpath.dirname(path[1])] = parent[1]
199
elif kind[1] not in (None, "directory"):
200
raise AssertionError(kind[1])
201
if path[0] is not None:
202
new_trees[posixpath.dirname(path[0])] = parent[0]
204
for (path, ie), chunks in tree.iter_files_bytes(
205
[(ie.file_id, (path, ie)) for (path, ie) in new_blobs]):
209
shamap[ie.file_id] = obj.id
211
for path in unusual_modes:
212
parent_path = posixpath.dirname(path)
213
new_trees[parent_path] = tree.path2id(parent_path)
217
items = new_trees.items()
219
for path, file_id in items:
221
parent_id = tree.inventory[file_id].parent_id
222
except errors.NoSuchId:
223
# Directory was removed recursively perhaps ?
225
if parent_id is not None:
226
parent_path = urlutils.dirname(path)
227
new_trees[parent_path] = parent_id
228
trees[path] = file_id
230
def ie_to_hexsha(ie):
232
return shamap[ie.file_id]
234
# FIXME: Should be the same as in parent
235
if ie.kind in ("file", "symlink"):
237
return idmap.lookup_blob_id(ie.file_id, ie.revision)
241
blob.data = tree.get_file_text(ie.file_id)
243
elif ie.kind == "directory":
244
# Not all cache backends store the tree information,
245
# calculate again from scratch
246
ret = directory_to_tree(ie, ie_to_hexsha, unusual_modes)
253
for path in sorted(trees.keys(), reverse=True):
254
ie = tree.inventory[trees[path]]
255
assert ie.kind == "directory"
256
obj = directory_to_tree(ie, ie_to_hexsha, unusual_modes)
259
shamap[ie.file_id] = obj.id
262
class BazaarObjectStore(BaseObjectStore):
41
263
"""A Git-style object store backed onto a Bazaar repository."""
43
265
def __init__(self, repository, mapping=None):
44
266
self.repository = repository
45
267
if mapping is None:
46
self.mapping = self.repository.get_mapping()
268
self.mapping = default_mapping
48
270
self.mapping = mapping
49
self._idmap = SqliteGitShaMap.from_repository(repository)
271
self._cache = cache_from_repository(repository)
272
self._content_cache_types = ("tree")
273
self.start_write_group = self._cache.idmap.start_write_group
274
self.abort_write_group = self._cache.idmap.abort_write_group
275
self.commit_write_group = self._cache.idmap.commit_write_group
276
self.tree_cache = LRUTreeCache(self.repository)
51
def _update_sha_map(self):
52
all_revids = self.repository.all_revision_ids()
278
def _update_sha_map(self, stop_revision=None):
53
279
graph = self.repository.get_graph()
54
present_revids = set(self._idmap.revids())
55
missing_revids = [revid for revid in graph.iter_topo_order(all_revids) if revid not in present_revids]
56
pb = ui.ui_factory.nested_progress_bar()
58
for i, revid in enumerate(missing_revids):
59
pb.update("updating git map", i, len(missing_revids))
60
self._update_sha_map_revision(revid)
65
def _update_sha_map_revision(self, revid):
66
inv = self.repository.get_inventory(revid)
67
tree_sha = self._get_ie_sha1(inv.root, inv)
68
rev = self.repository.get_revision(revid)
69
commit_obj = revision_to_commit(rev, tree_sha,
70
self._idmap._parent_lookup)
72
foreign_revid, mapping = mapping_registry.parse_revision_id(revid)
280
if stop_revision is None:
281
heads = graph.heads(self.repository.all_revision_ids())
283
heads = set([stop_revision])
284
missing_revids = self._cache.idmap.missing_revisions(heads)
286
parents = graph.get_parent_map(heads)
288
for p in parents.values():
289
todo.update([x for x in p if x not in missing_revids])
290
heads = self._cache.idmap.missing_revisions(todo)
291
missing_revids.update(heads)
292
if NULL_REVISION in missing_revids:
293
missing_revids.remove(NULL_REVISION)
294
missing_revids = self.repository.has_revisions(missing_revids)
295
if not missing_revids:
297
self.start_write_group()
299
pb = ui.ui_factory.nested_progress_bar()
301
for i, revid in enumerate(graph.iter_topo_order(missing_revids)):
302
trace.mutter('processing %r', revid)
303
pb.update("updating git map", i, len(missing_revids))
304
self._update_sha_map_revision(revid)
308
self.abort_write_group()
311
self.commit_write_group()
314
self._update_sha_map()
315
return iter(self._cache.idmap.sha1s())
317
def _reconstruct_commit(self, rev, tree_sha):
318
def parent_lookup(revid):
320
return self._lookup_revision_sha1(revid)
321
except errors.NoSuchRevision:
322
trace.warning("Ignoring ghost parent %s", revid)
324
return self.mapping.export_commit(rev, tree_sha, parent_lookup)
326
def _revision_to_objects(self, rev, tree):
327
unusual_modes = extract_unusual_modes(rev)
328
present_parents = self.repository.has_revisions(rev.parent_ids)
329
parent_trees = self.tree_cache.revision_trees(
330
[p for p in rev.parent_ids if p in present_parents])
332
for path, obj, ie in _tree_to_objects(tree, parent_trees,
333
self._cache.idmap, unusual_modes):
338
# Pointless commit - get the tree sha elsewhere
339
if not rev.parent_ids:
342
base_sha1 = self._lookup_revision_sha1(rev.parent_ids[0])
343
tree_sha = self[base_sha1].tree
344
commit_obj = self._reconstruct_commit(rev, tree_sha)
346
foreign_revid, mapping = mapping_registry.parse_revision_id(
73
348
except errors.InvalidRevisionId:
76
if foreign_revid != commit_obj.id:
77
raise AssertionError("recreated git commit had different sha1: expected %s, got %s" % (foreign_revid, commit_obj.id))
78
self._idmap.add_entry(commit_obj.id, "commit", (revid, tree_sha))
80
def _check_expected_sha(self, expected_sha, object):
81
if expected_sha is None:
83
if expected_sha != object.id:
84
raise AssertionError("Invalid sha for %r: %s" % (object, expected_sha))
86
def _get_ie_object(self, entry, inv):
87
if entry.kind == "directory":
88
return self._get_tree(entry.file_id, inv.revision_id, inv=inv)
90
return self._get_blob(entry.file_id, entry.revision)
92
def _get_ie_object_or_sha1(self, entry, inv):
93
if entry.kind == "directory":
95
return self._idmap.lookup_tree(entry.file_id, inv.revision_id), None
97
ret = self._get_ie_object(entry, inv)
98
self._idmap.add_entry(ret.id, "tree", (entry.file_id, inv.revision_id))
102
return self._idmap.lookup_blob(entry.file_id, entry.revision), None
104
ret = self._get_ie_object(entry, inv)
105
self._idmap.add_entry(ret.id, "blob", (entry.file_id, entry.revision))
108
def _get_ie_sha1(self, entry, inv):
109
return self._get_ie_object_or_sha1(entry, inv)[0]
111
def _get_blob(self, fileid, revision, expected_sha=None):
351
_check_expected_sha(foreign_revid, commit_obj)
352
yield None, commit_obj, None
354
def _get_updater(self, rev):
355
return self._cache.get_updater(rev)
357
def _update_sha_map_revision(self, revid):
358
rev = self.repository.get_revision(revid)
359
tree = self.tree_cache.revision_tree(rev.revision_id)
360
updater = self._get_updater(rev)
361
for path, obj, ie in self._revision_to_objects(rev, tree):
362
updater.add_object(obj, ie)
363
commit_obj = updater.finish()
366
def _reconstruct_blobs(self, keys):
112
367
"""Return a Git Blob object from a fileid and revision stored in bzr.
114
369
:param fileid: File id of the text
115
370
:param revision: Revision of the text
117
text = self.repository.texts.get_record_stream([(fileid, revision)],
118
"unordered", True).next().get_bytes_as("fulltext")
121
self._check_expected_sha(expected_sha, blob)
372
stream = self.repository.iter_files_bytes(
373
((key[0], key[1], key) for key in keys))
374
for (fileid, revision, expected_sha), chunks in stream:
376
blob.chunked = chunks
377
if blob.id != expected_sha and blob.data == "":
378
# Perhaps it's a symlink ?
379
tree = self.tree_cache.revision_tree(revision)
380
entry = tree.inventory[fileid]
381
if entry.kind == 'symlink':
382
blob = symlink_to_blob(entry)
383
_check_expected_sha(expected_sha, blob)
124
def _get_tree(self, fileid, revid, inv=None, expected_sha=None):
386
def _reconstruct_tree(self, fileid, revid, inv, unusual_modes,
125
388
"""Return a Git Tree object from a file id and a revision stored in bzr.
127
390
:param fileid: fileid in the tree.
128
391
:param revision: Revision of the tree.
131
inv = self.repository.get_inventory(revid)
132
tree = directory_to_tree(inv[fileid], lambda ie: self._get_ie_sha1(ie, inv))
133
self._check_expected_sha(expected_sha, tree)
393
def get_ie_sha1(entry):
394
if entry.kind == "directory":
396
return self._cache.idmap.lookup_tree_id(entry.file_id,
398
except (NotImplementedError, KeyError):
399
obj = self._reconstruct_tree(entry.file_id, revid, inv,
405
elif entry.kind in ("file", "symlink"):
407
return self._cache.idmap.lookup_blob_id(entry.file_id,
411
return self._reconstruct_blobs(
412
[(entry.file_id, entry.revision, None)]).next().id
414
raise AssertionError("unknown entry kind '%s'" % entry.kind)
415
tree = directory_to_tree(inv[fileid], get_ie_sha1, unusual_modes)
416
_check_expected_sha(expected_sha, tree)
136
def _get_commit(self, revid, tree_sha, expected_sha=None):
137
rev = self.repository.get_revision(revid)
138
commit = revision_to_commit(rev, tree_sha, self._lookup_revision_sha1)
139
self._check_expected_sha(expected_sha, commit)
419
def get_parents(self, sha):
420
"""Retrieve the parents of a Git commit by SHA1.
422
:param sha: SHA1 of the commit
423
:raises: KeyError, NotCommitError
425
return self[sha].parents
142
427
def _lookup_revision_sha1(self, revid):
428
"""Return the SHA1 matching a Bazaar revision."""
429
from dulwich.protocol import ZERO_SHA
430
if revid == NULL_REVISION:
144
return self._idmap._parent_lookup(revid)
433
return self._cache.idmap.lookup_commit(revid)
146
inv = self.repository.get_inventory(revid)
147
tree_sha = self._get_ie_sha1(inv.root, inv)
148
ret = self._get_commit(revid, tree_sha).id
149
self._idmap.add_entry(ret, "commit", (revid, tree_sha))
436
return mapping_registry.parse_revision_id(revid)[0]
437
except errors.InvalidRevisionId:
438
self._update_sha_map(revid)
439
return self._cache.idmap.lookup_commit(revid)
152
441
def get_raw(self, sha):
153
return self[sha]._text
442
"""Get the raw representation of a Git object by SHA1.
444
:param sha: SHA1 of the git object
447
return (obj.type, obj.as_raw_string())
449
def __contains__(self, sha):
450
# See if sha is in map
452
(type, type_data) = self.lookup_git_sha(sha)
454
return self.repository.has_revision(type_data[0])
456
return self.repository.texts.has_version(type_data)
458
return self.repository.has_revision(type_data[1])
460
raise AssertionError("Unknown object type '%s'" % type)
464
def lookup_git_shas(self, shas, update_map=True):
468
ret[sha] = self._cache.idmap.lookup_git_sha(sha)
471
# if not, see if there are any unconverted revisions and add
472
# them to the map, search for sha in map again
473
self._update_sha_map()
476
ret[sha] = self._cache.idmap.lookup_git_sha(sha)
481
def lookup_git_sha(self, sha, update_map=True):
482
return self.lookup_git_shas([sha], update_map=update_map)[sha]
155
484
def __getitem__(self, sha):
156
# See if sha is in map
158
(type, type_data) = self._idmap.lookup_git_sha(sha)
160
# if not, see if there are any unconverted revisions and add them
161
# to the map, search for sha in map again
162
self._update_sha_map()
163
(type, type_data) = self._idmap.lookup_git_sha(sha)
485
if self._cache.content_cache is not None:
487
return self._cache.content_cache[sha]
490
(type, type_data) = self.lookup_git_sha(sha)
164
491
# convert object to git object
165
492
if type == "commit":
166
return self._get_commit(type_data[0], type_data[1],
493
(revid, tree_sha) = type_data
495
rev = self.repository.get_revision(revid)
496
except errors.NoSuchRevision:
497
trace.mutter('entry for %s %s in shamap: %r, but not found in '
498
'repository', type, sha, type_data)
500
commit = self._reconstruct_commit(rev, tree_sha)
501
_check_expected_sha(sha, commit)
168
503
elif type == "blob":
169
return self._get_blob(type_data[0], type_data[1], expected_sha=sha)
504
(fileid, revision) = type_data
505
return self._reconstruct_blobs([(fileid, revision, sha)]).next()
170
506
elif type == "tree":
171
return self._get_tree(type_data[0], type_data[1], expected_sha=sha)
507
(fileid, revid) = type_data
509
tree = self.tree_cache.revision_tree(revid)
510
rev = self.repository.get_revision(revid)
511
except errors.NoSuchRevision:
512
trace.mutter('entry for %s %s in shamap: %r, but not found in repository', type, sha, type_data)
514
unusual_modes = extract_unusual_modes(rev)
516
return self._reconstruct_tree(fileid, revid, tree.inventory,
517
unusual_modes, expected_sha=sha)
518
except errors.NoSuchRevision:
173
521
raise AssertionError("Unknown object type '%s'" % type)
523
def generate_pack_contents(self, have, want, progress=None,
525
"""Iterate over the contents of a pack file.
527
:param have: List of SHA1s of objects that should not be sent
528
:param want: List of SHA1s of objects that should be sent
531
ret = self.lookup_git_shas(have + want)
532
for commit_sha in have:
534
(type, (revid, tree_sha)) = ret[commit_sha]
538
assert type == "commit"
541
for commit_sha in want:
542
if commit_sha in have:
545
(type, (revid, tree_sha)) = ret[commit_sha]
549
assert type == "commit"
552
todo = _find_missing_bzr_revids(self.repository.get_parent_map,
554
trace.mutter('sending revisions %r', todo)
556
pb = ui.ui_factory.nested_progress_bar()
558
for i, revid in enumerate(todo):
559
pb.update("generating git objects", i, len(todo))
560
rev = self.repository.get_revision(revid)
561
tree = self.tree_cache.revision_tree(revid)
562
for path, obj, ie in self._revision_to_objects(rev, tree):
563
ret.append((obj, path))
568
def add_thin_pack(self):
571
fd, path = tempfile.mkstemp(suffix=".pack")
572
f = os.fdopen(fd, 'wb')
574
from dulwich.pack import PackData, Pack
575
from bzrlib.plugins.git.fetch import import_git_objects
578
if os.path.getsize(path) == 0:
581
pd.create_index_v2(path[:-5]+".idx", self.object_store.get_raw)
584
self.repository.lock_write()
586
self.repository.start_write_group()
588
import_git_objects(self.repository, self.mapping,
589
p.iterobjects(get_raw=self.get_raw),
592
self.repository.abort_write_group()
595
self.repository.commit_write_group()
597
self.repository.unlock()
600
# The pack isn't kept around anyway, so no point
601
# in treating full packs different from thin packs
602
add_pack = add_thin_pack