2
0

object_store.py 36 KB

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