object_store.py 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649
  1. # object_store.py -- Object store for git objects
  2. # Copyright (C) 2008-2013 Jelmer Vernooij <jelmer@jelmer.uk>
  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. import os
  23. import stat
  24. import sys
  25. import warnings
  26. from contextlib import suppress
  27. from io import BytesIO
  28. from typing import (Callable, Dict, Iterable, Iterator, List, Optional,
  29. Sequence, Set, Tuple, cast)
  30. try:
  31. from typing import Protocol
  32. except ImportError: # python << 3.8
  33. from typing_extensions import Protocol # type: ignore
  34. from dulwich.errors import NotTreeError
  35. from dulwich.file import GitFile
  36. from dulwich.objects import (S_ISGITLINK, ZERO_SHA, Blob, Commit, ObjectID,
  37. ShaFile, Tag, Tree, TreeEntry, hex_to_filename,
  38. hex_to_sha, object_class, sha_to_hex,
  39. valid_hexsha)
  40. from dulwich.pack import (PACK_SPOOL_FILE_MAX_SIZE, ObjectContainer, Pack,
  41. PackData, PackedObjectContainer, PackFileDisappeared,
  42. PackHint, PackIndexer, PackInflater,
  43. PackStreamCopier, UnpackedObject, extend_pack,
  44. full_unpacked_object, generate_unpacked_objects,
  45. iter_sha1, load_pack_index_file,
  46. pack_objects_to_data, write_pack_data,
  47. write_pack_index)
  48. from dulwich.protocol import DEPTH_INFINITE
  49. from dulwich.refs import PEELED_TAG_SUFFIX, Ref
  50. INFODIR = "info"
  51. PACKDIR = "pack"
  52. # use permissions consistent with Git; just readable by everyone
  53. # TODO: should packs also be non-writable on Windows? if so, that
  54. # would requite some rather significant adjustments to the test suite
  55. PACK_MODE = 0o444 if sys.platform != "win32" else 0o644
  56. class PackContainer(Protocol):
  57. def add_pack(
  58. self
  59. ) -> Tuple[BytesIO, Callable[[], None], Callable[[], None]]:
  60. """Add a new pack."""
  61. class BaseObjectStore:
  62. """Object store interface."""
  63. def determine_wants_all(
  64. self,
  65. refs: Dict[Ref, ObjectID],
  66. depth: Optional[int] = None
  67. ) -> List[ObjectID]:
  68. def _want_deepen(sha):
  69. if not depth:
  70. return False
  71. if depth == DEPTH_INFINITE:
  72. return True
  73. return depth > self._get_depth(sha)
  74. return [
  75. sha
  76. for (ref, sha) in refs.items()
  77. if (sha not in self or _want_deepen(sha))
  78. and not ref.endswith(PEELED_TAG_SUFFIX)
  79. and not sha == ZERO_SHA
  80. ]
  81. def contains_loose(self, sha):
  82. """Check if a particular object is present by SHA1 and is loose."""
  83. raise NotImplementedError(self.contains_loose)
  84. def __contains__(self, sha1: bytes) -> bool:
  85. """Check if a particular object is present by SHA1.
  86. This method makes no distinction between loose and packed objects.
  87. """
  88. return self.contains_loose(sha1)
  89. @property
  90. def packs(self):
  91. """Iterable of pack objects."""
  92. raise NotImplementedError
  93. def get_raw(self, name):
  94. """Obtain the raw text for an object.
  95. Args:
  96. name: sha for the object.
  97. Returns: tuple with numeric type and object contents.
  98. """
  99. raise NotImplementedError(self.get_raw)
  100. def __getitem__(self, sha1: ObjectID) -> ShaFile:
  101. """Obtain an object by SHA1."""
  102. type_num, uncomp = self.get_raw(sha1)
  103. return ShaFile.from_raw_string(type_num, uncomp, sha=sha1)
  104. def __iter__(self):
  105. """Iterate over the SHAs that are present in this store."""
  106. raise NotImplementedError(self.__iter__)
  107. def add_object(self, obj):
  108. """Add a single object to this object store."""
  109. raise NotImplementedError(self.add_object)
  110. def add_objects(self, objects, progress=None):
  111. """Add a set of objects to this object store.
  112. Args:
  113. objects: Iterable over a list of (object, path) tuples
  114. """
  115. raise NotImplementedError(self.add_objects)
  116. def tree_changes(
  117. self,
  118. source,
  119. target,
  120. want_unchanged=False,
  121. include_trees=False,
  122. change_type_same=False,
  123. rename_detector=None,
  124. ):
  125. """Find the differences between the contents of two trees
  126. Args:
  127. source: SHA1 of the source tree
  128. target: SHA1 of the target tree
  129. want_unchanged: Whether unchanged files should be reported
  130. include_trees: Whether to include trees
  131. change_type_same: Whether to report files changing
  132. type in the same entry.
  133. Returns: Iterator over tuples with
  134. (oldpath, newpath), (oldmode, newmode), (oldsha, newsha)
  135. """
  136. from dulwich.diff_tree import tree_changes
  137. for change in tree_changes(
  138. self,
  139. source,
  140. target,
  141. want_unchanged=want_unchanged,
  142. include_trees=include_trees,
  143. change_type_same=change_type_same,
  144. rename_detector=rename_detector,
  145. ):
  146. yield (
  147. (change.old.path, change.new.path),
  148. (change.old.mode, change.new.mode),
  149. (change.old.sha, change.new.sha),
  150. )
  151. def iter_tree_contents(self, tree_id, include_trees=False):
  152. """Iterate the contents of a tree and all subtrees.
  153. Iteration is depth-first pre-order, as in e.g. os.walk.
  154. Args:
  155. tree_id: SHA1 of the tree.
  156. include_trees: If True, include tree objects in the iteration.
  157. Returns: Iterator over TreeEntry namedtuples for all the objects in a
  158. tree.
  159. """
  160. warnings.warn(
  161. "Please use dulwich.object_store.iter_tree_contents",
  162. DeprecationWarning, stacklevel=2)
  163. return iter_tree_contents(self, tree_id, include_trees=include_trees)
  164. def iterobjects_subset(self, shas: Iterable[bytes], *, allow_missing: bool = False) -> Iterator[ShaFile]:
  165. for sha in shas:
  166. try:
  167. yield self[sha]
  168. except KeyError:
  169. if not allow_missing:
  170. raise
  171. def find_missing_objects(
  172. self,
  173. haves,
  174. wants,
  175. shallow=None,
  176. progress=None,
  177. get_tagged=None,
  178. get_parents=lambda commit: commit.parents,
  179. ):
  180. """Find the missing objects required for a set of revisions.
  181. Args:
  182. haves: Iterable over SHAs already in common.
  183. wants: Iterable over SHAs of objects to fetch.
  184. shallow: Set of shallow commit SHA1s to skip
  185. progress: Simple progress function that will be called with
  186. updated progress strings.
  187. get_tagged: Function that returns a dict of pointed-to sha ->
  188. tag sha for including tags.
  189. get_parents: Optional function for getting the parents of a
  190. commit.
  191. Returns: Iterator over (sha, path) pairs.
  192. """
  193. warnings.warn(
  194. 'Please use MissingObjectFinder(store)', DeprecationWarning)
  195. finder = MissingObjectFinder(
  196. self,
  197. haves=haves,
  198. wants=wants,
  199. shallow=shallow,
  200. progress=progress,
  201. get_tagged=get_tagged,
  202. get_parents=get_parents,
  203. )
  204. return iter(finder)
  205. def find_common_revisions(self, graphwalker):
  206. """Find which revisions this store has in common using graphwalker.
  207. Args:
  208. graphwalker: A graphwalker object.
  209. Returns: List of SHAs that are in common
  210. """
  211. haves = []
  212. sha = next(graphwalker)
  213. while sha:
  214. if sha in self:
  215. haves.append(sha)
  216. graphwalker.ack(sha)
  217. sha = next(graphwalker)
  218. return haves
  219. def generate_pack_data(
  220. self, have, want, shallow=None, progress=None,
  221. ofs_delta=True
  222. ) -> Tuple[int, Iterator[UnpackedObject]]:
  223. """Generate pack data objects for a set of wants/haves.
  224. Args:
  225. have: List of SHA1s of objects that should not be sent
  226. want: List of SHA1s of objects that should be sent
  227. shallow: Set of shallow commit SHA1s to skip
  228. ofs_delta: Whether OFS deltas can be included
  229. progress: Optional progress reporting method
  230. """
  231. # Note that the pack-specific implementation below is more efficient,
  232. # as it reuses deltas
  233. missing_objects = MissingObjectFinder(
  234. self, haves=have, wants=want, shallow=shallow, progress=progress)
  235. object_ids = list(missing_objects)
  236. return pack_objects_to_data(
  237. [(self[oid], path) for oid, path in object_ids], ofs_delta=ofs_delta,
  238. progress=progress)
  239. def peel_sha(self, sha):
  240. """Peel all tags from a SHA.
  241. Args:
  242. sha: The object SHA to peel.
  243. Returns: The fully-peeled SHA1 of a tag object, after peeling all
  244. intermediate tags; if the original ref does not point to a tag,
  245. this will equal the original SHA1.
  246. """
  247. warnings.warn(
  248. "Please use dulwich.object_store.peel_sha()",
  249. DeprecationWarning, stacklevel=2)
  250. return peel_sha(self, sha)[1]
  251. def _get_depth(
  252. self, head, get_parents=lambda commit: commit.parents, max_depth=None,
  253. ):
  254. """Return the current available depth for the given head.
  255. For commits with multiple parents, the largest possible depth will be
  256. returned.
  257. Args:
  258. head: commit to start from
  259. get_parents: optional function for getting the parents of a commit
  260. max_depth: maximum depth to search
  261. """
  262. if head not in self:
  263. return 0
  264. current_depth = 1
  265. queue = [(head, current_depth)]
  266. while queue and (max_depth is None or current_depth < max_depth):
  267. e, depth = queue.pop(0)
  268. current_depth = max(current_depth, depth)
  269. cmt = self[e]
  270. if isinstance(cmt, Tag):
  271. _cls, sha = cmt.object
  272. cmt = self[sha]
  273. queue.extend(
  274. (parent, depth + 1)
  275. for parent in get_parents(cmt)
  276. if parent in self
  277. )
  278. return current_depth
  279. def close(self):
  280. """Close any files opened by this object store."""
  281. # Default implementation is a NO-OP
  282. class PackBasedObjectStore(BaseObjectStore):
  283. def __init__(self, pack_compression_level=-1):
  284. self._pack_cache = {}
  285. self.pack_compression_level = pack_compression_level
  286. def add_pack(
  287. self
  288. ) -> Tuple[BytesIO, Callable[[], None], Callable[[], None]]:
  289. """Add a new pack to this object store."""
  290. raise NotImplementedError(self.add_pack)
  291. def add_pack_data(self, count: int, unpacked_objects: Iterator[UnpackedObject], progress=None) -> None:
  292. """Add pack data to this object store.
  293. Args:
  294. count: Number of items to add
  295. pack_data: Iterator over pack data tuples
  296. """
  297. if count == 0:
  298. # Don't bother writing an empty pack file
  299. return
  300. f, commit, abort = self.add_pack()
  301. try:
  302. write_pack_data(
  303. f.write,
  304. unpacked_objects,
  305. num_records=count,
  306. progress=progress,
  307. compression_level=self.pack_compression_level,
  308. )
  309. except BaseException:
  310. abort()
  311. raise
  312. else:
  313. return commit()
  314. @property
  315. def alternates(self):
  316. return []
  317. def contains_packed(self, sha):
  318. """Check if a particular object is present by SHA1 and is packed.
  319. This does not check alternates.
  320. """
  321. for pack in self.packs:
  322. try:
  323. if sha in pack:
  324. return True
  325. except PackFileDisappeared:
  326. pass
  327. return False
  328. def __contains__(self, sha):
  329. """Check if a particular object is present by SHA1.
  330. This method makes no distinction between loose and packed objects.
  331. """
  332. if self.contains_packed(sha) or self.contains_loose(sha):
  333. return True
  334. for alternate in self.alternates:
  335. if sha in alternate:
  336. return True
  337. return False
  338. def _add_cached_pack(self, base_name, pack):
  339. """Add a newly appeared pack to the cache by path."""
  340. prev_pack = self._pack_cache.get(base_name)
  341. if prev_pack is not pack:
  342. self._pack_cache[base_name] = pack
  343. if prev_pack:
  344. prev_pack.close()
  345. def generate_pack_data(
  346. self, have, want, shallow=None, progress=None,
  347. ofs_delta=True
  348. ) -> Tuple[int, Iterator[UnpackedObject]]:
  349. """Generate pack data objects for a set of wants/haves.
  350. Args:
  351. have: List of SHA1s of objects that should not be sent
  352. want: List of SHA1s of objects that should be sent
  353. shallow: Set of shallow commit SHA1s to skip
  354. ofs_delta: Whether OFS deltas can be included
  355. progress: Optional progress reporting method
  356. """
  357. missing_objects = MissingObjectFinder(
  358. self, haves=have, wants=want, shallow=shallow, progress=progress)
  359. remote_has = missing_objects.get_remote_has()
  360. object_ids = list(missing_objects)
  361. return len(object_ids), generate_unpacked_objects(
  362. cast(PackedObjectContainer, self),
  363. object_ids,
  364. progress=progress,
  365. ofs_delta=ofs_delta,
  366. other_haves=remote_has)
  367. def _clear_cached_packs(self):
  368. pack_cache = self._pack_cache
  369. self._pack_cache = {}
  370. while pack_cache:
  371. (name, pack) = pack_cache.popitem()
  372. pack.close()
  373. def _iter_cached_packs(self):
  374. return self._pack_cache.values()
  375. def _update_pack_cache(self):
  376. raise NotImplementedError(self._update_pack_cache)
  377. def close(self):
  378. self._clear_cached_packs()
  379. @property
  380. def packs(self):
  381. """List with pack objects."""
  382. return list(self._iter_cached_packs()) + list(self._update_pack_cache())
  383. def _iter_alternate_objects(self):
  384. """Iterate over the SHAs of all the objects in alternate stores."""
  385. for alternate in self.alternates:
  386. yield from alternate
  387. def _iter_loose_objects(self):
  388. """Iterate over the SHAs of all loose objects."""
  389. raise NotImplementedError(self._iter_loose_objects)
  390. def _get_loose_object(self, sha):
  391. raise NotImplementedError(self._get_loose_object)
  392. def _remove_loose_object(self, sha):
  393. raise NotImplementedError(self._remove_loose_object)
  394. def _remove_pack(self, name):
  395. raise NotImplementedError(self._remove_pack)
  396. def pack_loose_objects(self):
  397. """Pack loose objects.
  398. Returns: Number of objects packed
  399. """
  400. objects = set()
  401. for sha in self._iter_loose_objects():
  402. objects.add((self._get_loose_object(sha), None))
  403. self.add_objects(list(objects))
  404. for obj, path in objects:
  405. self._remove_loose_object(obj.id)
  406. return len(objects)
  407. def repack(self):
  408. """Repack the packs in this repository.
  409. Note that this implementation is fairly naive and currently keeps all
  410. objects in memory while it repacks.
  411. """
  412. loose_objects = set()
  413. for sha in self._iter_loose_objects():
  414. loose_objects.add(self._get_loose_object(sha))
  415. objects = {(obj, None) for obj in loose_objects}
  416. old_packs = {p.name(): p for p in self.packs}
  417. for name, pack in old_packs.items():
  418. objects.update((obj, None) for obj in pack.iterobjects())
  419. # The name of the consolidated pack might match the name of a
  420. # pre-existing pack. Take care not to remove the newly created
  421. # consolidated pack.
  422. consolidated = self.add_objects(objects)
  423. old_packs.pop(consolidated.name(), None)
  424. for obj in loose_objects:
  425. self._remove_loose_object(obj.id)
  426. for name, pack in old_packs.items():
  427. self._remove_pack(pack)
  428. self._update_pack_cache()
  429. return len(objects)
  430. def __iter__(self):
  431. """Iterate over the SHAs that are present in this store."""
  432. self._update_pack_cache()
  433. for pack in self._iter_cached_packs():
  434. try:
  435. yield from pack
  436. except PackFileDisappeared:
  437. pass
  438. yield from self._iter_loose_objects()
  439. yield from self._iter_alternate_objects()
  440. def contains_loose(self, sha):
  441. """Check if a particular object is present by SHA1 and is loose.
  442. This does not check alternates.
  443. """
  444. return self._get_loose_object(sha) is not None
  445. def get_raw(self, name):
  446. """Obtain the raw fulltext for an object.
  447. Args:
  448. name: sha for the object.
  449. Returns: tuple with numeric type and object contents.
  450. """
  451. if name == ZERO_SHA:
  452. raise KeyError(name)
  453. if len(name) == 40:
  454. sha = hex_to_sha(name)
  455. hexsha = name
  456. elif len(name) == 20:
  457. sha = name
  458. hexsha = None
  459. else:
  460. raise AssertionError("Invalid object name {!r}".format(name))
  461. for pack in self._iter_cached_packs():
  462. try:
  463. return pack.get_raw(sha)
  464. except (KeyError, PackFileDisappeared):
  465. pass
  466. if hexsha is None:
  467. hexsha = sha_to_hex(name)
  468. ret = self._get_loose_object(hexsha)
  469. if ret is not None:
  470. return ret.type_num, ret.as_raw_string()
  471. # Maybe something else has added a pack with the object
  472. # in the mean time?
  473. for pack in self._update_pack_cache():
  474. try:
  475. return pack.get_raw(sha)
  476. except KeyError:
  477. pass
  478. for alternate in self.alternates:
  479. try:
  480. return alternate.get_raw(hexsha)
  481. except KeyError:
  482. pass
  483. raise KeyError(hexsha)
  484. def iter_unpacked_subset(self, shas, *, include_comp=False, allow_missing: bool = False, convert_ofs_delta: bool = True) -> Iterator[ShaFile]:
  485. todo: Set[bytes] = set(shas)
  486. for p in self._iter_cached_packs():
  487. for unpacked in p.iter_unpacked_subset(todo, include_comp=include_comp, allow_missing=True, convert_ofs_delta=convert_ofs_delta):
  488. yield unpacked
  489. hexsha = sha_to_hex(unpacked.sha())
  490. todo.remove(hexsha)
  491. # Maybe something else has added a pack with the object
  492. # in the mean time?
  493. for p in self._update_pack_cache():
  494. for unpacked in p.iter_unpacked_subset(todo, include_comp=include_comp, allow_missing=True, convert_ofs_delta=convert_ofs_delta):
  495. yield unpacked
  496. hexsha = sha_to_hex(unpacked.sha())
  497. todo.remove(hexsha)
  498. for alternate in self.alternates:
  499. for unpacked in alternate.iter_unpacked_subset(todo, include_comp=include_comp, allow_missing=True, convert_ofs_delta=convert_ofs_delta):
  500. yield unpacked
  501. hexsha = sha_to_hex(unpacked.sha())
  502. todo.remove(hexsha)
  503. def iterobjects_subset(self, shas: Iterable[bytes], *, allow_missing: bool = False) -> Iterator[ShaFile]:
  504. todo: Set[bytes] = set(shas)
  505. for p in self._iter_cached_packs():
  506. for o in p.iterobjects_subset(todo, allow_missing=True):
  507. yield o
  508. todo.remove(o.id)
  509. # Maybe something else has added a pack with the object
  510. # in the mean time?
  511. for p in self._update_pack_cache():
  512. for o in p.iterobjects_subset(todo, allow_missing=True):
  513. yield o
  514. todo.remove(o.id)
  515. for alternate in self.alternates:
  516. for o in alternate.iterobjects_subset(todo, allow_missing=True):
  517. yield o
  518. todo.remove(o.id)
  519. for oid in todo:
  520. o = self._get_loose_object(oid)
  521. if o is not None:
  522. yield o
  523. elif not allow_missing:
  524. raise KeyError(oid)
  525. def get_unpacked_object(self, sha1: bytes, *, include_comp: bool = False) -> UnpackedObject:
  526. """Obtain the unpacked object.
  527. Args:
  528. sha1: sha for the object.
  529. """
  530. if sha1 == ZERO_SHA:
  531. raise KeyError(sha1)
  532. if len(sha1) == 40:
  533. sha = hex_to_sha(sha1)
  534. hexsha = sha1
  535. elif len(sha1) == 20:
  536. sha = sha1
  537. hexsha = None
  538. else:
  539. raise AssertionError("Invalid object sha1 {!r}".format(sha1))
  540. for pack in self._iter_cached_packs():
  541. try:
  542. return pack.get_unpacked_object(sha, include_comp=include_comp)
  543. except (KeyError, PackFileDisappeared):
  544. pass
  545. if hexsha is None:
  546. hexsha = sha_to_hex(sha1)
  547. # Maybe something else has added a pack with the object
  548. # in the mean time?
  549. for pack in self._update_pack_cache():
  550. try:
  551. return pack.get_unpacked_object(sha, include_comp=include_comp)
  552. except KeyError:
  553. pass
  554. for alternate in self.alternates:
  555. try:
  556. return alternate.get_unpacked_object(hexsha, include_comp=include_comp)
  557. except KeyError:
  558. pass
  559. raise KeyError(hexsha)
  560. def add_objects(
  561. self, objects: Sequence[Tuple[ShaFile, Optional[str]]],
  562. progress: Optional[Callable[[str], None]] = None) -> None:
  563. """Add a set of objects to this object store.
  564. Args:
  565. objects: Iterable over (object, path) tuples, should support
  566. __len__.
  567. Returns: Pack object of the objects written.
  568. """
  569. count = len(objects)
  570. record_iter = (full_unpacked_object(o) for (o, p) in objects)
  571. return self.add_pack_data(count, record_iter, progress=progress)
  572. class DiskObjectStore(PackBasedObjectStore):
  573. """Git-style object store that exists on disk."""
  574. def __init__(self, path, loose_compression_level=-1, pack_compression_level=-1):
  575. """Open an object store.
  576. Args:
  577. path: Path of the object store.
  578. loose_compression_level: zlib compression level for loose objects
  579. pack_compression_level: zlib compression level for pack objects
  580. """
  581. super().__init__(
  582. pack_compression_level=pack_compression_level
  583. )
  584. self.path = path
  585. self.pack_dir = os.path.join(self.path, PACKDIR)
  586. self._alternates = None
  587. self.loose_compression_level = loose_compression_level
  588. self.pack_compression_level = pack_compression_level
  589. def __repr__(self):
  590. return "<{}({!r})>".format(self.__class__.__name__, self.path)
  591. @classmethod
  592. def from_config(cls, path, config):
  593. try:
  594. default_compression_level = int(
  595. config.get((b"core",), b"compression").decode()
  596. )
  597. except KeyError:
  598. default_compression_level = -1
  599. try:
  600. loose_compression_level = int(
  601. config.get((b"core",), b"looseCompression").decode()
  602. )
  603. except KeyError:
  604. loose_compression_level = default_compression_level
  605. try:
  606. pack_compression_level = int(
  607. config.get((b"core",), "packCompression").decode()
  608. )
  609. except KeyError:
  610. pack_compression_level = default_compression_level
  611. return cls(path, loose_compression_level, pack_compression_level)
  612. @property
  613. def alternates(self):
  614. if self._alternates is not None:
  615. return self._alternates
  616. self._alternates = []
  617. for path in self._read_alternate_paths():
  618. self._alternates.append(DiskObjectStore(path))
  619. return self._alternates
  620. def _read_alternate_paths(self):
  621. try:
  622. f = GitFile(os.path.join(self.path, INFODIR, "alternates"), "rb")
  623. except FileNotFoundError:
  624. return
  625. with f:
  626. for line in f.readlines():
  627. line = line.rstrip(b"\n")
  628. if line.startswith(b"#"):
  629. continue
  630. if os.path.isabs(line):
  631. yield os.fsdecode(line)
  632. else:
  633. yield os.fsdecode(os.path.join(os.fsencode(self.path), line))
  634. def add_alternate_path(self, path):
  635. """Add an alternate path to this object store."""
  636. try:
  637. os.mkdir(os.path.join(self.path, INFODIR))
  638. except FileExistsError:
  639. pass
  640. alternates_path = os.path.join(self.path, INFODIR, "alternates")
  641. with GitFile(alternates_path, "wb") as f:
  642. try:
  643. orig_f = open(alternates_path, "rb")
  644. except FileNotFoundError:
  645. pass
  646. else:
  647. with orig_f:
  648. f.write(orig_f.read())
  649. f.write(os.fsencode(path) + b"\n")
  650. if not os.path.isabs(path):
  651. path = os.path.join(self.path, path)
  652. self.alternates.append(DiskObjectStore(path))
  653. def _update_pack_cache(self):
  654. """Read and iterate over new pack files and cache them."""
  655. try:
  656. pack_dir_contents = os.listdir(self.pack_dir)
  657. except FileNotFoundError:
  658. self.close()
  659. return []
  660. pack_files = set()
  661. for name in pack_dir_contents:
  662. if name.startswith("pack-") and name.endswith(".pack"):
  663. # verify that idx exists first (otherwise the pack was not yet
  664. # fully written)
  665. idx_name = os.path.splitext(name)[0] + ".idx"
  666. if idx_name in pack_dir_contents:
  667. pack_name = name[: -len(".pack")]
  668. pack_files.add(pack_name)
  669. # Open newly appeared pack files
  670. new_packs = []
  671. for f in pack_files:
  672. if f not in self._pack_cache:
  673. pack = Pack(os.path.join(self.pack_dir, f))
  674. new_packs.append(pack)
  675. self._pack_cache[f] = pack
  676. # Remove disappeared pack files
  677. for f in set(self._pack_cache) - pack_files:
  678. self._pack_cache.pop(f).close()
  679. return new_packs
  680. def _get_shafile_path(self, sha):
  681. # Check from object dir
  682. return hex_to_filename(self.path, sha)
  683. def _iter_loose_objects(self):
  684. for base in os.listdir(self.path):
  685. if len(base) != 2:
  686. continue
  687. for rest in os.listdir(os.path.join(self.path, base)):
  688. sha = os.fsencode(base + rest)
  689. if not valid_hexsha(sha):
  690. continue
  691. yield sha
  692. def _get_loose_object(self, sha):
  693. path = self._get_shafile_path(sha)
  694. try:
  695. return ShaFile.from_path(path)
  696. except FileNotFoundError:
  697. return None
  698. def _remove_loose_object(self, sha):
  699. os.remove(self._get_shafile_path(sha))
  700. def _remove_pack(self, pack):
  701. try:
  702. del self._pack_cache[os.path.basename(pack._basename)]
  703. except KeyError:
  704. pass
  705. pack.close()
  706. os.remove(pack.data.path)
  707. os.remove(pack.index.path)
  708. def _get_pack_basepath(self, entries):
  709. suffix = iter_sha1(entry[0] for entry in entries)
  710. # TODO: Handle self.pack_dir being bytes
  711. suffix = suffix.decode("ascii")
  712. return os.path.join(self.pack_dir, "pack-" + suffix)
  713. def _complete_pack(self, f, path, num_objects, indexer, progress=None):
  714. """Move a specific file containing a pack into the pack directory.
  715. Note: The file should be on the same file system as the
  716. packs directory.
  717. Args:
  718. f: Open file object for the pack.
  719. path: Path to the pack file.
  720. indexer: A PackIndexer for indexing the pack.
  721. """
  722. entries = []
  723. for i, entry in enumerate(indexer):
  724. if progress is not None:
  725. progress(("generating index: %d/%d\r" % (i, num_objects)).encode('ascii'))
  726. entries.append(entry)
  727. pack_sha, extra_entries = extend_pack(
  728. f, indexer.ext_refs(), get_raw=self.get_raw, compression_level=self.pack_compression_level,
  729. progress=progress)
  730. f.flush()
  731. try:
  732. fileno = f.fileno()
  733. except AttributeError:
  734. pass
  735. else:
  736. os.fsync(fileno)
  737. f.close()
  738. entries.extend(extra_entries)
  739. # Move the pack in.
  740. entries.sort()
  741. pack_base_name = self._get_pack_basepath(entries)
  742. for pack in self.packs:
  743. if pack._basename == pack_base_name:
  744. return pack
  745. target_pack_path = pack_base_name + ".pack"
  746. target_index_path = pack_base_name + ".idx"
  747. if sys.platform == "win32":
  748. # Windows might have the target pack file lingering. Attempt
  749. # removal, silently passing if the target does not exist.
  750. with suppress(FileNotFoundError):
  751. os.remove(target_pack_path)
  752. os.rename(path, target_pack_path)
  753. # Write the index.
  754. with GitFile(target_index_path, "wb", mask=PACK_MODE) as index_file:
  755. write_pack_index(index_file, entries, pack_sha)
  756. # Add the pack to the store and return it.
  757. final_pack = Pack(pack_base_name)
  758. final_pack.check_length_and_checksum()
  759. self._add_cached_pack(pack_base_name, final_pack)
  760. return final_pack
  761. def add_thin_pack(self, read_all, read_some, progress=None):
  762. """Add a new thin pack to this object store.
  763. Thin packs are packs that contain deltas with parents that exist
  764. outside the pack. They should never be placed in the object store
  765. directly, and always indexed and completed as they are copied.
  766. Args:
  767. read_all: Read function that blocks until the number of
  768. requested bytes are read.
  769. read_some: Read function that returns at least one byte, but may
  770. not return the number of bytes requested.
  771. Returns: A Pack object pointing at the now-completed thin pack in the
  772. objects/pack directory.
  773. """
  774. import tempfile
  775. fd, path = tempfile.mkstemp(dir=self.path, prefix="tmp_pack_")
  776. with os.fdopen(fd, "w+b") as f:
  777. os.chmod(path, PACK_MODE)
  778. indexer = PackIndexer(f, resolve_ext_ref=self.get_raw)
  779. copier = PackStreamCopier(read_all, read_some, f, delta_iter=indexer)
  780. copier.verify(progress=progress)
  781. return self._complete_pack(f, path, len(copier), indexer, progress=progress)
  782. def add_pack(self):
  783. """Add a new pack to this object store.
  784. Returns: Fileobject to write to, a commit function to
  785. call when the pack is finished and an abort
  786. function.
  787. """
  788. import tempfile
  789. fd, path = tempfile.mkstemp(dir=self.pack_dir, suffix=".pack")
  790. f = os.fdopen(fd, "w+b")
  791. os.chmod(path, PACK_MODE)
  792. def commit():
  793. if f.tell() > 0:
  794. f.seek(0)
  795. with PackData(path, f) as pd:
  796. indexer = PackIndexer.for_pack_data(pd, resolve_ext_ref=self.get_raw)
  797. return self._complete_pack(f, path, len(pd), indexer)
  798. else:
  799. f.close()
  800. os.remove(path)
  801. return None
  802. def abort():
  803. f.close()
  804. os.remove(path)
  805. return f, commit, abort
  806. def add_object(self, obj):
  807. """Add a single object to this object store.
  808. Args:
  809. obj: Object to add
  810. """
  811. path = self._get_shafile_path(obj.id)
  812. dir = os.path.dirname(path)
  813. try:
  814. os.mkdir(dir)
  815. except FileExistsError:
  816. pass
  817. if os.path.exists(path):
  818. return # Already there, no need to write again
  819. with GitFile(path, "wb", mask=PACK_MODE) as f:
  820. f.write(
  821. obj.as_legacy_object(compression_level=self.loose_compression_level)
  822. )
  823. @classmethod
  824. def init(cls, path):
  825. try:
  826. os.mkdir(path)
  827. except FileExistsError:
  828. pass
  829. os.mkdir(os.path.join(path, "info"))
  830. os.mkdir(os.path.join(path, PACKDIR))
  831. return cls(path)
  832. class MemoryObjectStore(BaseObjectStore):
  833. """Object store that keeps all objects in memory."""
  834. def __init__(self):
  835. super().__init__()
  836. self._data = {}
  837. self.pack_compression_level = -1
  838. def _to_hexsha(self, sha):
  839. if len(sha) == 40:
  840. return sha
  841. elif len(sha) == 20:
  842. return sha_to_hex(sha)
  843. else:
  844. raise ValueError("Invalid sha {!r}".format(sha))
  845. def contains_loose(self, sha):
  846. """Check if a particular object is present by SHA1 and is loose."""
  847. return self._to_hexsha(sha) in self._data
  848. def contains_packed(self, sha):
  849. """Check if a particular object is present by SHA1 and is packed."""
  850. return False
  851. def __iter__(self):
  852. """Iterate over the SHAs that are present in this store."""
  853. return iter(self._data.keys())
  854. @property
  855. def packs(self):
  856. """List with pack objects."""
  857. return []
  858. def get_raw(self, name: ObjectID):
  859. """Obtain the raw text for an object.
  860. Args:
  861. name: sha for the object.
  862. Returns: tuple with numeric type and object contents.
  863. """
  864. obj = self[self._to_hexsha(name)]
  865. return obj.type_num, obj.as_raw_string()
  866. def __getitem__(self, name: ObjectID):
  867. return self._data[self._to_hexsha(name)].copy()
  868. def __delitem__(self, name: ObjectID):
  869. """Delete an object from this store, for testing only."""
  870. del self._data[self._to_hexsha(name)]
  871. def add_object(self, obj):
  872. """Add a single object to this object store."""
  873. self._data[obj.id] = obj.copy()
  874. def add_objects(self, objects, progress=None):
  875. """Add a set of objects to this object store.
  876. Args:
  877. objects: Iterable over a list of (object, path) tuples
  878. """
  879. for obj, path in objects:
  880. self.add_object(obj)
  881. def add_pack(self):
  882. """Add a new pack to this object store.
  883. Because this object store doesn't support packs, we extract and add the
  884. individual objects.
  885. Returns: Fileobject to write to and a commit function to
  886. call when the pack is finished.
  887. """
  888. from tempfile import SpooledTemporaryFile
  889. f = SpooledTemporaryFile(
  890. max_size=PACK_SPOOL_FILE_MAX_SIZE, prefix='incoming-')
  891. def commit():
  892. size = f.tell()
  893. if size > 0:
  894. f.seek(0)
  895. p = PackData.from_file(f, size)
  896. for obj in PackInflater.for_pack_data(p, self.get_raw):
  897. self.add_object(obj)
  898. p.close()
  899. else:
  900. f.close()
  901. def abort():
  902. f.close()
  903. return f, commit, abort
  904. def add_thin_pack(self, read_all, read_some, progress=None):
  905. """Add a new thin pack to this object store.
  906. Thin packs are packs that contain deltas with parents that exist
  907. outside the pack. Because this object store doesn't support packs, we
  908. extract and add the individual objects.
  909. Args:
  910. read_all: Read function that blocks until the number of
  911. requested bytes are read.
  912. read_some: Read function that returns at least one byte, but may
  913. not return the number of bytes requested.
  914. """
  915. f, commit, abort = self.add_pack()
  916. try:
  917. copier = PackStreamCopier(read_all, read_some, f)
  918. copier.verify()
  919. except BaseException:
  920. abort()
  921. raise
  922. else:
  923. commit()
  924. class ObjectIterator(Protocol):
  925. """Interface for iterating over objects."""
  926. def iterobjects(self) -> Iterator[ShaFile]:
  927. raise NotImplementedError(self.iterobjects)
  928. def tree_lookup_path(lookup_obj, root_sha, path):
  929. """Look up an object in a Git tree.
  930. Args:
  931. lookup_obj: Callback for retrieving object by SHA1
  932. root_sha: SHA1 of the root tree
  933. path: Path to lookup
  934. Returns: A tuple of (mode, SHA) of the resulting path.
  935. """
  936. tree = lookup_obj(root_sha)
  937. if not isinstance(tree, Tree):
  938. raise NotTreeError(root_sha)
  939. return tree.lookup_path(lookup_obj, path)
  940. def _collect_filetree_revs(obj_store: ObjectContainer, tree_sha: ObjectID, kset: Set[ObjectID]) -> None:
  941. """Collect SHA1s of files and directories for specified tree.
  942. Args:
  943. obj_store: Object store to get objects by SHA from
  944. tree_sha: tree reference to walk
  945. kset: set to fill with references to files and directories
  946. """
  947. filetree = obj_store[tree_sha]
  948. assert isinstance(filetree, Tree)
  949. for name, mode, sha in filetree.iteritems():
  950. if not S_ISGITLINK(mode) and sha not in kset:
  951. kset.add(sha)
  952. if stat.S_ISDIR(mode):
  953. _collect_filetree_revs(obj_store, sha, kset)
  954. def _split_commits_and_tags(obj_store: ObjectContainer, lst, *, ignore_unknown=False) -> Tuple[Set[bytes], Set[bytes], Set[bytes]]:
  955. """Split object id list into three lists with commit, tag, and other SHAs.
  956. Commits referenced by tags are included into commits
  957. list as well. Only SHA1s known in this repository will get
  958. through, and unless ignore_unknown argument is True, KeyError
  959. is thrown for SHA1 missing in the repository
  960. Args:
  961. obj_store: Object store to get objects by SHA1 from
  962. lst: Collection of commit and tag SHAs
  963. ignore_unknown: True to skip SHA1 missing in the repository
  964. silently.
  965. Returns: A tuple of (commits, tags, others) SHA1s
  966. """
  967. commits: Set[bytes] = set()
  968. tags: Set[bytes] = set()
  969. others: Set[bytes] = set()
  970. for e in lst:
  971. try:
  972. o = obj_store[e]
  973. except KeyError:
  974. if not ignore_unknown:
  975. raise
  976. else:
  977. if isinstance(o, Commit):
  978. commits.add(e)
  979. elif isinstance(o, Tag):
  980. tags.add(e)
  981. tagged = o.object[1]
  982. c, t, os = _split_commits_and_tags(
  983. obj_store, [tagged], ignore_unknown=ignore_unknown
  984. )
  985. commits |= c
  986. tags |= t
  987. others |= os
  988. else:
  989. others.add(e)
  990. return (commits, tags, others)
  991. class MissingObjectFinder:
  992. """Find the objects missing from another object store.
  993. Args:
  994. object_store: Object store containing at least all objects to be
  995. sent
  996. haves: SHA1s of commits not to send (already present in target)
  997. wants: SHA1s of commits to send
  998. progress: Optional function to report progress to.
  999. get_tagged: Function that returns a dict of pointed-to sha -> tag
  1000. sha for including tags.
  1001. get_parents: Optional function for getting the parents of a commit.
  1002. tagged: dict of pointed-to sha -> tag sha for including tags
  1003. """
  1004. def __init__(
  1005. self,
  1006. object_store,
  1007. haves,
  1008. wants,
  1009. *,
  1010. shallow=None,
  1011. progress=None,
  1012. get_tagged=None,
  1013. get_parents=lambda commit: commit.parents,
  1014. ):
  1015. self.object_store = object_store
  1016. if shallow is None:
  1017. shallow = set()
  1018. self._get_parents = get_parents
  1019. # process Commits and Tags differently
  1020. # Note, while haves may list commits/tags not available locally,
  1021. # and such SHAs would get filtered out by _split_commits_and_tags,
  1022. # wants shall list only known SHAs, and otherwise
  1023. # _split_commits_and_tags fails with KeyError
  1024. have_commits, have_tags, have_others = _split_commits_and_tags(
  1025. object_store, haves, ignore_unknown=True
  1026. )
  1027. want_commits, want_tags, want_others = _split_commits_and_tags(
  1028. object_store, wants, ignore_unknown=False
  1029. )
  1030. # all_ancestors is a set of commits that shall not be sent
  1031. # (complete repository up to 'haves')
  1032. all_ancestors = _collect_ancestors(
  1033. object_store,
  1034. have_commits, shallow=shallow, get_parents=self._get_parents
  1035. )[0]
  1036. # all_missing - complete set of commits between haves and wants
  1037. # common - commits from all_ancestors we hit into while
  1038. # traversing parent hierarchy of wants
  1039. missing_commits, common_commits = _collect_ancestors(
  1040. object_store,
  1041. want_commits,
  1042. all_ancestors,
  1043. shallow=shallow,
  1044. get_parents=self._get_parents,
  1045. )
  1046. self.remote_has: Set[bytes] = set()
  1047. # Now, fill sha_done with commits and revisions of
  1048. # files and directories known to be both locally
  1049. # and on target. Thus these commits and files
  1050. # won't get selected for fetch
  1051. for h in common_commits:
  1052. self.remote_has.add(h)
  1053. cmt = object_store[h]
  1054. _collect_filetree_revs(object_store, cmt.tree, self.remote_has)
  1055. # record tags we have as visited, too
  1056. for t in have_tags:
  1057. self.remote_has.add(t)
  1058. self.sha_done = set(self.remote_has)
  1059. # in fact, what we 'want' is commits, tags, and others
  1060. # we've found missing
  1061. self.objects_to_send = {
  1062. (w, None, Commit.type_num, False)
  1063. for w in missing_commits}
  1064. missing_tags = want_tags.difference(have_tags)
  1065. self.objects_to_send.update(
  1066. {(w, None, Tag.type_num, False)
  1067. for w in missing_tags})
  1068. missing_others = want_others.difference(have_others)
  1069. self.objects_to_send.update(
  1070. {(w, None, None, False)
  1071. for w in missing_others})
  1072. if progress is None:
  1073. self.progress = lambda x: None
  1074. else:
  1075. self.progress = progress
  1076. self._tagged = get_tagged and get_tagged() or {}
  1077. def get_remote_has(self):
  1078. return self.remote_has
  1079. def add_todo(self, entries: Iterable[Tuple[ObjectID, Optional[bytes], Optional[int], bool]]):
  1080. self.objects_to_send.update([e for e in entries if not e[0] in self.sha_done])
  1081. def __next__(self) -> Tuple[bytes, PackHint]:
  1082. while True:
  1083. if not self.objects_to_send:
  1084. self.progress(("counting objects: %d, done.\n" % len(self.sha_done)).encode("ascii"))
  1085. raise StopIteration
  1086. (sha, name, type_num, leaf) = self.objects_to_send.pop()
  1087. if sha not in self.sha_done:
  1088. break
  1089. if not leaf:
  1090. o = self.object_store[sha]
  1091. if isinstance(o, Commit):
  1092. self.add_todo([(o.tree, b"", Tree.type_num, False)])
  1093. elif isinstance(o, Tree):
  1094. self.add_todo(
  1095. [
  1096. (s, n, (Blob.type_num if stat.S_ISREG(m) else Tree.type_num),
  1097. not stat.S_ISDIR(m))
  1098. for n, m, s in o.iteritems()
  1099. if not S_ISGITLINK(m)
  1100. ]
  1101. )
  1102. elif isinstance(o, Tag):
  1103. self.add_todo([(o.object[1], None, o.object[0].type_num, False)])
  1104. if sha in self._tagged:
  1105. self.add_todo([(self._tagged[sha], None, None, True)])
  1106. self.sha_done.add(sha)
  1107. if len(self.sha_done) % 1000 == 0:
  1108. self.progress(("counting objects: %d\r" % len(self.sha_done)).encode("ascii"))
  1109. return (sha, (type_num, name))
  1110. def __iter__(self):
  1111. return self
  1112. class ObjectStoreGraphWalker:
  1113. """Graph walker that finds what commits are missing from an object store.
  1114. Attributes:
  1115. heads: Revisions without descendants in the local repo
  1116. get_parents: Function to retrieve parents in the local repo
  1117. """
  1118. def __init__(self, local_heads, get_parents, shallow=None):
  1119. """Create a new instance.
  1120. Args:
  1121. local_heads: Heads to start search with
  1122. get_parents: Function for finding the parents of a SHA1.
  1123. """
  1124. self.heads = set(local_heads)
  1125. self.get_parents = get_parents
  1126. self.parents = {}
  1127. if shallow is None:
  1128. shallow = set()
  1129. self.shallow = shallow
  1130. def nak(self):
  1131. """Nothing in common was found."""
  1132. def ack(self, sha):
  1133. """Ack that a revision and its ancestors are present in the source."""
  1134. if len(sha) != 40:
  1135. raise ValueError("unexpected sha %r received" % sha)
  1136. ancestors = {sha}
  1137. # stop if we run out of heads to remove
  1138. while self.heads:
  1139. for a in ancestors:
  1140. if a in self.heads:
  1141. self.heads.remove(a)
  1142. # collect all ancestors
  1143. new_ancestors = set()
  1144. for a in ancestors:
  1145. ps = self.parents.get(a)
  1146. if ps is not None:
  1147. new_ancestors.update(ps)
  1148. self.parents[a] = None
  1149. # no more ancestors; stop
  1150. if not new_ancestors:
  1151. break
  1152. ancestors = new_ancestors
  1153. def next(self):
  1154. """Iterate over ancestors of heads in the target."""
  1155. if self.heads:
  1156. ret = self.heads.pop()
  1157. try:
  1158. ps = self.get_parents(ret)
  1159. except KeyError:
  1160. return None
  1161. self.parents[ret] = ps
  1162. self.heads.update([p for p in ps if p not in self.parents])
  1163. return ret
  1164. return None
  1165. __next__ = next
  1166. def commit_tree_changes(object_store, tree, changes):
  1167. """Commit a specified set of changes to a tree structure.
  1168. This will apply a set of changes on top of an existing tree, storing new
  1169. objects in object_store.
  1170. changes are a list of tuples with (path, mode, object_sha).
  1171. Paths can be both blobs and trees. See the mode and
  1172. object sha to None deletes the path.
  1173. This method works especially well if there are only a small
  1174. number of changes to a big tree. For a large number of changes
  1175. to a large tree, use e.g. commit_tree.
  1176. Args:
  1177. object_store: Object store to store new objects in
  1178. and retrieve old ones from.
  1179. tree: Original tree root
  1180. changes: changes to apply
  1181. Returns: New tree root object
  1182. """
  1183. # TODO(jelmer): Save up the objects and add them using .add_objects
  1184. # rather than with individual calls to .add_object.
  1185. nested_changes = {}
  1186. for (path, new_mode, new_sha) in changes:
  1187. try:
  1188. (dirname, subpath) = path.split(b"/", 1)
  1189. except ValueError:
  1190. if new_sha is None:
  1191. del tree[path]
  1192. else:
  1193. tree[path] = (new_mode, new_sha)
  1194. else:
  1195. nested_changes.setdefault(dirname, []).append((subpath, new_mode, new_sha))
  1196. for name, subchanges in nested_changes.items():
  1197. try:
  1198. orig_subtree = object_store[tree[name][1]]
  1199. except KeyError:
  1200. orig_subtree = Tree()
  1201. subtree = commit_tree_changes(object_store, orig_subtree, subchanges)
  1202. if len(subtree) == 0:
  1203. del tree[name]
  1204. else:
  1205. tree[name] = (stat.S_IFDIR, subtree.id)
  1206. object_store.add_object(tree)
  1207. return tree
  1208. class OverlayObjectStore(BaseObjectStore):
  1209. """Object store that can overlay multiple object stores."""
  1210. def __init__(self, bases, add_store=None):
  1211. self.bases = bases
  1212. self.add_store = add_store
  1213. def add_object(self, object):
  1214. if self.add_store is None:
  1215. raise NotImplementedError(self.add_object)
  1216. return self.add_store.add_object(object)
  1217. def add_objects(self, objects, progress=None):
  1218. if self.add_store is None:
  1219. raise NotImplementedError(self.add_object)
  1220. return self.add_store.add_objects(objects, progress)
  1221. @property
  1222. def packs(self):
  1223. ret = []
  1224. for b in self.bases:
  1225. ret.extend(b.packs)
  1226. return ret
  1227. def __iter__(self):
  1228. done = set()
  1229. for b in self.bases:
  1230. for o_id in b:
  1231. if o_id not in done:
  1232. yield o_id
  1233. done.add(o_id)
  1234. def iterobjects_subset(self, shas: Iterable[bytes], *, allow_missing: bool = False) -> Iterator[ShaFile]:
  1235. todo = set(shas)
  1236. for b in self.bases:
  1237. for o in b.iterobjects_subset(todo, allow_missing=True):
  1238. yield o
  1239. todo.remove(o.id)
  1240. if todo and not allow_missing:
  1241. raise KeyError(o.id)
  1242. def iter_unpacked_subset(self, shas: Iterable[bytes], *, include_comp=False, allow_missing: bool = False, convert_ofs_delta=True) -> Iterator[ShaFile]:
  1243. todo = set(shas)
  1244. for b in self.bases:
  1245. for o in b.iter_unpacked_subset(todo, include_comp=include_comp, allow_missing=True, convert_ofs_delta=convert_ofs_delta):
  1246. yield o
  1247. todo.remove(o.id)
  1248. if todo and not allow_missing:
  1249. raise KeyError(o.id)
  1250. def get_raw(self, sha_id):
  1251. for b in self.bases:
  1252. try:
  1253. return b.get_raw(sha_id)
  1254. except KeyError:
  1255. pass
  1256. raise KeyError(sha_id)
  1257. def contains_packed(self, sha):
  1258. for b in self.bases:
  1259. if b.contains_packed(sha):
  1260. return True
  1261. return False
  1262. def contains_loose(self, sha):
  1263. for b in self.bases:
  1264. if b.contains_loose(sha):
  1265. return True
  1266. return False
  1267. def read_packs_file(f):
  1268. """Yield the packs listed in a packs file."""
  1269. for line in f.read().splitlines():
  1270. if not line:
  1271. continue
  1272. (kind, name) = line.split(b" ", 1)
  1273. if kind != b"P":
  1274. continue
  1275. yield os.fsdecode(name)
  1276. class BucketBasedObjectStore(PackBasedObjectStore):
  1277. """Object store implementation that uses a bucket store like S3 as backend.
  1278. """
  1279. def _iter_loose_objects(self):
  1280. """Iterate over the SHAs of all loose objects."""
  1281. return iter([])
  1282. def _get_loose_object(self, sha):
  1283. return None
  1284. def _remove_loose_object(self, sha):
  1285. # Doesn't exist..
  1286. pass
  1287. def _remove_pack(self, name):
  1288. raise NotImplementedError(self._remove_pack)
  1289. def _iter_pack_names(self):
  1290. raise NotImplementedError(self._iter_pack_names)
  1291. def _get_pack(self, name):
  1292. raise NotImplementedError(self._get_pack)
  1293. def _update_pack_cache(self):
  1294. pack_files = set(self._iter_pack_names())
  1295. # Open newly appeared pack files
  1296. new_packs = []
  1297. for f in pack_files:
  1298. if f not in self._pack_cache:
  1299. pack = self._get_pack(f)
  1300. new_packs.append(pack)
  1301. self._pack_cache[f] = pack
  1302. # Remove disappeared pack files
  1303. for f in set(self._pack_cache) - pack_files:
  1304. self._pack_cache.pop(f).close()
  1305. return new_packs
  1306. def _upload_pack(self, basename, pack_file, index_file):
  1307. raise NotImplementedError
  1308. def add_pack(self):
  1309. """Add a new pack to this object store.
  1310. Returns: Fileobject to write to, a commit function to
  1311. call when the pack is finished and an abort
  1312. function.
  1313. """
  1314. import tempfile
  1315. pf = tempfile.SpooledTemporaryFile(
  1316. max_size=PACK_SPOOL_FILE_MAX_SIZE, prefix='incoming-')
  1317. def commit():
  1318. if pf.tell() == 0:
  1319. pf.close()
  1320. return None
  1321. pf.seek(0)
  1322. p = PackData(pf.name, pf)
  1323. entries = p.sorted_entries()
  1324. basename = iter_sha1(entry[0] for entry in entries).decode('ascii')
  1325. idxf = tempfile.SpooledTemporaryFile(
  1326. max_size=PACK_SPOOL_FILE_MAX_SIZE, prefix='incoming-')
  1327. checksum = p.get_stored_checksum()
  1328. write_pack_index(idxf, entries, checksum)
  1329. idxf.seek(0)
  1330. idx = load_pack_index_file(basename + '.idx', idxf)
  1331. for pack in self.packs:
  1332. if pack.get_stored_checksum() == p.get_stored_checksum():
  1333. p.close()
  1334. idx.close()
  1335. return pack
  1336. pf.seek(0)
  1337. idxf.seek(0)
  1338. self._upload_pack(basename, pf, idxf)
  1339. final_pack = Pack.from_objects(p, idx)
  1340. self._add_cached_pack(basename, final_pack)
  1341. return final_pack
  1342. return pf, commit, pf.close
  1343. def _collect_ancestors(
  1344. store: ObjectContainer,
  1345. heads,
  1346. common=frozenset(),
  1347. shallow=frozenset(),
  1348. get_parents=lambda commit: commit.parents,
  1349. ):
  1350. """Collect all ancestors of heads up to (excluding) those in common.
  1351. Args:
  1352. heads: commits to start from
  1353. common: commits to end at, or empty set to walk repository
  1354. completely
  1355. get_parents: Optional function for getting the parents of a
  1356. commit.
  1357. Returns: a tuple (A, B) where A - all commits reachable
  1358. from heads but not present in common, B - common (shared) elements
  1359. that are directly reachable from heads
  1360. """
  1361. bases = set()
  1362. commits = set()
  1363. queue = []
  1364. queue.extend(heads)
  1365. while queue:
  1366. e = queue.pop(0)
  1367. if e in common:
  1368. bases.add(e)
  1369. elif e not in commits:
  1370. commits.add(e)
  1371. if e in shallow:
  1372. continue
  1373. cmt = store[e]
  1374. queue.extend(get_parents(cmt))
  1375. return (commits, bases)
  1376. def iter_tree_contents(
  1377. store: ObjectContainer, tree_id: Optional[ObjectID], *, include_trees: bool = False):
  1378. """Iterate the contents of a tree and all subtrees.
  1379. Iteration is depth-first pre-order, as in e.g. os.walk.
  1380. Args:
  1381. tree_id: SHA1 of the tree.
  1382. include_trees: If True, include tree objects in the iteration.
  1383. Returns: Iterator over TreeEntry namedtuples for all the objects in a
  1384. tree.
  1385. """
  1386. if tree_id is None:
  1387. return
  1388. # This could be fairly easily generalized to >2 trees if we find a use
  1389. # case.
  1390. todo = [TreeEntry(b"", stat.S_IFDIR, tree_id)]
  1391. while todo:
  1392. entry = todo.pop()
  1393. if stat.S_ISDIR(entry.mode):
  1394. extra = []
  1395. tree = store[entry.sha]
  1396. assert isinstance(tree, Tree)
  1397. for subentry in tree.iteritems(name_order=True):
  1398. extra.append(subentry.in_path(entry.path))
  1399. todo.extend(reversed(extra))
  1400. if not stat.S_ISDIR(entry.mode) or include_trees:
  1401. yield entry
  1402. def peel_sha(store: ObjectContainer, sha: bytes) -> Tuple[ShaFile, ShaFile]:
  1403. """Peel all tags from a SHA.
  1404. Args:
  1405. sha: The object SHA to peel.
  1406. Returns: The fully-peeled SHA1 of a tag object, after peeling all
  1407. intermediate tags; if the original ref does not point to a tag,
  1408. this will equal the original SHA1.
  1409. """
  1410. unpeeled = obj = store[sha]
  1411. obj_class = object_class(obj.type_name)
  1412. while obj_class is Tag:
  1413. assert isinstance(obj, Tag)
  1414. obj_class, sha = obj.object
  1415. obj = store[sha]
  1416. return unpeeled, obj