object_store.py 37 KB

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