object_store.py 24 KB

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