object_store.py 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001
  1. # object_store.py -- Object store for git objects
  2. # Copyright (C) 2008-2012 Jelmer Vernooij <jelmer@samba.org>
  3. # and others
  4. #
  5. # This program is free software; you can redistribute it and/or
  6. # modify it under the terms of the GNU General Public License
  7. # as published by the Free Software Foundation; either version 2
  8. # or (at your option) a later version of the License.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program; if not, write to the Free Software
  17. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  18. # MA 02110-1301, USA.
  19. """Git object store interfaces and implementation."""
  20. import errno
  21. import itertools
  22. import os
  23. import stat
  24. import tempfile
  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. ZERO_SHA,
  39. hex_to_sha,
  40. sha_to_hex,
  41. hex_to_filename,
  42. S_ISGITLINK,
  43. object_class,
  44. )
  45. from dulwich.pack import (
  46. Pack,
  47. PackData,
  48. iter_sha1,
  49. write_pack_header,
  50. write_pack_index_v2,
  51. write_pack_object,
  52. write_pack_objects,
  53. compute_file_sha,
  54. PackIndexer,
  55. PackStreamCopier,
  56. )
  57. INFODIR = 'info'
  58. PACKDIR = 'pack'
  59. class BaseObjectStore(object):
  60. """Object store interface."""
  61. def determine_wants_all(self, refs):
  62. return [sha for (ref, sha) in refs.iteritems()
  63. if not sha in self and not ref.endswith("^{}") and
  64. not sha == ZERO_SHA]
  65. def iter_shas(self, shas):
  66. """Iterate over the objects for the specified shas.
  67. :param shas: Iterable object with SHAs
  68. :return: Object iterator
  69. """
  70. return ObjectStoreIterator(self, shas)
  71. def contains_loose(self, sha):
  72. """Check if a particular object is present by SHA1 and is loose."""
  73. raise NotImplementedError(self.contains_loose)
  74. def contains_packed(self, sha):
  75. """Check if a particular object is present by SHA1 and is packed."""
  76. raise NotImplementedError(self.contains_packed)
  77. def __contains__(self, sha):
  78. """Check if a particular object is present by SHA1.
  79. This method makes no distinction between loose and packed objects.
  80. """
  81. return self.contains_packed(sha) or self.contains_loose(sha)
  82. @property
  83. def packs(self):
  84. """Iterable of pack objects."""
  85. raise NotImplementedError
  86. def get_raw(self, name):
  87. """Obtain the raw text for an object.
  88. :param name: sha for the object.
  89. :return: tuple with numeric type and object contents.
  90. """
  91. raise NotImplementedError(self.get_raw)
  92. def __getitem__(self, sha):
  93. """Obtain an object by SHA1."""
  94. type_num, uncomp = self.get_raw(sha)
  95. return ShaFile.from_raw_string(type_num, uncomp)
  96. def __iter__(self):
  97. """Iterate over the SHAs that are present in this store."""
  98. raise NotImplementedError(self.__iter__)
  99. def add_object(self, obj):
  100. """Add a single object to this object store.
  101. """
  102. raise NotImplementedError(self.add_object)
  103. def add_objects(self, objects):
  104. """Add a set of objects to this object store.
  105. :param objects: Iterable over a list of objects.
  106. """
  107. raise NotImplementedError(self.add_objects)
  108. def tree_changes(self, source, target, want_unchanged=False):
  109. """Find the differences between the contents of two trees
  110. :param source: SHA1 of the source tree
  111. :param target: SHA1 of the target tree
  112. :param want_unchanged: Whether unchanged files should be reported
  113. :return: Iterator over tuples with
  114. (oldpath, newpath), (oldmode, newmode), (oldsha, newsha)
  115. """
  116. for change in tree_changes(self, source, target,
  117. want_unchanged=want_unchanged):
  118. yield ((change.old.path, change.new.path),
  119. (change.old.mode, change.new.mode),
  120. (change.old.sha, change.new.sha))
  121. def iter_tree_contents(self, tree_id, include_trees=False):
  122. """Iterate the contents of a tree and all subtrees.
  123. Iteration is depth-first pre-order, as in e.g. os.walk.
  124. :param tree_id: SHA1 of the tree.
  125. :param include_trees: If True, include tree objects in the iteration.
  126. :return: Iterator over TreeEntry namedtuples for all the objects in a
  127. tree.
  128. """
  129. for entry, _ in walk_trees(self, tree_id, None):
  130. if not stat.S_ISDIR(entry.mode) or include_trees:
  131. yield entry
  132. def find_missing_objects(self, haves, wants, progress=None,
  133. get_tagged=None):
  134. """Find the missing objects required for a set of revisions.
  135. :param haves: Iterable over SHAs already in common.
  136. :param wants: Iterable over SHAs of objects to fetch.
  137. :param progress: Simple progress function that will be called with
  138. updated progress strings.
  139. :param get_tagged: Function that returns a dict of pointed-to sha -> tag
  140. sha for including tags.
  141. :return: Iterator over (sha, path) pairs.
  142. """
  143. finder = MissingObjectFinder(self, haves, wants, progress, get_tagged)
  144. return iter(finder.next, None)
  145. def find_common_revisions(self, graphwalker):
  146. """Find which revisions this store has in common using graphwalker.
  147. :param graphwalker: A graphwalker object.
  148. :return: List of SHAs that are in common
  149. """
  150. haves = []
  151. sha = graphwalker.next()
  152. while sha:
  153. if sha in self:
  154. haves.append(sha)
  155. graphwalker.ack(sha)
  156. sha = graphwalker.next()
  157. return haves
  158. def get_graph_walker(self, heads):
  159. """Obtain a graph walker for this object store.
  160. :param heads: Local heads to start search with
  161. :return: GraphWalker object
  162. """
  163. return ObjectStoreGraphWalker(heads, lambda sha: self[sha].parents)
  164. def generate_pack_contents(self, have, want, progress=None):
  165. """Iterate over the contents of a pack file.
  166. :param have: List of SHA1s of objects that should not be sent
  167. :param want: List of SHA1s of objects that should be sent
  168. :param progress: Optional progress reporting method
  169. """
  170. return self.iter_shas(self.find_missing_objects(have, want, progress))
  171. def peel_sha(self, sha):
  172. """Peel all tags from a SHA.
  173. :param sha: The object SHA to peel.
  174. :return: The fully-peeled SHA1 of a tag object, after peeling all
  175. intermediate tags; if the original ref does not point to a tag, this
  176. will equal the original SHA1.
  177. """
  178. obj = self[sha]
  179. obj_class = object_class(obj.type_name)
  180. while obj_class is Tag:
  181. obj_class, sha = obj.object
  182. obj = self[sha]
  183. return obj
  184. def _collect_ancestors(self, heads, common = set()):
  185. """Collect all ancestors of heads up to (excluding) those in common
  186. :param heads: commits to start from
  187. :param common: commits to end at, or empty set to walk repository completely
  188. :return: a tuple (A, B) where A - all commits reachable
  189. from heads but not present in common, B - common (shared) elements
  190. that are directly reachable from heads
  191. """
  192. bases = set()
  193. commits = set()
  194. queue = []
  195. queue.extend(heads)
  196. while queue:
  197. e = queue.pop(0)
  198. if e in common:
  199. bases.add(e)
  200. elif e not in commits:
  201. commits.add(e)
  202. cmt = self[e]
  203. queue.extend(cmt.parents)
  204. return (commits, bases)
  205. class PackBasedObjectStore(BaseObjectStore):
  206. def __init__(self):
  207. self._pack_cache = None
  208. @property
  209. def alternates(self):
  210. return []
  211. def contains_packed(self, sha):
  212. """Check if a particular object is present by SHA1 and is packed.
  213. This does not check alternates.
  214. """
  215. for pack in self.packs:
  216. if sha in pack:
  217. return True
  218. return False
  219. def __contains__(self, sha):
  220. """Check if a particular object is present by SHA1.
  221. This method makes no distinction between loose and packed objects.
  222. """
  223. if self.contains_packed(sha) or self.contains_loose(sha):
  224. return True
  225. for alternate in self.alternates:
  226. if sha in alternate:
  227. return True
  228. return False
  229. def _load_packs(self):
  230. raise NotImplementedError(self._load_packs)
  231. def _pack_cache_stale(self):
  232. """Check whether the pack cache is stale."""
  233. raise NotImplementedError(self._pack_cache_stale)
  234. def _add_known_pack(self, pack):
  235. """Add a newly appeared pack to the cache by path.
  236. """
  237. if self._pack_cache is not None:
  238. self._pack_cache.append(pack)
  239. @property
  240. def packs(self):
  241. """List with pack objects."""
  242. if self._pack_cache is None or self._pack_cache_stale():
  243. self._pack_cache = self._load_packs()
  244. return self._pack_cache
  245. def _iter_alternate_objects(self):
  246. """Iterate over the SHAs of all the objects in alternate stores."""
  247. for alternate in self.alternates:
  248. for alternate_object in alternate:
  249. yield alternate_object
  250. def _iter_loose_objects(self):
  251. """Iterate over the SHAs of all loose objects."""
  252. raise NotImplementedError(self._iter_loose_objects)
  253. def _get_loose_object(self, sha):
  254. raise NotImplementedError(self._get_loose_object)
  255. def _remove_loose_object(self, sha):
  256. raise NotImplementedError(self._remove_loose_object)
  257. def pack_loose_objects(self):
  258. """Pack loose objects.
  259. :return: Number of objects packed
  260. """
  261. objects = set()
  262. for sha in self._iter_loose_objects():
  263. objects.add((self._get_loose_object(sha), None))
  264. self.add_objects(list(objects))
  265. for obj, path in objects:
  266. self._remove_loose_object(obj.id)
  267. return len(objects)
  268. def __iter__(self):
  269. """Iterate over the SHAs that are present in this store."""
  270. iterables = self.packs + [self._iter_loose_objects()] + [self._iter_alternate_objects()]
  271. return itertools.chain(*iterables)
  272. def contains_loose(self, sha):
  273. """Check if a particular object is present by SHA1 and is loose.
  274. This does not check alternates.
  275. """
  276. return self._get_loose_object(sha) is not None
  277. def get_raw(self, name):
  278. """Obtain the raw text for an object.
  279. :param name: sha for the object.
  280. :return: tuple with numeric type and object contents.
  281. """
  282. if len(name) == 40:
  283. sha = hex_to_sha(name)
  284. hexsha = name
  285. elif len(name) == 20:
  286. sha = name
  287. hexsha = None
  288. else:
  289. raise AssertionError("Invalid object name %r" % name)
  290. for pack in self.packs:
  291. try:
  292. return pack.get_raw(sha)
  293. except KeyError:
  294. pass
  295. if hexsha is None:
  296. hexsha = sha_to_hex(name)
  297. ret = self._get_loose_object(hexsha)
  298. if ret is not None:
  299. return ret.type_num, ret.as_raw_string()
  300. for alternate in self.alternates:
  301. try:
  302. return alternate.get_raw(hexsha)
  303. except KeyError:
  304. pass
  305. raise KeyError(hexsha)
  306. def add_objects(self, objects):
  307. """Add a set of objects to this object store.
  308. :param objects: Iterable over objects, should support __len__.
  309. :return: Pack object of the objects written.
  310. """
  311. if len(objects) == 0:
  312. # Don't bother writing an empty pack file
  313. return
  314. f, commit = self.add_pack()
  315. write_pack_objects(f, objects)
  316. return commit()
  317. class DiskObjectStore(PackBasedObjectStore):
  318. """Git-style object store that exists on disk."""
  319. def __init__(self, path):
  320. """Open an object store.
  321. :param path: Path of the object store.
  322. """
  323. super(DiskObjectStore, self).__init__()
  324. self.path = path
  325. self.pack_dir = os.path.join(self.path, PACKDIR)
  326. self._pack_cache_time = 0
  327. self._alternates = None
  328. @property
  329. def alternates(self):
  330. if self._alternates is not None:
  331. return self._alternates
  332. self._alternates = []
  333. for path in self._read_alternate_paths():
  334. self._alternates.append(DiskObjectStore(path))
  335. return self._alternates
  336. def _read_alternate_paths(self):
  337. try:
  338. f = GitFile(os.path.join(self.path, "info", "alternates"),
  339. 'rb')
  340. except (OSError, IOError), e:
  341. if e.errno == errno.ENOENT:
  342. return []
  343. raise
  344. ret = []
  345. try:
  346. for l in f.readlines():
  347. l = l.rstrip("\n")
  348. if l[0] == "#":
  349. continue
  350. if not os.path.isabs(l):
  351. continue
  352. ret.append(l)
  353. return ret
  354. finally:
  355. f.close()
  356. def add_alternate_path(self, path):
  357. """Add an alternate path to this object store.
  358. """
  359. try:
  360. os.mkdir(os.path.join(self.path, "info"))
  361. except OSError, e:
  362. if e.errno != errno.EEXIST:
  363. raise
  364. alternates_path = os.path.join(self.path, "info/alternates")
  365. f = GitFile(alternates_path, 'wb')
  366. try:
  367. try:
  368. orig_f = open(alternates_path, 'rb')
  369. except (OSError, IOError), e:
  370. if e.errno != errno.ENOENT:
  371. raise
  372. else:
  373. try:
  374. f.write(orig_f.read())
  375. finally:
  376. orig_f.close()
  377. f.write("%s\n" % path)
  378. finally:
  379. f.close()
  380. self.alternates.append(DiskObjectStore(path))
  381. def _load_packs(self):
  382. pack_files = []
  383. try:
  384. self._pack_cache_time = os.stat(self.pack_dir).st_mtime
  385. pack_dir_contents = os.listdir(self.pack_dir)
  386. for name in pack_dir_contents:
  387. # TODO: verify that idx exists first
  388. if name.startswith("pack-") and name.endswith(".pack"):
  389. filename = os.path.join(self.pack_dir, name)
  390. pack_files.append((os.stat(filename).st_mtime, filename))
  391. except OSError, e:
  392. if e.errno == errno.ENOENT:
  393. return []
  394. raise
  395. pack_files.sort(reverse=True)
  396. suffix_len = len(".pack")
  397. return [Pack(f[:-suffix_len]) for _, f in pack_files]
  398. def _pack_cache_stale(self):
  399. try:
  400. return os.stat(self.pack_dir).st_mtime > self._pack_cache_time
  401. except OSError, e:
  402. if e.errno == errno.ENOENT:
  403. return True
  404. raise
  405. def _get_shafile_path(self, sha):
  406. # Check from object dir
  407. return hex_to_filename(self.path, sha)
  408. def _iter_loose_objects(self):
  409. for base in os.listdir(self.path):
  410. if len(base) != 2:
  411. continue
  412. for rest in os.listdir(os.path.join(self.path, base)):
  413. yield base+rest
  414. def _get_loose_object(self, sha):
  415. path = self._get_shafile_path(sha)
  416. try:
  417. return ShaFile.from_path(path)
  418. except (OSError, IOError), e:
  419. if e.errno == errno.ENOENT:
  420. return None
  421. raise
  422. def _remove_loose_object(self, sha):
  423. os.remove(self._get_shafile_path(sha))
  424. def _complete_thin_pack(self, f, path, copier, indexer):
  425. """Move a specific file containing a pack into the pack directory.
  426. :note: The file should be on the same file system as the
  427. packs directory.
  428. :param f: Open file object for the pack.
  429. :param path: Path to the pack file.
  430. :param copier: A PackStreamCopier to use for writing pack data.
  431. :param indexer: A PackIndexer for indexing the pack.
  432. """
  433. entries = list(indexer)
  434. # Update the header with the new number of objects.
  435. f.seek(0)
  436. write_pack_header(f, len(entries) + len(indexer.ext_refs()))
  437. # Must flush before reading (http://bugs.python.org/issue3207)
  438. f.flush()
  439. # Rescan the rest of the pack, computing the SHA with the new header.
  440. new_sha = compute_file_sha(f, end_ofs=-20)
  441. # Must reposition before writing (http://bugs.python.org/issue3207)
  442. f.seek(0, os.SEEK_CUR)
  443. # Complete the pack.
  444. for ext_sha in indexer.ext_refs():
  445. assert len(ext_sha) == 20
  446. type_num, data = self.get_raw(ext_sha)
  447. offset = f.tell()
  448. crc32 = write_pack_object(f, type_num, data, sha=new_sha)
  449. entries.append((ext_sha, offset, crc32))
  450. pack_sha = new_sha.digest()
  451. f.write(pack_sha)
  452. f.close()
  453. # Move the pack in.
  454. entries.sort()
  455. pack_base_name = os.path.join(
  456. self.pack_dir, 'pack-' + iter_sha1(e[0] for e in entries))
  457. os.rename(path, pack_base_name + '.pack')
  458. # Write the index.
  459. index_file = GitFile(pack_base_name + '.idx', 'wb')
  460. try:
  461. write_pack_index_v2(index_file, entries, pack_sha)
  462. index_file.close()
  463. finally:
  464. index_file.abort()
  465. # Add the pack to the store and return it.
  466. final_pack = Pack(pack_base_name)
  467. final_pack.check_length_and_checksum()
  468. self._add_known_pack(final_pack)
  469. return final_pack
  470. def add_thin_pack(self, read_all, read_some):
  471. """Add a new thin pack to this object store.
  472. Thin packs are packs that contain deltas with parents that exist outside
  473. the pack. They should never be placed in the object store directly, and
  474. always indexed and completed as they are copied.
  475. :param read_all: Read function that blocks until the number of requested
  476. bytes are read.
  477. :param read_some: Read function that returns at least one byte, but may
  478. not return the number of bytes requested.
  479. :return: A Pack object pointing at the now-completed thin pack in the
  480. objects/pack directory.
  481. """
  482. fd, path = tempfile.mkstemp(dir=self.path, prefix='tmp_pack_')
  483. f = os.fdopen(fd, 'w+b')
  484. try:
  485. indexer = PackIndexer(f, resolve_ext_ref=self.get_raw)
  486. copier = PackStreamCopier(read_all, read_some, f,
  487. delta_iter=indexer)
  488. copier.verify()
  489. return self._complete_thin_pack(f, path, copier, indexer)
  490. finally:
  491. f.close()
  492. def move_in_pack(self, path):
  493. """Move a specific file containing a pack into the pack directory.
  494. :note: The file should be on the same file system as the
  495. packs directory.
  496. :param path: Path to the pack file.
  497. """
  498. p = PackData(path)
  499. entries = p.sorted_entries()
  500. basename = os.path.join(self.pack_dir,
  501. "pack-%s" % iter_sha1(entry[0] for entry in entries))
  502. f = GitFile(basename+".idx", "wb")
  503. try:
  504. write_pack_index_v2(f, entries, p.get_stored_checksum())
  505. finally:
  506. f.close()
  507. p.close()
  508. os.rename(path, basename + ".pack")
  509. final_pack = Pack(basename)
  510. self._add_known_pack(final_pack)
  511. return final_pack
  512. def add_pack(self):
  513. """Add a new pack to this object store.
  514. :return: Fileobject to write to and a commit function to
  515. call when the pack is finished.
  516. """
  517. fd, path = tempfile.mkstemp(dir=self.pack_dir, suffix=".pack")
  518. f = os.fdopen(fd, 'wb')
  519. def commit():
  520. os.fsync(fd)
  521. f.close()
  522. if os.path.getsize(path) > 0:
  523. return self.move_in_pack(path)
  524. else:
  525. os.remove(path)
  526. return None
  527. return f, commit
  528. def add_object(self, obj):
  529. """Add a single object to this object store.
  530. :param obj: Object to add
  531. """
  532. dir = os.path.join(self.path, obj.id[:2])
  533. try:
  534. os.mkdir(dir)
  535. except OSError, e:
  536. if e.errno != errno.EEXIST:
  537. raise
  538. path = os.path.join(dir, obj.id[2:])
  539. if os.path.exists(path):
  540. return # Already there, no need to write again
  541. f = GitFile(path, 'wb')
  542. try:
  543. f.write(obj.as_legacy_object())
  544. finally:
  545. f.close()
  546. @classmethod
  547. def init(cls, path):
  548. try:
  549. os.mkdir(path)
  550. except OSError, e:
  551. if e.errno != errno.EEXIST:
  552. raise
  553. os.mkdir(os.path.join(path, "info"))
  554. os.mkdir(os.path.join(path, PACKDIR))
  555. return cls(path)
  556. class MemoryObjectStore(BaseObjectStore):
  557. """Object store that keeps all objects in memory."""
  558. def __init__(self):
  559. super(MemoryObjectStore, self).__init__()
  560. self._data = {}
  561. def _to_hexsha(self, sha):
  562. if len(sha) == 40:
  563. return sha
  564. elif len(sha) == 20:
  565. return sha_to_hex(sha)
  566. else:
  567. raise ValueError("Invalid sha %r" % (sha,))
  568. def contains_loose(self, sha):
  569. """Check if a particular object is present by SHA1 and is loose."""
  570. return self._to_hexsha(sha) in self._data
  571. def contains_packed(self, sha):
  572. """Check if a particular object is present by SHA1 and is packed."""
  573. return False
  574. def __iter__(self):
  575. """Iterate over the SHAs that are present in this store."""
  576. return self._data.iterkeys()
  577. @property
  578. def packs(self):
  579. """List with pack objects."""
  580. return []
  581. def get_raw(self, name):
  582. """Obtain the raw text for an object.
  583. :param name: sha for the object.
  584. :return: tuple with numeric type and object contents.
  585. """
  586. obj = self[self._to_hexsha(name)]
  587. return obj.type_num, obj.as_raw_string()
  588. def __getitem__(self, name):
  589. return self._data[self._to_hexsha(name)]
  590. def __delitem__(self, name):
  591. """Delete an object from this store, for testing only."""
  592. del self._data[self._to_hexsha(name)]
  593. def add_object(self, obj):
  594. """Add a single object to this object store.
  595. """
  596. self._data[obj.id] = obj
  597. def add_objects(self, objects):
  598. """Add a set of objects to this object store.
  599. :param objects: Iterable over a list of objects.
  600. """
  601. for obj, path in objects:
  602. self._data[obj.id] = obj
  603. class ObjectImporter(object):
  604. """Interface for importing objects."""
  605. def __init__(self, count):
  606. """Create a new ObjectImporter.
  607. :param count: Number of objects that's going to be imported.
  608. """
  609. self.count = count
  610. def add_object(self, object):
  611. """Add an object."""
  612. raise NotImplementedError(self.add_object)
  613. def finish(self, object):
  614. """Finish the import and write objects to disk."""
  615. raise NotImplementedError(self.finish)
  616. class ObjectIterator(object):
  617. """Interface for iterating over objects."""
  618. def iterobjects(self):
  619. raise NotImplementedError(self.iterobjects)
  620. class ObjectStoreIterator(ObjectIterator):
  621. """ObjectIterator that works on top of an ObjectStore."""
  622. def __init__(self, store, sha_iter):
  623. """Create a new ObjectIterator.
  624. :param store: Object store to retrieve from
  625. :param sha_iter: Iterator over (sha, path) tuples
  626. """
  627. self.store = store
  628. self.sha_iter = sha_iter
  629. self._shas = []
  630. def __iter__(self):
  631. """Yield tuple with next object and path."""
  632. for sha, path in self.itershas():
  633. yield self.store[sha], path
  634. def iterobjects(self):
  635. """Iterate over just the objects."""
  636. for o, path in self:
  637. yield o
  638. def itershas(self):
  639. """Iterate over the SHAs."""
  640. for sha in self._shas:
  641. yield sha
  642. for sha in self.sha_iter:
  643. self._shas.append(sha)
  644. yield sha
  645. def __contains__(self, needle):
  646. """Check if an object is present.
  647. :note: This checks if the object is present in
  648. the underlying object store, not if it would
  649. be yielded by the iterator.
  650. :param needle: SHA1 of the object to check for
  651. """
  652. return needle in self.store
  653. def __getitem__(self, key):
  654. """Find an object by SHA1.
  655. :note: This retrieves the object from the underlying
  656. object store. It will also succeed if the object would
  657. not be returned by the iterator.
  658. """
  659. return self.store[key]
  660. def __len__(self):
  661. """Return the number of objects."""
  662. return len(list(self.itershas()))
  663. def tree_lookup_path(lookup_obj, root_sha, path):
  664. """Look up an object in a Git tree.
  665. :param lookup_obj: Callback for retrieving object by SHA1
  666. :param root_sha: SHA1 of the root tree
  667. :param path: Path to lookup
  668. :return: A tuple of (mode, SHA) of the resulting path.
  669. """
  670. tree = lookup_obj(root_sha)
  671. if not isinstance(tree, Tree):
  672. raise NotTreeError(root_sha)
  673. return tree.lookup_path(lookup_obj, path)
  674. def _collect_filetree_revs(obj_store, tree_sha, kset):
  675. """Collect SHA1s of files and directories for specified tree
  676. (identified by SHA1)
  677. :param obj_store: Object store to get objects by SHA from
  678. :param tree_sha: tree reference to walk
  679. :param kset: set to fill with references to files and directories
  680. """
  681. filetree = obj_store[tree_sha]
  682. for name,mode,sha in filetree.iteritems():
  683. if not S_ISGITLINK(mode) and sha not in kset:
  684. kset.add(sha)
  685. if stat.S_ISDIR(mode):
  686. _collect_filetree_revs(obj_store, sha, kset)
  687. def _split_commits_and_tags(obj_store, lst, ignore_unknown = False):
  688. """Split lst into two lists, one with commit SHA1s, another with
  689. tag SHA1s. Commits referenced by tags are included into commits
  690. list as well. Only SHA1s known in this repository will get
  691. through, and unless ignore_unknown argument is True, KeyError
  692. is thrown for SHA1 missing in the repository
  693. :param obj_store: Object store to get objects by SHA1 from
  694. :param lst: Collection of commit and tag SHAs
  695. :param ignore_unknown: True to skip SHA1 missing in the
  696. repository silently.
  697. :return: A tuple of (commits, tags) SHA1s
  698. """
  699. commits = set()
  700. tags = set()
  701. for e in lst:
  702. try:
  703. o = obj_store[e]
  704. except KeyError:
  705. if ignore_unknown:
  706. pass
  707. else:
  708. raise
  709. else:
  710. if isinstance(o, Commit):
  711. commits.add(e)
  712. elif isinstance(o, Tag):
  713. tags.add(e)
  714. commits.add(o.object[1])
  715. else:
  716. raise KeyError('Not a commit or a tag: %s' % e)
  717. return (commits, tags)
  718. class MissingObjectFinder(object):
  719. """Find the objects missing from another object store.
  720. :param object_store: Object store containing at least all objects to be
  721. sent
  722. :param haves: SHA1s of commits not to send (already present in target)
  723. :param wants: SHA1s of commits to send
  724. :param progress: Optional function to report progress to.
  725. :param get_tagged: Function that returns a dict of pointed-to sha -> tag
  726. sha for including tags.
  727. :param tagged: dict of pointed-to sha -> tag sha for including tags
  728. """
  729. def __init__(self, object_store, haves, wants, progress=None,
  730. get_tagged=None):
  731. self.object_store = object_store
  732. # process Commits and Tags differently
  733. # Note, while haves may list commits/tags not available locally,
  734. # and such SHAs would get filtered out by _split_commits_and_tags,
  735. # wants shall list only known SHAs, and otherwise
  736. # _split_commits_and_tags fails with KeyError
  737. have_commits, have_tags = \
  738. _split_commits_and_tags(object_store, haves, True)
  739. want_commits, want_tags = \
  740. _split_commits_and_tags(object_store, wants, False)
  741. # all_ancestors is a set of commits that shall not be sent
  742. # (complete repository up to 'haves')
  743. all_ancestors = object_store._collect_ancestors(have_commits)[0]
  744. # all_missing - complete set of commits between haves and wants
  745. # common - commits from all_ancestors we hit into while
  746. # traversing parent hierarchy of wants
  747. missing_commits, common_commits = \
  748. object_store._collect_ancestors(want_commits, all_ancestors)
  749. self.sha_done = set()
  750. # Now, fill sha_done with commits and revisions of
  751. # files and directories known to be both locally
  752. # and on target. Thus these commits and files
  753. # won't get selected for fetch
  754. for h in common_commits:
  755. self.sha_done.add(h)
  756. cmt = object_store[h]
  757. _collect_filetree_revs(object_store, cmt.tree, self.sha_done)
  758. # record tags we have as visited, too
  759. for t in have_tags:
  760. self.sha_done.add(t)
  761. missing_tags = want_tags.difference(have_tags)
  762. # in fact, what we 'want' is commits and tags
  763. # we've found missing
  764. wants = missing_commits.union(missing_tags)
  765. self.objects_to_send = set([(w, None, False) for w in wants])
  766. if progress is None:
  767. self.progress = lambda x: None
  768. else:
  769. self.progress = progress
  770. self._tagged = get_tagged and get_tagged() or {}
  771. def add_todo(self, entries):
  772. self.objects_to_send.update([e for e in entries
  773. if not e[0] in self.sha_done])
  774. def next(self):
  775. while True:
  776. if not self.objects_to_send:
  777. return None
  778. (sha, name, leaf) = self.objects_to_send.pop()
  779. if sha not in self.sha_done:
  780. break
  781. if not leaf:
  782. o = self.object_store[sha]
  783. if isinstance(o, Commit):
  784. self.add_todo([(o.tree, "", False)])
  785. elif isinstance(o, Tree):
  786. self.add_todo([(s, n, not stat.S_ISDIR(m))
  787. for n, m, s in o.iteritems()
  788. if not S_ISGITLINK(m)])
  789. elif isinstance(o, Tag):
  790. self.add_todo([(o.object[1], None, False)])
  791. if sha in self._tagged:
  792. self.add_todo([(self._tagged[sha], None, True)])
  793. self.sha_done.add(sha)
  794. self.progress("counting objects: %d\r" % len(self.sha_done))
  795. return (sha, name)
  796. class ObjectStoreGraphWalker(object):
  797. """Graph walker that finds what commits are missing from an object store.
  798. :ivar heads: Revisions without descendants in the local repo
  799. :ivar get_parents: Function to retrieve parents in the local repo
  800. """
  801. def __init__(self, local_heads, get_parents):
  802. """Create a new instance.
  803. :param local_heads: Heads to start search with
  804. :param get_parents: Function for finding the parents of a SHA1.
  805. """
  806. self.heads = set(local_heads)
  807. self.get_parents = get_parents
  808. self.parents = {}
  809. def ack(self, sha):
  810. """Ack that a revision and its ancestors are present in the source."""
  811. ancestors = set([sha])
  812. # stop if we run out of heads to remove
  813. while self.heads:
  814. for a in ancestors:
  815. if a in self.heads:
  816. self.heads.remove(a)
  817. # collect all ancestors
  818. new_ancestors = set()
  819. for a in ancestors:
  820. ps = self.parents.get(a)
  821. if ps is not None:
  822. new_ancestors.update(ps)
  823. self.parents[a] = None
  824. # no more ancestors; stop
  825. if not new_ancestors:
  826. break
  827. ancestors = new_ancestors
  828. def next(self):
  829. """Iterate over ancestors of heads in the target."""
  830. if self.heads:
  831. ret = self.heads.pop()
  832. ps = self.get_parents(ret)
  833. self.parents[ret] = ps
  834. self.heads.update([p for p in ps if not p in self.parents])
  835. return ret
  836. return None