object_store.py 37 KB

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