object_store.py 26 KB

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