13
13
# You should have received a copy of the GNU General Public License
14
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
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
"""Fetching from git into bzr."""
17
19
from dulwich.objects import (
23
27
from dulwich.object_store import (
26
from itertools import (
39
from bzrlib.errors import (
39
from ..errors import (
43
from bzrlib.inventory import (
42
from ..bzr.inventory import (
45
43
InventoryDirectory,
50
from bzrlib.repository import (
53
from bzrlib.revision import (
48
from ..revision import (
56
from bzrlib.revisiontree import (
59
from bzrlib.testament import (
51
from ..bzr.inventorytree import InventoryRevisionTree
52
from ..bzr.testament import (
62
from bzrlib.tsort import (
55
from ..tree import InterTree
65
from bzrlib.versionedfile import (
59
from ..bzr.versionedfile import (
66
60
ChunkedContentFactory,
69
from bzrlib.plugins.git.mapping import (
63
from .mapping import (
71
66
mode_is_executable,
75
from bzrlib.plugins.git.object_store import (
70
from .object_store import (
80
from bzrlib.plugins.git.remote import (
83
from bzrlib.plugins.git.repository import (
90
def import_git_blob(texts, mapping, path, name, (base_hexsha, hexsha),
91
base_inv, parent_id, revision_id,
92
parent_invs, lookup_object, (base_mode, mode), store_updater,
76
def import_git_blob(texts, mapping, path, name, hexshas,
77
base_bzr_tree, parent_id, revision_id,
78
parent_bzr_trees, lookup_object, modes, store_updater,
94
80
"""Import a git blob object into a bzr repository.
96
82
:param texts: VersionedFiles to add to
98
84
:param blob: A git blob
99
85
:return: Inventory delta for this file
101
if mapping.is_control_file(path):
87
if not isinstance(path, bytes):
89
decoded_path = decode_git_path(path)
90
(base_mode, mode) = modes
91
(base_hexsha, hexsha) = hexshas
92
if mapping.is_special_file(path):
103
94
if base_hexsha == hexsha and base_mode == mode:
104
95
# If nothing has changed since the base revision, we're done
106
file_id = lookup_file_id(path)
97
file_id = lookup_file_id(decoded_path)
107
98
if stat.S_ISLNK(mode):
108
99
cls = InventoryLink
110
101
cls = InventoryFile
111
ie = cls(file_id, name.decode("utf-8"), parent_id)
102
ie = cls(file_id, decode_git_path(name), parent_id)
112
103
if ie.kind == "file":
113
104
ie.executable = mode_is_executable(mode)
114
105
if base_hexsha == hexsha and mode_kind(base_mode) == mode_kind(mode):
115
base_ie = base_inv[base_inv.path2id(path)]
116
ie.text_size = base_ie.text_size
117
ie.text_sha1 = base_ie.text_sha1
106
base_exec = base_bzr_tree.is_executable(decoded_path)
118
107
if ie.kind == "symlink":
119
ie.symlink_target = base_ie.symlink_target
120
if ie.executable == base_ie.executable:
121
ie.revision = base_ie.revision
108
ie.symlink_target = base_bzr_tree.get_symlink_target(decoded_path)
110
ie.text_size = base_bzr_tree.get_file_size(decoded_path)
111
ie.text_sha1 = base_bzr_tree.get_file_sha1(decoded_path)
112
if ie.kind == "symlink" or ie.executable == base_exec:
113
ie.revision = base_bzr_tree.get_file_revision(decoded_path)
123
115
blob = lookup_object(hexsha)
125
117
blob = lookup_object(hexsha)
126
118
if ie.kind == "symlink":
127
119
ie.revision = None
128
ie.symlink_target = blob.data
120
ie.symlink_target = decode_git_path(blob.data)
130
ie.text_size = sum(imap(len, blob.chunked))
122
ie.text_size = sum(map(len, blob.chunked))
131
123
ie.text_sha1 = osutils.sha_strings(blob.chunked)
132
124
# Check what revision we should store
134
for pinv in parent_invs:
126
for ptree in parent_bzr_trees:
127
intertree = InterTree.get(ptree, base_bzr_tree)
139
if (pie.text_sha1 == ie.text_sha1 and
140
pie.executable == ie.executable and
141
pie.symlink_target == ie.symlink_target):
129
ppath = intertree.find_source_paths(decoded_path, recurse='none')
130
except errors.NoSuchFile:
134
pkind = ptree.kind(ppath)
135
if (pkind == ie.kind and
136
((pkind == "symlink" and ptree.get_symlink_target(ppath) == ie.symlink_target) or
137
(pkind == "file" and ptree.get_file_sha1(ppath) == ie.text_sha1 and
138
ptree.is_executable(ppath) == ie.executable))):
142
139
# found a revision in one of the parents to use
143
ie.revision = pie.revision
140
ie.revision = ptree.get_file_revision(ppath)
145
parent_key = (file_id, pie.revision)
146
if not parent_key in parent_keys:
142
parent_key = (file_id, ptree.get_file_revision(ppath))
143
if parent_key not in parent_keys:
147
144
parent_keys.append(parent_key)
148
145
if ie.revision is None:
149
146
# Need to store a new revision
150
147
ie.revision = revision_id
151
assert ie.revision is not None
148
if ie.revision is None:
149
raise ValueError("no file revision set")
152
150
if ie.kind == 'symlink':
155
153
chunks = blob.chunked
156
154
texts.insert_record_stream([
157
155
ChunkedContentFactory((file_id, ie.revision),
158
tuple(parent_keys), ie.text_sha1, chunks)])
156
tuple(parent_keys), ie.text_sha1, chunks)])
160
158
if base_hexsha is not None:
161
old_path = path.decode("utf-8") # Renames are not supported yet
159
old_path = decoded_path # Renames are not supported yet
162
160
if stat.S_ISDIR(base_mode):
163
invdelta.extend(remove_disappeared_children(base_inv, old_path,
164
lookup_object(base_hexsha), [], lookup_object))
161
invdelta.extend(remove_disappeared_children(
162
base_bzr_tree, old_path, lookup_object(base_hexsha), [],
167
new_path = path.decode("utf-8")
168
invdelta.append((old_path, new_path, file_id, ie))
166
invdelta.append((old_path, decoded_path, file_id, ie))
169
167
if base_hexsha != hexsha:
170
store_updater.add_object(blob, ie, path)
168
store_updater.add_object(blob, (ie.file_id, ie.revision), path)
174
172
class SubmodulesRequireSubtrees(BzrError):
175
_fmt = """The repository you are fetching from contains submodules. To continue, upgrade your Bazaar repository to a format that supports nested trees, such as 'development-subtree'."""
173
_fmt = ("The repository you are fetching from contains submodules, "
174
"which require a Bazaar format that supports tree references.")
179
def import_git_submodule(texts, mapping, path, name, (base_hexsha, hexsha),
180
base_inv, parent_id, revision_id, parent_invs, lookup_object,
181
(base_mode, mode), store_updater, lookup_file_id):
178
def import_git_submodule(texts, mapping, path, name, hexshas,
179
base_bzr_tree, parent_id, revision_id,
180
parent_bzr_trees, lookup_object,
181
modes, store_updater, lookup_file_id):
182
"""Import a git submodule."""
183
(base_hexsha, hexsha) = hexshas
184
(base_mode, mode) = modes
182
185
if base_hexsha == hexsha and base_mode == mode:
187
path = decode_git_path(path)
184
188
file_id = lookup_file_id(path)
185
ie = TreeReference(file_id, name.decode("utf-8"), parent_id)
190
ie = TreeReference(file_id, decode_git_path(name), parent_id)
186
191
ie.revision = revision_id
187
if base_hexsha is None:
192
if base_hexsha is not None:
193
old_path = path # Renames are not supported yet
194
if stat.S_ISDIR(base_mode):
195
invdelta.extend(remove_disappeared_children(
196
base_bzr_tree, old_path, lookup_object(base_hexsha), [],
191
200
ie.reference_revision = mapping.revision_id_foreign_to_bzr(hexsha)
192
201
texts.insert_record_stream([
193
202
ChunkedContentFactory((file_id, ie.revision), (), None, [])])
194
invdelta = [(oldpath, path, file_id, ie)]
203
invdelta.append((old_path, path, file_id, ie))
195
204
return invdelta, {}
198
def remove_disappeared_children(base_inv, path, base_tree, existing_children,
207
def remove_disappeared_children(base_bzr_tree, path, base_tree,
208
existing_children, lookup_object):
200
209
"""Generate an inventory delta for removed children.
202
:param base_inv: Base inventory against which to generate the
211
:param base_bzr_tree: Base bzr tree against which to generate the
204
213
:param path: Path to process (unicode)
205
214
:param base_tree: Git Tree base object
207
216
:param lookup_object: Lookup a git object by its SHA1
208
217
:return: Inventory delta, as list
210
assert type(path) is unicode
219
if not isinstance(path, str):
220
raise TypeError(path)
212
222
for name, mode, hexsha in base_tree.iteritems():
213
223
if name in existing_children:
215
c_path = posixpath.join(path, name.decode("utf-8"))
216
file_id = base_inv.path2id(c_path)
217
assert file_id is not None
225
c_path = posixpath.join(path, decode_git_path(name))
226
file_id = base_bzr_tree.path2id(c_path)
228
raise TypeError(file_id)
218
229
ret.append((c_path, None, file_id, None))
219
230
if stat.S_ISDIR(mode):
220
231
ret.extend(remove_disappeared_children(
221
base_inv, c_path, lookup_object(hexsha), [], lookup_object))
232
base_bzr_tree, c_path, lookup_object(hexsha), [],
225
def import_git_tree(texts, mapping, path, name, (base_hexsha, hexsha),
226
base_inv, parent_id, revision_id, parent_invs,
227
lookup_object, (base_mode, mode), store_updater,
228
lookup_file_id, allow_submodules=False):
237
def import_git_tree(texts, mapping, path, name, hexshas,
238
base_bzr_tree, parent_id, revision_id, parent_bzr_trees,
239
lookup_object, modes, store_updater,
240
lookup_file_id, allow_submodules=False):
229
241
"""Import a git tree object into a bzr repository.
231
243
:param texts: VersionedFiles object to add to
232
244
:param path: Path in the tree (str)
233
245
:param name: Name of the tree (str)
234
246
:param tree: A git tree object
235
:param base_inv: Base inventory against which to return inventory delta
247
:param base_bzr_tree: Base inventory against which to return inventory
236
249
:return: Inventory delta for this subtree
238
assert type(path) is str
239
assert type(name) is str
251
(base_hexsha, hexsha) = hexshas
252
(base_mode, mode) = modes
253
if not isinstance(path, bytes):
254
raise TypeError(path)
255
if not isinstance(name, bytes):
256
raise TypeError(name)
240
257
if base_hexsha == hexsha and base_mode == mode:
241
258
# If nothing has changed since the base revision, we're done
244
file_id = lookup_file_id(path)
245
# We just have to hope this is indeed utf-8:
246
ie = InventoryDirectory(file_id, name.decode("utf-8"), parent_id)
261
file_id = lookup_file_id(osutils.safe_unicode(path))
262
ie = InventoryDirectory(file_id, decode_git_path(name), parent_id)
247
263
tree = lookup_object(hexsha)
248
264
if base_hexsha is None:
250
old_path = None # Newly appeared here
266
old_path = None # Newly appeared here
252
268
base_tree = lookup_object(base_hexsha)
253
old_path = path.decode("utf-8") # Renames aren't supported yet
254
new_path = path.decode("utf-8")
269
old_path = decode_git_path(path) # Renames aren't supported yet
270
new_path = decode_git_path(path)
255
271
if base_tree is None or type(base_tree) is not Tree:
256
272
ie.revision = revision_id
257
273
invdelta.append((old_path, new_path, ie.file_id, ie))
273
289
child_base_hexsha = None
274
290
child_base_mode = 0
275
291
if stat.S_ISDIR(child_mode):
276
subinvdelta, grandchildmodes = import_git_tree(texts, mapping,
277
child_path, name, (child_base_hexsha, child_hexsha), base_inv,
278
file_id, revision_id, parent_invs, lookup_object,
292
subinvdelta, grandchildmodes = import_git_tree(
293
texts, mapping, child_path, name,
294
(child_base_hexsha, child_hexsha), base_bzr_tree, file_id,
295
revision_id, parent_bzr_trees, lookup_object,
279
296
(child_base_mode, child_mode), store_updater, lookup_file_id,
280
297
allow_submodules=allow_submodules)
281
elif S_ISGITLINK(child_mode): # submodule
298
elif S_ISGITLINK(child_mode): # submodule
282
299
if not allow_submodules:
283
300
raise SubmodulesRequireSubtrees()
284
subinvdelta, grandchildmodes = import_git_submodule(texts, mapping,
285
child_path, name, (child_base_hexsha, child_hexsha), base_inv,
286
file_id, revision_id, parent_invs, lookup_object,
287
(child_base_mode, child_mode), store_updater, lookup_file_id)
301
subinvdelta, grandchildmodes = import_git_submodule(
302
texts, mapping, child_path, name,
303
(child_base_hexsha, child_hexsha),
304
base_bzr_tree, file_id, revision_id, parent_bzr_trees,
305
lookup_object, (child_base_mode, child_mode), store_updater,
289
subinvdelta = import_git_blob(texts, mapping, child_path, name,
290
(child_base_hexsha, child_hexsha), base_inv, file_id,
291
revision_id, parent_invs, lookup_object,
292
(child_base_mode, child_mode), store_updater, lookup_file_id)
308
if not mapping.is_special_file(name):
309
subinvdelta = import_git_blob(
310
texts, mapping, child_path, name,
311
(child_base_hexsha, child_hexsha), base_bzr_tree, file_id,
312
revision_id, parent_bzr_trees, lookup_object,
313
(child_base_mode, child_mode), store_updater,
293
317
grandchildmodes = {}
294
318
child_modes.update(grandchildmodes)
295
319
invdelta.extend(subinvdelta)
296
320
if child_mode not in (stat.S_IFDIR, DEFAULT_FILE_MODE,
297
stat.S_IFLNK, DEFAULT_FILE_MODE|0111):
321
stat.S_IFLNK, DEFAULT_FILE_MODE | 0o111,
298
323
child_modes[child_path] = child_mode
299
324
# Remove any children that have disappeared
300
325
if base_tree is not None and type(base_tree) is Tree:
301
invdelta.extend(remove_disappeared_children(base_inv, old_path,
302
base_tree, existing_children, lookup_object))
303
store_updater.add_object(tree, ie, path)
326
invdelta.extend(remove_disappeared_children(
327
base_bzr_tree, old_path, base_tree, existing_children,
329
store_updater.add_object(tree, (file_id, revision_id), path)
304
330
return invdelta, child_modes
307
333
def verify_commit_reconstruction(target_git_object_retriever, lookup_object,
308
o, rev, ret_tree, parent_trees, mapping, unusual_modes):
334
o, rev, ret_tree, parent_trees, mapping,
335
unusual_modes, verifiers):
309
336
new_unusual_modes = mapping.export_unusual_file_modes(rev)
310
337
if new_unusual_modes != unusual_modes:
311
338
raise AssertionError("unusual modes don't match: %r != %r" % (
312
339
unusual_modes, new_unusual_modes))
313
340
# Verify that we can reconstruct the commit properly
314
rec_o = target_git_object_retriever._reconstruct_commit(rev, o.tree, True)
341
rec_o = target_git_object_retriever._reconstruct_commit(rev, o.tree, True,
316
344
raise AssertionError("Reconstructed commit differs: %r != %r" % (
320
for path, obj, ie in _tree_to_objects(ret_tree, parent_trees,
321
target_git_object_retriever._cache.idmap, unusual_modes, mapping.BZR_DUMMY_FILE):
348
for path, obj, ie in _tree_to_objects(
349
ret_tree, parent_trees, target_git_object_retriever._cache.idmap,
350
unusual_modes, mapping.BZR_DUMMY_FILE):
322
351
old_obj_id = tree_lookup_path(lookup_object, o.tree, path)[1]
323
352
new_objs[path] = obj
324
353
if obj.id != old_obj_id:
325
354
diff.append((path, lookup_object(old_obj_id), obj))
326
355
for (path, old_obj, new_obj) in diff:
327
while (old_obj.type_name == "tree" and
328
new_obj.type_name == "tree" and
329
sorted(old_obj) == sorted(new_obj)):
356
while (old_obj.type_name == "tree"
357
and new_obj.type_name == "tree"
358
and sorted(old_obj) == sorted(new_obj)):
330
359
for name in old_obj:
331
360
if old_obj[name][0] != new_obj[name][0]:
332
raise AssertionError("Modes for %s differ: %o != %o" %
361
raise AssertionError(
362
"Modes for %s differ: %o != %o" %
333
363
(path, old_obj[name][0], new_obj[name][0]))
334
364
if old_obj[name][1] != new_obj[name][1]:
335
365
# Found a differing child, delve deeper
337
367
old_obj = lookup_object(old_obj[name][1])
338
368
new_obj = new_objs[path]
340
raise AssertionError("objects differ for %s: %r != %r" % (path,
370
raise AssertionError(
371
"objects differ for %s: %r != %r" % (path, old_obj, new_obj))
374
def ensure_inventories_in_repo(repo, trees):
375
real_inv_vf = repo.inventories.without_fallbacks()
377
revid = t.get_revision_id()
378
if not real_inv_vf.get_parent_map([(revid, )]):
379
repo.add_inventory(revid, t.root_inventory, t.get_parent_ids())
344
382
def import_git_commit(repo, mapping, head, lookup_object,
345
target_git_object_retriever, trees_cache):
383
target_git_object_retriever, trees_cache, strict):
346
384
o = lookup_object(head)
347
rev, roundtrip_revid, verifiers = mapping.import_commit(o,
348
lambda x: target_git_object_retriever.lookup_git_sha(x)[1][0])
385
# Note that this uses mapping.revision_id_foreign_to_bzr. If the parents
386
# were bzr roundtripped revisions they would be specified in the
388
rev, roundtrip_revid, verifiers = mapping.import_commit(
389
o, mapping.revision_id_foreign_to_bzr, strict)
390
if roundtrip_revid is not None:
391
original_revid = rev.revision_id
392
rev.revision_id = roundtrip_revid
349
393
# We have to do this here, since we have to walk the tree and
350
394
# we need to make sure to import the blobs / trees with the right
351
395
# path; this may involve adding them more than once.
352
396
parent_trees = trees_cache.revision_trees(rev.parent_ids)
397
ensure_inventories_in_repo(repo, parent_trees)
353
398
if parent_trees == []:
354
base_inv = Inventory(root_id=None)
399
base_bzr_tree = trees_cache.revision_tree(NULL_REVISION)
358
base_inv = parent_trees[0].inventory
403
base_bzr_tree = parent_trees[0]
359
404
base_tree = lookup_object(o.parents[0]).tree
360
405
base_mode = stat.S_IFDIR
361
406
store_updater = target_git_object_retriever._get_updater(rev)
362
fileid_map = mapping.get_fileid_map(lookup_object, o.tree)
363
inv_delta, unusual_modes = import_git_tree(repo.texts,
364
mapping, "", "", (base_tree, o.tree), base_inv,
365
None, rev.revision_id, [p.inventory for p in parent_trees],
366
lookup_object, (base_mode, stat.S_IFDIR), store_updater,
367
fileid_map.lookup_file_id,
368
allow_submodules=getattr(repo._format, "supports_tree_reference", False))
407
inv_delta, unusual_modes = import_git_tree(
408
repo.texts, mapping, b"", b"", (base_tree, o.tree), base_bzr_tree,
409
None, rev.revision_id, parent_trees, lookup_object,
410
(base_mode, stat.S_IFDIR), store_updater,
411
mapping.generate_file_id,
412
allow_submodules=repo._format.supports_tree_reference)
369
413
if unusual_modes != {}:
370
414
for path, mode in unusual_modes.iteritems():
371
415
warn_unusual_mode(rev.foreign_revid, path, mode)
374
418
basis_id = rev.parent_ids[0]
375
419
except IndexError:
376
420
basis_id = NULL_REVISION
378
rev.inventory_sha1, inv = repo.add_inventory_by_delta(basis_id,
379
inv_delta, rev.revision_id, rev.parent_ids, base_inv)
380
# FIXME: Check verifiers
381
testament = StrictTestament3(rev, inv)
382
calculated_verifiers = { "testament3-sha1": testament.as_sha1() }
383
if roundtrip_revid is not None:
384
original_revid = rev.revision_id
385
rev.revision_id = roundtrip_revid
421
base_bzr_inventory = None
423
base_bzr_inventory = base_bzr_tree.root_inventory
424
rev.inventory_sha1, inv = repo.add_inventory_by_delta(
425
basis_id, inv_delta, rev.revision_id, rev.parent_ids,
427
ret_tree = InventoryRevisionTree(repo, inv, rev.revision_id)
429
if verifiers and roundtrip_revid is not None:
430
testament = StrictTestament3(rev, ret_tree)
431
calculated_verifiers = {"testament3-sha1": testament.as_sha1()}
386
432
if calculated_verifiers != verifiers:
387
433
trace.mutter("Testament SHA1 %r for %r did not match %r.",
388
434
calculated_verifiers["testament3-sha1"],
389
435
rev.revision_id, verifiers["testament3-sha1"])
390
436
rev.revision_id = original_revid
437
rev.inventory_sha1, inv = repo.add_inventory_by_delta(
438
basis_id, inv_delta, rev.revision_id, rev.parent_ids,
440
ret_tree = InventoryRevisionTree(repo, inv, rev.revision_id)
442
calculated_verifiers = {}
391
443
store_updater.add_object(o, calculated_verifiers, None)
392
444
store_updater.finish()
393
ret_tree = RevisionTree(repo, inv, rev.revision_id)
394
445
trees_cache.add(ret_tree)
395
446
repo.add_revision(rev.revision_id, rev)
396
447
if "verify" in debug.debug_flags:
397
verify_commit_reconstruction(target_git_object_retriever,
398
lookup_object, o, rev, ret_tree, parent_trees, mapping,
448
verify_commit_reconstruction(
449
target_git_object_retriever, lookup_object, o, rev, ret_tree,
450
parent_trees, mapping, unusual_modes, verifiers)
402
453
def import_git_objects(repo, mapping, object_iter,
403
target_git_object_retriever, heads, pb=None, limit=None):
454
target_git_object_retriever, heads, pb=None,
404
456
"""Import a set of git objects into a bzr repository.
406
458
:param repo: Target Bazaar repository
478
535
return pack_hints, last_imported
481
class InterGitRepository(InterRepository):
483
_matching_repo_format = GitRepositoryFormat()
486
def _get_repo_format_to_test():
489
def copy_content(self, revision_id=None, pb=None):
490
"""See InterRepository.copy_content."""
491
self.fetch(revision_id, pb, find_ghosts=False)
494
class InterGitNonGitRepository(InterGitRepository):
495
"""Base InterRepository that copies revisions from a Git into a non-Git
498
def fetch_objects(self, determine_wants, mapping, pb=None, limit=None):
499
"""Fetch objects from a remote server.
501
:param determine_wants: determine_wants callback
502
:param mapping: BzrGitMapping to use
503
:param pb: Optional progress bar
504
:param limit: Maximum number of commits to import.
505
:return: Tuple with pack hint, last imported revision id and remote refs
507
raise NotImplementedError(self.fetch_objects)
509
def fetch(self, revision_id=None, pb=None, find_ghosts=False,
510
mapping=None, fetch_spec=None):
512
mapping = self.source.get_mapping()
513
if revision_id is not None:
514
interesting_heads = [revision_id]
515
elif fetch_spec is not None:
516
interesting_heads = fetch_spec.heads
518
interesting_heads = None
519
def determine_wants(refs):
520
if interesting_heads is None:
521
ret = [sha for (ref, sha) in refs.iteritems() if not ref.endswith("^{}")]
523
ret = [self.source.lookup_bzr_revision_id(revid)[0] for revid in interesting_heads if revid not in (None, NULL_REVISION)]
524
return [rev for rev in ret if not self.target.has_revision(self.source.lookup_foreign_revision_id(rev))]
525
(pack_hint, _, remote_refs) = self.fetch_objects(determine_wants, mapping, pb)
526
if pack_hint is not None and self.target._format.pack_compresses:
527
self.target.pack(hint=pack_hint)
531
_GIT_PROGRESS_RE = re.compile(r"(.*?): +(\d+)% \((\d+)/(\d+)\)")
532
def report_git_progress(pb, text):
533
text = text.rstrip("\r\n")
534
g = _GIT_PROGRESS_RE.match(text)
536
(text, pct, current, total) = g.groups()
537
pb.update(text, int(current), int(total))
539
pb.update(text, 0, 0)
542
538
class DetermineWantsRecorder(object):
544
540
def __init__(self, actual):
547
543
self.remote_refs = {}
549
545
def __call__(self, refs):
546
if type(refs) is not dict:
547
raise TypeError(refs)
550
548
self.remote_refs = refs
551
549
self.wants = self.actual(refs)
552
550
return self.wants
555
class InterRemoteGitNonGitRepository(InterGitNonGitRepository):
556
"""InterRepository that copies revisions from a remote Git into a non-Git
559
def get_target_heads(self):
560
# FIXME: This should be more efficient
561
all_revs = self.target.all_revision_ids()
562
parent_map = self.target.get_parent_map(all_revs)
564
map(all_parents.update, parent_map.itervalues())
565
return set(all_revs) - all_parents
567
def fetch_objects(self, determine_wants, mapping, pb=None, limit=None):
568
"""See `InterGitNonGitRepository`."""
570
report_git_progress(pb, text)
571
store = BazaarObjectStore(self.target, mapping)
572
self.target.lock_write()
574
heads = self.get_target_heads()
575
graph_walker = store.get_graph_walker(
576
[store._lookup_revision_sha1(head) for head in heads])
577
wants_recorder = DetermineWantsRecorder(determine_wants)
581
create_pb = pb = ui.ui_factory.nested_progress_bar()
583
objects_iter = self.source.fetch_objects(
584
wants_recorder, graph_walker, store.get_raw,
586
(pack_hint, last_rev) = import_git_objects(self.target, mapping,
587
objects_iter, store, wants_recorder.wants, pb, limit)
588
return (pack_hint, last_rev, wants_recorder.remote_refs)
596
def is_compatible(source, target):
597
"""Be compatible with GitRepository."""
598
return (isinstance(source, RemoteGitRepository) and
599
target.supports_rich_root() and
600
not isinstance(target, GitRepository) and
601
target.texts is not None)
604
class InterLocalGitNonGitRepository(InterGitNonGitRepository):
605
"""InterRepository that copies revisions from a local Git into a non-Git
608
def fetch_objects(self, determine_wants, mapping, pb=None, limit=None):
609
"""See `InterGitNonGitRepository`."""
610
remote_refs = self.source._git.get_refs()
611
wants = determine_wants(remote_refs)
614
create_pb = pb = ui.ui_factory.nested_progress_bar()
615
target_git_object_retriever = BazaarObjectStore(self.target, mapping)
617
self.target.lock_write()
619
(pack_hint, last_rev) = import_git_objects(self.target, mapping,
620
self.source._git.object_store,
621
target_git_object_retriever, wants, pb, limit)
622
return (pack_hint, last_rev, remote_refs)
630
def is_compatible(source, target):
631
"""Be compatible with GitRepository."""
632
return (isinstance(source, LocalGitRepository) and
633
target.supports_rich_root() and
634
not isinstance(target, GitRepository) and
635
target.texts is not None)
638
class InterGitGitRepository(InterGitRepository):
639
"""InterRepository that copies between Git repositories."""
641
def fetch_objects(self, determine_wants, mapping, pb=None):
643
trace.note("git: %s", text)
644
graphwalker = self.target._git.get_graph_walker()
645
if (isinstance(self.source, LocalGitRepository) and
646
isinstance(self.target, LocalGitRepository)):
647
refs = self.source._git.fetch(self.target._git, determine_wants,
649
return (None, None, refs)
650
elif (isinstance(self.source, LocalGitRepository) and
651
isinstance(self.target, RemoteGitRepository)):
652
raise NotImplementedError
653
elif (isinstance(self.source, RemoteGitRepository) and
654
isinstance(self.target, LocalGitRepository)):
655
f, commit = self.target._git.object_store.add_thin_pack()
657
refs = self.source.bzrdir.root_transport.fetch_pack(
658
determine_wants, graphwalker, f.write, progress)
660
return (None, None, refs)
667
def fetch(self, revision_id=None, pb=None, find_ghosts=False,
668
mapping=None, fetch_spec=None, branches=None):
670
mapping = self.source.get_mapping()
672
if revision_id is not None:
673
args = [mapping.revision_id_bzr_to_foreign(revision_id)[0]]
674
elif fetch_spec is not None:
675
args = [mapping.revision_id_bzr_to_foreign(revid)[0] for revid in fetch_spec.heads]
676
if branches is not None:
677
determine_wants = lambda x: [x[y] for y in branches if not x[y] in r.object_store]
678
elif fetch_spec is None and revision_id is None:
679
determine_wants = r.object_store.determine_wants_all
681
determine_wants = lambda x: [y for y in args if not y in r.object_store]
682
self.fetch_objects(determine_wants, mapping)
685
def is_compatible(source, target):
686
"""Be compatible with GitRepository."""
687
return (isinstance(source, GitRepository) and
688
isinstance(target, GitRepository))