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