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