object_store.py 36 KB

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