object_store.py 36 KB

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