object_store.py 24 KB

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