object_store.py 59 KB

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