object_store.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  1. # object_store.py -- Object store for git objects
  2. # Copyright (C) 2008-2009 Jelmer Vernooij <jelmer@samba.org>
  3. #
  4. # This program is free software; you can redistribute it and/or
  5. # modify it under the terms of the GNU General Public License
  6. # as published by the Free Software Foundation; either version 2
  7. # or (at your option) a later version of the License.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program; if not, write to the Free Software
  16. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  17. # MA 02110-1301, USA.
  18. """Git object store interfaces and implementation."""
  19. import errno
  20. import itertools
  21. import os
  22. import posixpath
  23. import stat
  24. import tempfile
  25. import urllib2
  26. from dulwich.errors import (
  27. NotTreeError,
  28. )
  29. from dulwich.file import GitFile
  30. from dulwich.objects import (
  31. Commit,
  32. ShaFile,
  33. Tag,
  34. Tree,
  35. hex_to_sha,
  36. sha_to_hex,
  37. hex_to_filename,
  38. S_ISGITLINK,
  39. )
  40. from dulwich.pack import (
  41. Pack,
  42. PackData,
  43. ThinPackData,
  44. iter_sha1,
  45. load_pack_index,
  46. write_pack,
  47. write_pack_data,
  48. write_pack_index_v2,
  49. )
  50. INFODIR = 'info'
  51. PACKDIR = 'pack'
  52. class BaseObjectStore(object):
  53. """Object store interface."""
  54. def determine_wants_all(self, refs):
  55. return [sha for (ref, sha) in refs.iteritems()
  56. if not sha in self and not ref.endswith("^{}")]
  57. def iter_shas(self, shas):
  58. """Iterate over the objects for the specified shas.
  59. :param shas: Iterable object with SHAs
  60. :return: Object iterator
  61. """
  62. return ObjectStoreIterator(self, shas)
  63. def contains_loose(self, sha):
  64. """Check if a particular object is present by SHA1 and is loose."""
  65. raise NotImplementedError(self.contains_loose)
  66. def contains_packed(self, sha):
  67. """Check if a particular object is present by SHA1 and is packed."""
  68. raise NotImplementedError(self.contains_packed)
  69. def __contains__(self, sha):
  70. """Check if a particular object is present by SHA1.
  71. This method makes no distinction between loose and packed objects.
  72. """
  73. return self.contains_packed(sha) or self.contains_loose(sha)
  74. @property
  75. def packs(self):
  76. """Iterable of pack objects."""
  77. raise NotImplementedError
  78. def get_raw(self, name):
  79. """Obtain the raw text for an object.
  80. :param name: sha for the object.
  81. :return: tuple with numeric type and object contents.
  82. """
  83. raise NotImplementedError(self.get_raw)
  84. def __getitem__(self, sha):
  85. """Obtain an object by SHA1."""
  86. type_num, uncomp = self.get_raw(sha)
  87. return ShaFile.from_raw_string(type_num, uncomp)
  88. def __iter__(self):
  89. """Iterate over the SHAs that are present in this store."""
  90. raise NotImplementedError(self.__iter__)
  91. def add_object(self, obj):
  92. """Add a single object to this object store.
  93. """
  94. raise NotImplementedError(self.add_object)
  95. def add_objects(self, objects):
  96. """Add a set of objects to this object store.
  97. :param objects: Iterable over a list of objects.
  98. """
  99. raise NotImplementedError(self.add_objects)
  100. def tree_changes(self, source, target, want_unchanged=False):
  101. """Find the differences between the contents of two trees
  102. :param object_store: Object store to use for retrieving tree contents
  103. :param tree: SHA1 of the root tree
  104. :param want_unchanged: Whether unchanged files should be reported
  105. :return: Iterator over tuples with (oldpath, newpath), (oldmode, newmode), (oldsha, newsha)
  106. """
  107. todo = set([(source, target, "")])
  108. while todo:
  109. (sid, tid, path) = todo.pop()
  110. if sid is not None:
  111. stree = self[sid]
  112. else:
  113. stree = {}
  114. if tid is not None:
  115. ttree = self[tid]
  116. else:
  117. ttree = {}
  118. for name, oldmode, oldhexsha in stree.iteritems():
  119. oldchildpath = posixpath.join(path, name)
  120. try:
  121. (newmode, newhexsha) = ttree[name]
  122. newchildpath = oldchildpath
  123. except KeyError:
  124. newmode = None
  125. newhexsha = None
  126. newchildpath = None
  127. if (want_unchanged or oldmode != newmode or
  128. oldhexsha != newhexsha):
  129. if stat.S_ISDIR(oldmode):
  130. if newmode is None or stat.S_ISDIR(newmode):
  131. todo.add((oldhexsha, newhexsha, oldchildpath))
  132. else:
  133. # entry became a file
  134. todo.add((oldhexsha, None, oldchildpath))
  135. yield ((None, newchildpath), (None, newmode), (None, newhexsha))
  136. else:
  137. if newmode is not None and stat.S_ISDIR(newmode):
  138. # entry became a dir
  139. yield ((oldchildpath, None), (oldmode, None), (oldhexsha, None))
  140. todo.add((None, newhexsha, newchildpath))
  141. else:
  142. yield ((oldchildpath, newchildpath), (oldmode, newmode), (oldhexsha, newhexsha))
  143. for name, newmode, newhexsha in ttree.iteritems():
  144. childpath = posixpath.join(path, name)
  145. if not name in stree:
  146. if not stat.S_ISDIR(newmode):
  147. yield ((None, childpath), (None, newmode), (None, newhexsha))
  148. else:
  149. todo.add((None, newhexsha, childpath))
  150. def iter_tree_contents(self, tree_id, include_trees=False):
  151. """Iterate the contents of a tree and all subtrees.
  152. Iteration is depth-first pre-order, as in e.g. os.walk.
  153. :param tree_id: SHA1 of the tree.
  154. :param include_trees: If True, include tree objects in the iteration.
  155. :yield: Tuples of (path, mode, hexhsa) for objects in a tree.
  156. """
  157. todo = [('', stat.S_IFDIR, tree_id)]
  158. while todo:
  159. path, mode, hexsha = todo.pop()
  160. is_subtree = stat.S_ISDIR(mode)
  161. if not is_subtree or include_trees:
  162. yield path, mode, hexsha
  163. if is_subtree:
  164. entries = reversed(list(self[hexsha].iteritems()))
  165. for name, entry_mode, entry_hexsha in entries:
  166. entry_path = posixpath.join(path, name)
  167. todo.append((entry_path, entry_mode, entry_hexsha))
  168. def find_missing_objects(self, haves, wants, progress=None,
  169. get_tagged=None):
  170. """Find the missing objects required for a set of revisions.
  171. :param haves: Iterable over SHAs already in common.
  172. :param wants: Iterable over SHAs of objects to fetch.
  173. :param progress: Simple progress function that will be called with
  174. updated progress strings.
  175. :param get_tagged: Function that returns a dict of pointed-to sha -> tag
  176. sha for including tags.
  177. :return: Iterator over (sha, path) pairs.
  178. """
  179. finder = MissingObjectFinder(self, haves, wants, progress, get_tagged)
  180. return iter(finder.next, None)
  181. def find_common_revisions(self, graphwalker):
  182. """Find which revisions this store has in common using graphwalker.
  183. :param graphwalker: A graphwalker object.
  184. :return: List of SHAs that are in common
  185. """
  186. haves = []
  187. sha = graphwalker.next()
  188. while sha:
  189. if sha in self:
  190. haves.append(sha)
  191. graphwalker.ack(sha)
  192. sha = graphwalker.next()
  193. return haves
  194. def get_graph_walker(self, heads):
  195. """Obtain a graph walker for this object store.
  196. :param heads: Local heads to start search with
  197. :return: GraphWalker object
  198. """
  199. return ObjectStoreGraphWalker(heads, lambda sha: self[sha].parents)
  200. def generate_pack_contents(self, have, want, progress=None):
  201. """Iterate over the contents of a pack file.
  202. :param have: List of SHA1s of objects that should not be sent
  203. :param want: List of SHA1s of objects that should be sent
  204. :param progress: Optional progress reporting method
  205. """
  206. return self.iter_shas(self.find_missing_objects(have, want, progress))
  207. class PackBasedObjectStore(BaseObjectStore):
  208. def __init__(self):
  209. self._pack_cache = None
  210. def contains_packed(self, sha):
  211. """Check if a particular object is present by SHA1 and is packed."""
  212. for pack in self.packs:
  213. if sha in pack:
  214. return True
  215. return False
  216. def _load_packs(self):
  217. raise NotImplementedError(self._load_packs)
  218. def _pack_cache_stale(self):
  219. """Check whether the pack cache is stale."""
  220. raise NotImplementedError(self._pack_cache_stale)
  221. def _add_known_pack(self, pack):
  222. """Add a newly appeared pack to the cache by path.
  223. """
  224. if self._pack_cache is not None:
  225. self._pack_cache.append(pack)
  226. @property
  227. def packs(self):
  228. """List with pack objects."""
  229. if self._pack_cache is None or self._pack_cache_stale():
  230. self._pack_cache = self._load_packs()
  231. return self._pack_cache
  232. def _iter_loose_objects(self):
  233. """Iterate over the SHAs of all loose objects."""
  234. raise NotImplementedError(self._iter_loose_objects)
  235. def _get_loose_object(self, sha):
  236. raise NotImplementedError(self._get_loose_object)
  237. def _remove_loose_object(self, sha):
  238. raise NotImplementedError(self._remove_loose_object)
  239. def pack_loose_objects(self):
  240. """Pack loose objects.
  241. :return: Number of objects packed
  242. """
  243. objects = set()
  244. for sha in self._iter_loose_objects():
  245. objects.add((self._get_loose_object(sha), None))
  246. self.add_objects(objects)
  247. for obj, path in objects:
  248. self._remove_loose_object(obj.id)
  249. return len(objects)
  250. def __iter__(self):
  251. """Iterate over the SHAs that are present in this store."""
  252. iterables = self.packs + [self._iter_loose_objects()]
  253. return itertools.chain(*iterables)
  254. def contains_loose(self, sha):
  255. """Check if a particular object is present by SHA1 and is loose."""
  256. return self._get_loose_object(sha) is not None
  257. def get_raw(self, name):
  258. """Obtain the raw text for an object.
  259. :param name: sha for the object.
  260. :return: tuple with numeric type and object contents.
  261. """
  262. if len(name) == 40:
  263. sha = hex_to_sha(name)
  264. hexsha = name
  265. elif len(name) == 20:
  266. sha = name
  267. hexsha = None
  268. else:
  269. raise AssertionError
  270. for pack in self.packs:
  271. try:
  272. return pack.get_raw(sha)
  273. except KeyError:
  274. pass
  275. if hexsha is None:
  276. hexsha = sha_to_hex(name)
  277. ret = self._get_loose_object(hexsha)
  278. if ret is not None:
  279. return ret.type_num, ret.as_raw_string()
  280. raise KeyError(hexsha)
  281. def add_objects(self, objects):
  282. """Add a set of objects to this object store.
  283. :param objects: Iterable over objects, should support __len__.
  284. :return: Pack object of the objects written.
  285. """
  286. if len(objects) == 0:
  287. # Don't bother writing an empty pack file
  288. return
  289. f, commit = self.add_pack()
  290. write_pack_data(f, objects, len(objects))
  291. return commit()
  292. class DiskObjectStore(PackBasedObjectStore):
  293. """Git-style object store that exists on disk."""
  294. def __init__(self, path):
  295. """Open an object store.
  296. :param path: Path of the object store.
  297. """
  298. super(DiskObjectStore, self).__init__()
  299. self.path = path
  300. self.pack_dir = os.path.join(self.path, PACKDIR)
  301. self._pack_cache_time = 0
  302. def _load_packs(self):
  303. pack_files = []
  304. try:
  305. self._pack_cache_time = os.stat(self.pack_dir).st_mtime
  306. pack_dir_contents = os.listdir(self.pack_dir)
  307. for name in pack_dir_contents:
  308. # TODO: verify that idx exists first
  309. if name.startswith("pack-") and name.endswith(".pack"):
  310. filename = os.path.join(self.pack_dir, name)
  311. pack_files.append((os.stat(filename).st_mtime, filename))
  312. except OSError, e:
  313. if e.errno == errno.ENOENT:
  314. return []
  315. raise
  316. pack_files.sort(reverse=True)
  317. suffix_len = len(".pack")
  318. return [Pack(f[:-suffix_len]) for _, f in pack_files]
  319. def _pack_cache_stale(self):
  320. try:
  321. return os.stat(self.pack_dir).st_mtime > self._pack_cache_time
  322. except OSError, e:
  323. if e.errno == errno.ENOENT:
  324. return True
  325. raise
  326. def _get_shafile_path(self, sha):
  327. # Check from object dir
  328. return hex_to_filename(self.path, sha)
  329. def _iter_loose_objects(self):
  330. for base in os.listdir(self.path):
  331. if len(base) != 2:
  332. continue
  333. for rest in os.listdir(os.path.join(self.path, base)):
  334. yield base+rest
  335. def _get_loose_object(self, sha):
  336. path = self._get_shafile_path(sha)
  337. try:
  338. return ShaFile.from_path(path)
  339. except (OSError, IOError), e:
  340. if e.errno == errno.ENOENT:
  341. return None
  342. raise
  343. def _remove_loose_object(self, sha):
  344. os.remove(self._get_shafile_path(sha))
  345. def move_in_thin_pack(self, path):
  346. """Move a specific file containing a pack into the pack directory.
  347. :note: The file should be on the same file system as the
  348. packs directory.
  349. :param path: Path to the pack file.
  350. """
  351. data = ThinPackData(self.get_raw, path)
  352. # Write index for the thin pack (do we really need this?)
  353. temppath = os.path.join(self.pack_dir,
  354. sha_to_hex(urllib2.randombytes(20))+".tempidx")
  355. data.create_index_v2(temppath)
  356. p = Pack.from_objects(data, load_pack_index(temppath))
  357. # Write a full pack version
  358. temppath = os.path.join(self.pack_dir,
  359. sha_to_hex(urllib2.randombytes(20))+".temppack")
  360. write_pack(temppath, ((o, None) for o in p.iterobjects()), len(p))
  361. pack_sha = load_pack_index(temppath+".idx").objects_sha1()
  362. newbasename = os.path.join(self.pack_dir, "pack-%s" % pack_sha)
  363. os.rename(temppath+".pack", newbasename+".pack")
  364. os.rename(temppath+".idx", newbasename+".idx")
  365. final_pack = Pack(newbasename)
  366. self._add_known_pack(final_pack)
  367. return final_pack
  368. def move_in_pack(self, path):
  369. """Move a specific file containing a pack into the pack directory.
  370. :note: The file should be on the same file system as the
  371. packs directory.
  372. :param path: Path to the pack file.
  373. """
  374. p = PackData(path)
  375. entries = p.sorted_entries()
  376. basename = os.path.join(self.pack_dir,
  377. "pack-%s" % iter_sha1(entry[0] for entry in entries))
  378. f = GitFile(basename+".idx", "wb")
  379. try:
  380. write_pack_index_v2(f, entries, p.get_stored_checksum())
  381. finally:
  382. f.close()
  383. p.close()
  384. os.rename(path, basename + ".pack")
  385. final_pack = Pack(basename)
  386. self._add_known_pack(final_pack)
  387. return final_pack
  388. def add_thin_pack(self):
  389. """Add a new thin pack to this object store.
  390. Thin packs are packs that contain deltas with parents that exist
  391. in a different pack.
  392. """
  393. fd, path = tempfile.mkstemp(dir=self.pack_dir, suffix=".pack")
  394. f = os.fdopen(fd, 'wb')
  395. def commit():
  396. os.fsync(fd)
  397. f.close()
  398. if os.path.getsize(path) > 0:
  399. return self.move_in_thin_pack(path)
  400. else:
  401. return None
  402. return f, commit
  403. def add_pack(self):
  404. """Add a new pack to this object store.
  405. :return: Fileobject to write to and a commit function to
  406. call when the pack is finished.
  407. """
  408. fd, path = tempfile.mkstemp(dir=self.pack_dir, suffix=".pack")
  409. f = os.fdopen(fd, 'wb')
  410. def commit():
  411. os.fsync(fd)
  412. f.close()
  413. if os.path.getsize(path) > 0:
  414. return self.move_in_pack(path)
  415. else:
  416. return None
  417. return f, commit
  418. def add_object(self, obj):
  419. """Add a single object to this object store.
  420. :param obj: Object to add
  421. """
  422. dir = os.path.join(self.path, obj.id[:2])
  423. try:
  424. os.mkdir(dir)
  425. except OSError, e:
  426. if e.errno != errno.EEXIST:
  427. raise
  428. path = os.path.join(dir, obj.id[2:])
  429. if os.path.exists(path):
  430. return # Already there, no need to write again
  431. f = GitFile(path, 'wb')
  432. try:
  433. f.write(obj.as_legacy_object())
  434. finally:
  435. f.close()
  436. @classmethod
  437. def init(cls, path):
  438. try:
  439. os.mkdir(path)
  440. except OSError, e:
  441. if e.errno != errno.EEXIST:
  442. raise
  443. os.mkdir(os.path.join(path, "info"))
  444. os.mkdir(os.path.join(path, PACKDIR))
  445. return cls(path)
  446. class MemoryObjectStore(BaseObjectStore):
  447. """Object store that keeps all objects in memory."""
  448. def __init__(self):
  449. super(MemoryObjectStore, self).__init__()
  450. self._data = {}
  451. def contains_loose(self, sha):
  452. """Check if a particular object is present by SHA1 and is loose."""
  453. return sha in self._data
  454. def contains_packed(self, sha):
  455. """Check if a particular object is present by SHA1 and is packed."""
  456. return False
  457. def __iter__(self):
  458. """Iterate over the SHAs that are present in this store."""
  459. return self._data.iterkeys()
  460. @property
  461. def packs(self):
  462. """List with pack objects."""
  463. return []
  464. def get_raw(self, name):
  465. """Obtain the raw text for an object.
  466. :param name: sha for the object.
  467. :return: tuple with numeric type and object contents.
  468. """
  469. return self[name].as_raw_string()
  470. def __getitem__(self, name):
  471. return self._data[name]
  472. def add_object(self, obj):
  473. """Add a single object to this object store.
  474. """
  475. self._data[obj.id] = obj
  476. def add_objects(self, objects):
  477. """Add a set of objects to this object store.
  478. :param objects: Iterable over a list of objects.
  479. """
  480. for obj, path in objects:
  481. self._data[obj.id] = obj
  482. class ObjectImporter(object):
  483. """Interface for importing objects."""
  484. def __init__(self, count):
  485. """Create a new ObjectImporter.
  486. :param count: Number of objects that's going to be imported.
  487. """
  488. self.count = count
  489. def add_object(self, object):
  490. """Add an object."""
  491. raise NotImplementedError(self.add_object)
  492. def finish(self, object):
  493. """Finish the imoprt and write objects to disk."""
  494. raise NotImplementedError(self.finish)
  495. class ObjectIterator(object):
  496. """Interface for iterating over objects."""
  497. def iterobjects(self):
  498. raise NotImplementedError(self.iterobjects)
  499. class ObjectStoreIterator(ObjectIterator):
  500. """ObjectIterator that works on top of an ObjectStore."""
  501. def __init__(self, store, sha_iter):
  502. """Create a new ObjectIterator.
  503. :param store: Object store to retrieve from
  504. :param sha_iter: Iterator over (sha, path) tuples
  505. """
  506. self.store = store
  507. self.sha_iter = sha_iter
  508. self._shas = []
  509. def __iter__(self):
  510. """Yield tuple with next object and path."""
  511. for sha, path in self.itershas():
  512. yield self.store[sha], path
  513. def iterobjects(self):
  514. """Iterate over just the objects."""
  515. for o, path in self:
  516. yield o
  517. def itershas(self):
  518. """Iterate over the SHAs."""
  519. for sha in self._shas:
  520. yield sha
  521. for sha in self.sha_iter:
  522. self._shas.append(sha)
  523. yield sha
  524. def __contains__(self, needle):
  525. """Check if an object is present.
  526. :note: This checks if the object is present in
  527. the underlying object store, not if it would
  528. be yielded by the iterator.
  529. :param needle: SHA1 of the object to check for
  530. """
  531. return needle in self.store
  532. def __getitem__(self, key):
  533. """Find an object by SHA1.
  534. :note: This retrieves the object from the underlying
  535. object store. It will also succeed if the object would
  536. not be returned by the iterator.
  537. """
  538. return self.store[key]
  539. def __len__(self):
  540. """Return the number of objects."""
  541. return len(list(self.itershas()))
  542. def tree_lookup_path(lookup_obj, root_sha, path):
  543. """Lookup an object in a Git tree.
  544. :param lookup_obj: Callback for retrieving object by SHA1
  545. :param root_sha: SHA1 of the root tree
  546. :param path: Path to lookup
  547. """
  548. parts = path.split("/")
  549. sha = root_sha
  550. mode = None
  551. for p in parts:
  552. obj = lookup_obj(sha)
  553. if not isinstance(obj, Tree):
  554. raise NotTreeError(sha)
  555. if p == '':
  556. continue
  557. mode, sha = obj[p]
  558. return mode, sha
  559. class MissingObjectFinder(object):
  560. """Find the objects missing from another object store.
  561. :param object_store: Object store containing at least all objects to be
  562. sent
  563. :param haves: SHA1s of commits not to send (already present in target)
  564. :param wants: SHA1s of commits to send
  565. :param progress: Optional function to report progress to.
  566. :param get_tagged: Function that returns a dict of pointed-to sha -> tag
  567. sha for including tags.
  568. :param tagged: dict of pointed-to sha -> tag sha for including tags
  569. """
  570. def __init__(self, object_store, haves, wants, progress=None,
  571. get_tagged=None):
  572. self.sha_done = set(haves)
  573. self.objects_to_send = set([(w, None, False) for w in wants if w not in haves])
  574. self.object_store = object_store
  575. if progress is None:
  576. self.progress = lambda x: None
  577. else:
  578. self.progress = progress
  579. self._tagged = get_tagged and get_tagged() or {}
  580. def add_todo(self, entries):
  581. self.objects_to_send.update([e for e in entries if not e[0] in self.sha_done])
  582. def parse_tree(self, tree):
  583. self.add_todo([(sha, name, not stat.S_ISDIR(mode)) for (mode, name, sha) in tree.entries() if not S_ISGITLINK(mode)])
  584. def parse_commit(self, commit):
  585. self.add_todo([(commit.tree, "", False)])
  586. self.add_todo([(p, None, False) for p in commit.parents])
  587. def parse_tag(self, tag):
  588. self.add_todo([(tag.object[1], None, False)])
  589. def next(self):
  590. if not self.objects_to_send:
  591. return None
  592. (sha, name, leaf) = self.objects_to_send.pop()
  593. if not leaf:
  594. o = self.object_store[sha]
  595. if isinstance(o, Commit):
  596. self.parse_commit(o)
  597. elif isinstance(o, Tree):
  598. self.parse_tree(o)
  599. elif isinstance(o, Tag):
  600. self.parse_tag(o)
  601. if sha in self._tagged:
  602. self.add_todo([(self._tagged[sha], None, True)])
  603. self.sha_done.add(sha)
  604. self.progress("counting objects: %d\r" % len(self.sha_done))
  605. return (sha, name)
  606. class ObjectStoreGraphWalker(object):
  607. """Graph walker that finds what commits are missing from an object store.
  608. :ivar heads: Revisions without descendants in the local repo
  609. :ivar get_parents: Function to retrieve parents in the local repo
  610. """
  611. def __init__(self, local_heads, get_parents):
  612. """Create a new instance.
  613. :param local_heads: Heads to start search with
  614. :param get_parents: Function for finding the parents of a SHA1.
  615. """
  616. self.heads = set(local_heads)
  617. self.get_parents = get_parents
  618. self.parents = {}
  619. def ack(self, sha):
  620. """Ack that a revision and its ancestors are present in the source."""
  621. ancestors = set([sha])
  622. # stop if we run out of heads to remove
  623. while self.heads:
  624. for a in ancestors:
  625. if a in self.heads:
  626. self.heads.remove(a)
  627. # collect all ancestors
  628. new_ancestors = set()
  629. for a in ancestors:
  630. if a in self.parents:
  631. new_ancestors.update(self.parents[a])
  632. # no more ancestors; stop
  633. if not new_ancestors:
  634. break
  635. ancestors = new_ancestors
  636. def next(self):
  637. """Iterate over ancestors of heads in the target."""
  638. if self.heads:
  639. ret = self.heads.pop()
  640. ps = self.get_parents(ret)
  641. self.parents[ret] = ps
  642. self.heads.update(ps)
  643. return ret
  644. return None