object_store.py 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255
  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 time
  28. import warnings
  29. from collections.abc import Iterable, Iterator, Sequence
  30. from contextlib import suppress
  31. from io import BytesIO
  32. from typing import (
  33. Callable,
  34. Optional,
  35. Protocol,
  36. Union,
  37. cast,
  38. )
  39. from .errors import NotTreeError
  40. from .file import GitFile
  41. from .objects import (
  42. S_ISGITLINK,
  43. ZERO_SHA,
  44. Blob,
  45. Commit,
  46. ObjectID,
  47. ShaFile,
  48. Tag,
  49. Tree,
  50. TreeEntry,
  51. hex_to_filename,
  52. hex_to_sha,
  53. object_class,
  54. sha_to_hex,
  55. valid_hexsha,
  56. )
  57. from .pack import (
  58. PACK_SPOOL_FILE_MAX_SIZE,
  59. ObjectContainer,
  60. Pack,
  61. PackData,
  62. PackedObjectContainer,
  63. PackFileDisappeared,
  64. PackHint,
  65. PackIndexer,
  66. PackInflater,
  67. PackStreamCopier,
  68. UnpackedObject,
  69. extend_pack,
  70. full_unpacked_object,
  71. generate_unpacked_objects,
  72. iter_sha1,
  73. load_pack_index_file,
  74. pack_objects_to_data,
  75. write_pack_data,
  76. write_pack_index,
  77. )
  78. from .protocol import DEPTH_INFINITE
  79. from .refs import PEELED_TAG_SUFFIX, Ref
  80. INFODIR = "info"
  81. PACKDIR = "pack"
  82. # use permissions consistent with Git; just readable by everyone
  83. # TODO: should packs also be non-writable on Windows? if so, that
  84. # would requite some rather significant adjustments to the test suite
  85. PACK_MODE = 0o444 if sys.platform != "win32" else 0o644
  86. # Grace period for cleaning up temporary pack files (in seconds)
  87. # Matches git's default of 2 weeks
  88. DEFAULT_TEMPFILE_GRACE_PERIOD = 14 * 24 * 60 * 60 # 2 weeks
  89. def find_shallow(store, heads, depth):
  90. """Find shallow commits according to a given depth.
  91. Args:
  92. store: An ObjectStore for looking up objects.
  93. heads: Iterable of head SHAs to start walking from.
  94. depth: The depth of ancestors to include. A depth of one includes
  95. only the heads themselves.
  96. Returns: A tuple of (shallow, not_shallow), sets of SHAs that should be
  97. considered shallow and unshallow according to the arguments. Note that
  98. these sets may overlap if a commit is reachable along multiple paths.
  99. """
  100. parents = {}
  101. commit_graph = store.get_commit_graph()
  102. def get_parents(sha):
  103. result = parents.get(sha, None)
  104. if not result:
  105. # Try to use commit graph first if available
  106. if commit_graph:
  107. graph_parents = commit_graph.get_parents(sha)
  108. if graph_parents is not None:
  109. result = graph_parents
  110. parents[sha] = result
  111. return result
  112. # Fall back to loading the object
  113. result = store[sha].parents
  114. parents[sha] = result
  115. return result
  116. todo = [] # stack of (sha, depth)
  117. for head_sha in heads:
  118. obj = store[head_sha]
  119. # Peel tags if necessary
  120. while isinstance(obj, Tag):
  121. _, sha = obj.object
  122. obj = store[sha]
  123. if isinstance(obj, Commit):
  124. todo.append((obj.id, 1))
  125. not_shallow = set()
  126. shallow = set()
  127. while todo:
  128. sha, cur_depth = todo.pop()
  129. if cur_depth < depth:
  130. not_shallow.add(sha)
  131. new_depth = cur_depth + 1
  132. todo.extend((p, new_depth) for p in get_parents(sha))
  133. else:
  134. shallow.add(sha)
  135. return shallow, not_shallow
  136. def get_depth(
  137. store,
  138. head,
  139. get_parents=lambda commit: commit.parents,
  140. max_depth=None,
  141. ):
  142. """Return the current available depth for the given head.
  143. For commits with multiple parents, the largest possible depth will be
  144. returned.
  145. Args:
  146. head: commit to start from
  147. get_parents: optional function for getting the parents of a commit
  148. max_depth: maximum depth to search
  149. """
  150. if head not in store:
  151. return 0
  152. current_depth = 1
  153. queue = [(head, current_depth)]
  154. commit_graph = store.get_commit_graph()
  155. while queue and (max_depth is None or current_depth < max_depth):
  156. e, depth = queue.pop(0)
  157. current_depth = max(current_depth, depth)
  158. # Try to use commit graph for parent lookup if available
  159. parents = None
  160. if commit_graph:
  161. parents = commit_graph.get_parents(e)
  162. if parents is None:
  163. # Fall back to loading the object
  164. cmt = store[e]
  165. if isinstance(cmt, Tag):
  166. _cls, sha = cmt.object
  167. cmt = store[sha]
  168. parents = get_parents(cmt)
  169. queue.extend((parent, depth + 1) for parent in parents if parent in store)
  170. return current_depth
  171. class PackContainer(Protocol):
  172. def add_pack(self) -> tuple[BytesIO, Callable[[], None], Callable[[], None]]:
  173. """Add a new pack."""
  174. class BaseObjectStore:
  175. """Object store interface."""
  176. def determine_wants_all(
  177. self, refs: dict[Ref, ObjectID], depth: Optional[int] = None
  178. ) -> list[ObjectID]:
  179. def _want_deepen(sha):
  180. if not depth:
  181. return False
  182. if depth == DEPTH_INFINITE:
  183. return True
  184. return depth > self._get_depth(sha)
  185. return [
  186. sha
  187. for (ref, sha) in refs.items()
  188. if (sha not in self or _want_deepen(sha))
  189. and not ref.endswith(PEELED_TAG_SUFFIX)
  190. and not sha == ZERO_SHA
  191. ]
  192. def contains_loose(self, sha) -> bool:
  193. """Check if a particular object is present by SHA1 and is loose."""
  194. raise NotImplementedError(self.contains_loose)
  195. def __contains__(self, sha1: bytes) -> bool:
  196. """Check if a particular object is present by SHA1.
  197. This method makes no distinction between loose and packed objects.
  198. """
  199. return self.contains_loose(sha1)
  200. @property
  201. def packs(self):
  202. """Iterable of pack objects."""
  203. raise NotImplementedError
  204. def get_raw(self, name) -> tuple[int, bytes]:
  205. """Obtain the raw text for an object.
  206. Args:
  207. name: sha for the object.
  208. Returns: tuple with numeric type and object contents.
  209. """
  210. raise NotImplementedError(self.get_raw)
  211. def __getitem__(self, sha1: ObjectID) -> ShaFile:
  212. """Obtain an object by SHA1."""
  213. type_num, uncomp = self.get_raw(sha1)
  214. return ShaFile.from_raw_string(type_num, uncomp, sha=sha1)
  215. def __iter__(self):
  216. """Iterate over the SHAs that are present in this store."""
  217. raise NotImplementedError(self.__iter__)
  218. def add_object(self, obj) -> None:
  219. """Add a single object to this object store."""
  220. raise NotImplementedError(self.add_object)
  221. def add_objects(self, objects, progress=None) -> None:
  222. """Add a set of objects to this object store.
  223. Args:
  224. objects: Iterable over a list of (object, path) tuples
  225. """
  226. raise NotImplementedError(self.add_objects)
  227. def tree_changes(
  228. self,
  229. source,
  230. target,
  231. want_unchanged=False,
  232. include_trees=False,
  233. change_type_same=False,
  234. rename_detector=None,
  235. paths=None,
  236. ):
  237. """Find the differences between the contents of two trees.
  238. Args:
  239. source: SHA1 of the source tree
  240. target: SHA1 of the target tree
  241. want_unchanged: Whether unchanged files should be reported
  242. include_trees: Whether to include trees
  243. change_type_same: Whether to report files changing
  244. type in the same entry.
  245. rename_detector: RenameDetector object for detecting renames.
  246. paths: Optional list of paths to filter to (as bytes).
  247. Returns: Iterator over tuples with
  248. (oldpath, newpath), (oldmode, newmode), (oldsha, newsha)
  249. """
  250. from .diff_tree import tree_changes
  251. for change in tree_changes(
  252. self,
  253. source,
  254. target,
  255. want_unchanged=want_unchanged,
  256. include_trees=include_trees,
  257. change_type_same=change_type_same,
  258. rename_detector=rename_detector,
  259. paths=paths,
  260. ):
  261. yield (
  262. (change.old.path, change.new.path),
  263. (change.old.mode, change.new.mode),
  264. (change.old.sha, change.new.sha),
  265. )
  266. def iter_tree_contents(self, tree_id, include_trees=False):
  267. """Iterate the contents of a tree and all subtrees.
  268. Iteration is depth-first pre-order, as in e.g. os.walk.
  269. Args:
  270. tree_id: SHA1 of the tree.
  271. include_trees: If True, include tree objects in the iteration.
  272. Returns: Iterator over TreeEntry namedtuples for all the objects in a
  273. tree.
  274. """
  275. warnings.warn(
  276. "Please use dulwich.object_store.iter_tree_contents",
  277. DeprecationWarning,
  278. stacklevel=2,
  279. )
  280. return iter_tree_contents(self, tree_id, include_trees=include_trees)
  281. def iterobjects_subset(
  282. self, shas: Iterable[bytes], *, allow_missing: bool = False
  283. ) -> Iterator[ShaFile]:
  284. for sha in shas:
  285. try:
  286. yield self[sha]
  287. except KeyError:
  288. if not allow_missing:
  289. raise
  290. def find_missing_objects(
  291. self,
  292. haves,
  293. wants,
  294. shallow=None,
  295. progress=None,
  296. get_tagged=None,
  297. get_parents=lambda commit: commit.parents,
  298. ):
  299. """Find the missing objects required for a set of revisions.
  300. Args:
  301. haves: Iterable over SHAs already in common.
  302. wants: Iterable over SHAs of objects to fetch.
  303. shallow: Set of shallow commit SHA1s to skip
  304. progress: Simple progress function that will be called with
  305. updated progress strings.
  306. get_tagged: Function that returns a dict of pointed-to sha ->
  307. tag sha for including tags.
  308. get_parents: Optional function for getting the parents of a
  309. commit.
  310. Returns: Iterator over (sha, path) pairs.
  311. """
  312. warnings.warn("Please use MissingObjectFinder(store)", DeprecationWarning)
  313. finder = MissingObjectFinder(
  314. self,
  315. haves=haves,
  316. wants=wants,
  317. shallow=shallow,
  318. progress=progress,
  319. get_tagged=get_tagged,
  320. get_parents=get_parents,
  321. )
  322. return iter(finder)
  323. def find_common_revisions(self, graphwalker):
  324. """Find which revisions this store has in common using graphwalker.
  325. Args:
  326. graphwalker: A graphwalker object.
  327. Returns: List of SHAs that are in common
  328. """
  329. haves = []
  330. sha = next(graphwalker)
  331. while sha:
  332. if sha in self:
  333. haves.append(sha)
  334. graphwalker.ack(sha)
  335. sha = next(graphwalker)
  336. return haves
  337. def generate_pack_data(
  338. self, have, want, shallow=None, progress=None, ofs_delta=True
  339. ) -> tuple[int, Iterator[UnpackedObject]]:
  340. """Generate pack data objects for a set of wants/haves.
  341. Args:
  342. have: List of SHA1s of objects that should not be sent
  343. want: List of SHA1s of objects that should be sent
  344. shallow: Set of shallow commit SHA1s to skip
  345. ofs_delta: Whether OFS deltas can be included
  346. progress: Optional progress reporting method
  347. """
  348. # Note that the pack-specific implementation below is more efficient,
  349. # as it reuses deltas
  350. missing_objects = MissingObjectFinder(
  351. self, haves=have, wants=want, shallow=shallow, progress=progress
  352. )
  353. object_ids = list(missing_objects)
  354. return pack_objects_to_data(
  355. [(self[oid], path) for oid, path in object_ids],
  356. ofs_delta=ofs_delta,
  357. progress=progress,
  358. )
  359. def peel_sha(self, sha):
  360. """Peel all tags from a SHA.
  361. Args:
  362. sha: The object SHA to peel.
  363. Returns: The fully-peeled SHA1 of a tag object, after peeling all
  364. intermediate tags; if the original ref does not point to a tag,
  365. this will equal the original SHA1.
  366. """
  367. warnings.warn(
  368. "Please use dulwich.object_store.peel_sha()",
  369. DeprecationWarning,
  370. stacklevel=2,
  371. )
  372. return peel_sha(self, sha)[1]
  373. def _get_depth(
  374. self,
  375. head,
  376. get_parents=lambda commit: commit.parents,
  377. max_depth=None,
  378. ):
  379. """Return the current available depth for the given head.
  380. For commits with multiple parents, the largest possible depth will be
  381. returned.
  382. Args:
  383. head: commit to start from
  384. get_parents: optional function for getting the parents of a commit
  385. max_depth: maximum depth to search
  386. """
  387. return get_depth(self, head, get_parents=get_parents, max_depth=max_depth)
  388. def close(self) -> None:
  389. """Close any files opened by this object store."""
  390. # Default implementation is a NO-OP
  391. def prune(self, grace_period: Optional[int] = None) -> None:
  392. """Prune/clean up this object store.
  393. This includes removing orphaned temporary files and other
  394. housekeeping tasks. Default implementation is a NO-OP.
  395. Args:
  396. grace_period: Grace period in seconds for removing temporary files.
  397. If None, uses the default grace period.
  398. """
  399. # Default implementation is a NO-OP
  400. def iter_prefix(self, prefix: bytes) -> Iterator[ObjectID]:
  401. """Iterate over all SHA1s that start with a given prefix.
  402. The default implementation is a naive iteration over all objects.
  403. However, subclasses may override this method with more efficient
  404. implementations.
  405. """
  406. for sha in self:
  407. if sha.startswith(prefix):
  408. yield sha
  409. def get_commit_graph(self):
  410. """Get the commit graph for this object store.
  411. Returns:
  412. CommitGraph object if available, None otherwise
  413. """
  414. return None
  415. def write_commit_graph(self, refs=None, reachable=True) -> None:
  416. """Write a commit graph file for this object store.
  417. Args:
  418. refs: List of refs to include. If None, includes all refs from object store.
  419. reachable: If True, includes all commits reachable from refs.
  420. If False, only includes the direct ref targets.
  421. Note:
  422. Default implementation does nothing. Subclasses should override
  423. this method to provide commit graph writing functionality.
  424. """
  425. raise NotImplementedError(self.write_commit_graph)
  426. def get_object_mtime(self, sha):
  427. """Get the modification time of an object.
  428. Args:
  429. sha: SHA1 of the object
  430. Returns:
  431. Modification time as seconds since epoch
  432. Raises:
  433. KeyError: if the object is not found
  434. """
  435. # Default implementation raises KeyError
  436. # Subclasses should override to provide actual mtime
  437. raise KeyError(sha)
  438. class PackBasedObjectStore(BaseObjectStore, PackedObjectContainer):
  439. def __init__(self, pack_compression_level=-1, pack_index_version=None) -> None:
  440. self._pack_cache: dict[str, Pack] = {}
  441. self.pack_compression_level = pack_compression_level
  442. self.pack_index_version = pack_index_version
  443. def add_pack(self) -> tuple[BytesIO, Callable[[], None], Callable[[], None]]:
  444. """Add a new pack to this object store."""
  445. raise NotImplementedError(self.add_pack)
  446. def add_pack_data(
  447. self, count: int, unpacked_objects: Iterator[UnpackedObject], progress=None
  448. ) -> None:
  449. """Add pack data to this object store.
  450. Args:
  451. count: Number of items to add
  452. """
  453. if count == 0:
  454. # Don't bother writing an empty pack file
  455. return
  456. f, commit, abort = self.add_pack()
  457. try:
  458. write_pack_data(
  459. f.write,
  460. unpacked_objects,
  461. num_records=count,
  462. progress=progress,
  463. compression_level=self.pack_compression_level,
  464. )
  465. except BaseException:
  466. abort()
  467. raise
  468. else:
  469. return commit()
  470. @property
  471. def alternates(self):
  472. return []
  473. def contains_packed(self, sha) -> bool:
  474. """Check if a particular object is present by SHA1 and is packed.
  475. This does not check alternates.
  476. """
  477. for pack in self.packs:
  478. try:
  479. if sha in pack:
  480. return True
  481. except PackFileDisappeared:
  482. pass
  483. return False
  484. def __contains__(self, sha) -> bool:
  485. """Check if a particular object is present by SHA1.
  486. This method makes no distinction between loose and packed objects.
  487. """
  488. if self.contains_packed(sha) or self.contains_loose(sha):
  489. return True
  490. for alternate in self.alternates:
  491. if sha in alternate:
  492. return True
  493. return False
  494. def _add_cached_pack(self, base_name, pack) -> None:
  495. """Add a newly appeared pack to the cache by path."""
  496. prev_pack = self._pack_cache.get(base_name)
  497. if prev_pack is not pack:
  498. self._pack_cache[base_name] = pack
  499. if prev_pack:
  500. prev_pack.close()
  501. def generate_pack_data(
  502. self, have, want, shallow=None, progress=None, ofs_delta=True
  503. ) -> tuple[int, Iterator[UnpackedObject]]:
  504. """Generate pack data objects for a set of wants/haves.
  505. Args:
  506. have: List of SHA1s of objects that should not be sent
  507. want: List of SHA1s of objects that should be sent
  508. shallow: Set of shallow commit SHA1s to skip
  509. ofs_delta: Whether OFS deltas can be included
  510. progress: Optional progress reporting method
  511. """
  512. missing_objects = MissingObjectFinder(
  513. self, haves=have, wants=want, shallow=shallow, progress=progress
  514. )
  515. remote_has = missing_objects.get_remote_has()
  516. object_ids = list(missing_objects)
  517. return len(object_ids), generate_unpacked_objects(
  518. cast(PackedObjectContainer, self),
  519. object_ids,
  520. progress=progress,
  521. ofs_delta=ofs_delta,
  522. other_haves=remote_has,
  523. )
  524. def _clear_cached_packs(self) -> None:
  525. pack_cache = self._pack_cache
  526. self._pack_cache = {}
  527. while pack_cache:
  528. (name, pack) = pack_cache.popitem()
  529. pack.close()
  530. def _iter_cached_packs(self):
  531. return self._pack_cache.values()
  532. def _update_pack_cache(self) -> list[Pack]:
  533. raise NotImplementedError(self._update_pack_cache)
  534. def close(self) -> None:
  535. self._clear_cached_packs()
  536. @property
  537. def packs(self):
  538. """List with pack objects."""
  539. return list(self._iter_cached_packs()) + list(self._update_pack_cache())
  540. def count_pack_files(self) -> int:
  541. """Count the number of pack files.
  542. Returns:
  543. Number of pack files (excluding those with .keep files)
  544. """
  545. count = 0
  546. for pack in self.packs:
  547. # Check if there's a .keep file for this pack
  548. keep_path = pack._basename + ".keep"
  549. if not os.path.exists(keep_path):
  550. count += 1
  551. return count
  552. def _iter_alternate_objects(self):
  553. """Iterate over the SHAs of all the objects in alternate stores."""
  554. for alternate in self.alternates:
  555. yield from alternate
  556. def _iter_loose_objects(self):
  557. """Iterate over the SHAs of all loose objects."""
  558. raise NotImplementedError(self._iter_loose_objects)
  559. def _get_loose_object(self, sha) -> Optional[ShaFile]:
  560. raise NotImplementedError(self._get_loose_object)
  561. def delete_loose_object(self, sha) -> None:
  562. """Delete a loose object.
  563. This method only handles loose objects. For packed objects,
  564. use repack(exclude=...) to exclude them during repacking.
  565. """
  566. raise NotImplementedError(self.delete_loose_object)
  567. def _remove_pack(self, name) -> None:
  568. raise NotImplementedError(self._remove_pack)
  569. def pack_loose_objects(self):
  570. """Pack loose objects.
  571. Returns: Number of objects packed
  572. """
  573. objects = set()
  574. for sha in self._iter_loose_objects():
  575. objects.add((self._get_loose_object(sha), None))
  576. self.add_objects(list(objects))
  577. for obj, path in objects:
  578. self.delete_loose_object(obj.id)
  579. return len(objects)
  580. def repack(self, exclude=None):
  581. """Repack the packs in this repository.
  582. Note that this implementation is fairly naive and currently keeps all
  583. objects in memory while it repacks.
  584. Args:
  585. exclude: Optional set of object SHAs to exclude from repacking
  586. """
  587. if exclude is None:
  588. exclude = set()
  589. loose_objects = set()
  590. excluded_loose_objects = set()
  591. for sha in self._iter_loose_objects():
  592. if sha not in exclude:
  593. loose_objects.add(self._get_loose_object(sha))
  594. else:
  595. excluded_loose_objects.add(sha)
  596. objects = {(obj, None) for obj in loose_objects}
  597. old_packs = {p.name(): p for p in self.packs}
  598. for name, pack in old_packs.items():
  599. objects.update(
  600. (obj, None) for obj in pack.iterobjects() if obj.id not in exclude
  601. )
  602. # Only create a new pack if there are objects to pack
  603. if objects:
  604. # The name of the consolidated pack might match the name of a
  605. # pre-existing pack. Take care not to remove the newly created
  606. # consolidated pack.
  607. consolidated = self.add_objects(objects)
  608. old_packs.pop(consolidated.name(), None)
  609. # Delete loose objects that were packed
  610. for obj in loose_objects:
  611. self.delete_loose_object(obj.id)
  612. # Delete excluded loose objects
  613. for sha in excluded_loose_objects:
  614. self.delete_loose_object(sha)
  615. for name, pack in old_packs.items():
  616. self._remove_pack(pack)
  617. self._update_pack_cache()
  618. return len(objects)
  619. def __iter__(self):
  620. """Iterate over the SHAs that are present in this store."""
  621. self._update_pack_cache()
  622. for pack in self._iter_cached_packs():
  623. try:
  624. yield from pack
  625. except PackFileDisappeared:
  626. pass
  627. yield from self._iter_loose_objects()
  628. yield from self._iter_alternate_objects()
  629. def contains_loose(self, sha):
  630. """Check if a particular object is present by SHA1 and is loose.
  631. This does not check alternates.
  632. """
  633. return self._get_loose_object(sha) is not None
  634. def get_raw(self, name):
  635. """Obtain the raw fulltext for an object.
  636. Args:
  637. name: sha for the object.
  638. Returns: tuple with numeric type and object contents.
  639. """
  640. if name == ZERO_SHA:
  641. raise KeyError(name)
  642. if len(name) == 40:
  643. sha = hex_to_sha(name)
  644. hexsha = name
  645. elif len(name) == 20:
  646. sha = name
  647. hexsha = None
  648. else:
  649. raise AssertionError(f"Invalid object name {name!r}")
  650. for pack in self._iter_cached_packs():
  651. try:
  652. return pack.get_raw(sha)
  653. except (KeyError, PackFileDisappeared):
  654. pass
  655. if hexsha is None:
  656. hexsha = sha_to_hex(name)
  657. ret = self._get_loose_object(hexsha)
  658. if ret is not None:
  659. return ret.type_num, ret.as_raw_string()
  660. # Maybe something else has added a pack with the object
  661. # in the mean time?
  662. for pack in self._update_pack_cache():
  663. try:
  664. return pack.get_raw(sha)
  665. except KeyError:
  666. pass
  667. for alternate in self.alternates:
  668. try:
  669. return alternate.get_raw(hexsha)
  670. except KeyError:
  671. pass
  672. raise KeyError(hexsha)
  673. def iter_unpacked_subset(
  674. self,
  675. shas: set[bytes],
  676. include_comp: bool = False,
  677. allow_missing: bool = False,
  678. convert_ofs_delta: bool = True,
  679. ) -> Iterator[UnpackedObject]:
  680. todo: set[bytes] = set(shas)
  681. for p in self._iter_cached_packs():
  682. for unpacked in p.iter_unpacked_subset(
  683. todo,
  684. include_comp=include_comp,
  685. allow_missing=True,
  686. convert_ofs_delta=convert_ofs_delta,
  687. ):
  688. yield unpacked
  689. hexsha = sha_to_hex(unpacked.sha())
  690. todo.remove(hexsha)
  691. # Maybe something else has added a pack with the object
  692. # in the mean time?
  693. for p in self._update_pack_cache():
  694. for unpacked in p.iter_unpacked_subset(
  695. todo,
  696. include_comp=include_comp,
  697. allow_missing=True,
  698. convert_ofs_delta=convert_ofs_delta,
  699. ):
  700. yield unpacked
  701. hexsha = sha_to_hex(unpacked.sha())
  702. todo.remove(hexsha)
  703. for alternate in self.alternates:
  704. for unpacked in alternate.iter_unpacked_subset(
  705. todo,
  706. include_comp=include_comp,
  707. allow_missing=True,
  708. convert_ofs_delta=convert_ofs_delta,
  709. ):
  710. yield unpacked
  711. hexsha = sha_to_hex(unpacked.sha())
  712. todo.remove(hexsha)
  713. def iterobjects_subset(
  714. self, shas: Iterable[bytes], *, allow_missing: bool = False
  715. ) -> Iterator[ShaFile]:
  716. todo: set[bytes] = set(shas)
  717. for p in self._iter_cached_packs():
  718. for o in p.iterobjects_subset(todo, allow_missing=True):
  719. yield o
  720. todo.remove(o.id)
  721. # Maybe something else has added a pack with the object
  722. # in the mean time?
  723. for p in self._update_pack_cache():
  724. for o in p.iterobjects_subset(todo, allow_missing=True):
  725. yield o
  726. todo.remove(o.id)
  727. for alternate in self.alternates:
  728. for o in alternate.iterobjects_subset(todo, allow_missing=True):
  729. yield o
  730. todo.remove(o.id)
  731. for oid in todo:
  732. o = self._get_loose_object(oid)
  733. if o is not None:
  734. yield o
  735. elif not allow_missing:
  736. raise KeyError(oid)
  737. def get_unpacked_object(
  738. self, sha1: bytes, *, include_comp: bool = False
  739. ) -> UnpackedObject:
  740. """Obtain the unpacked object.
  741. Args:
  742. sha1: sha for the object.
  743. """
  744. if sha1 == ZERO_SHA:
  745. raise KeyError(sha1)
  746. if len(sha1) == 40:
  747. sha = hex_to_sha(sha1)
  748. hexsha = sha1
  749. elif len(sha1) == 20:
  750. sha = sha1
  751. hexsha = None
  752. else:
  753. raise AssertionError(f"Invalid object sha1 {sha1!r}")
  754. for pack in self._iter_cached_packs():
  755. try:
  756. return pack.get_unpacked_object(sha, include_comp=include_comp)
  757. except (KeyError, PackFileDisappeared):
  758. pass
  759. if hexsha is None:
  760. hexsha = sha_to_hex(sha1)
  761. # Maybe something else has added a pack with the object
  762. # in the mean time?
  763. for pack in self._update_pack_cache():
  764. try:
  765. return pack.get_unpacked_object(sha, include_comp=include_comp)
  766. except KeyError:
  767. pass
  768. for alternate in self.alternates:
  769. try:
  770. return alternate.get_unpacked_object(hexsha, include_comp=include_comp)
  771. except KeyError:
  772. pass
  773. raise KeyError(hexsha)
  774. def add_objects(
  775. self,
  776. objects: Sequence[tuple[ShaFile, Optional[str]]],
  777. progress: Optional[Callable[[str], None]] = None,
  778. ) -> None:
  779. """Add a set of objects to this object store.
  780. Args:
  781. objects: Iterable over (object, path) tuples, should support
  782. __len__.
  783. Returns: Pack object of the objects written.
  784. """
  785. count = len(objects)
  786. record_iter = (full_unpacked_object(o) for (o, p) in objects)
  787. return self.add_pack_data(count, record_iter, progress=progress)
  788. class DiskObjectStore(PackBasedObjectStore):
  789. """Git-style object store that exists on disk."""
  790. path: Union[str, os.PathLike]
  791. pack_dir: Union[str, os.PathLike]
  792. def __init__(
  793. self,
  794. path: Union[str, os.PathLike],
  795. loose_compression_level=-1,
  796. pack_compression_level=-1,
  797. pack_index_version=None,
  798. ) -> None:
  799. """Open an object store.
  800. Args:
  801. path: Path of the object store.
  802. loose_compression_level: zlib compression level for loose objects
  803. pack_compression_level: zlib compression level for pack objects
  804. pack_index_version: pack index version to use (1, 2, or 3)
  805. """
  806. super().__init__(
  807. pack_compression_level=pack_compression_level,
  808. pack_index_version=pack_index_version,
  809. )
  810. self.path = path
  811. self.pack_dir = os.path.join(self.path, PACKDIR)
  812. self._alternates = None
  813. self.loose_compression_level = loose_compression_level
  814. self.pack_compression_level = pack_compression_level
  815. self.pack_index_version = pack_index_version
  816. # Commit graph support - lazy loaded
  817. self._commit_graph = None
  818. self._use_commit_graph = True # Default to true
  819. def __repr__(self) -> str:
  820. return f"<{self.__class__.__name__}({self.path!r})>"
  821. @classmethod
  822. def from_config(cls, path: Union[str, os.PathLike], config):
  823. try:
  824. default_compression_level = int(
  825. config.get((b"core",), b"compression").decode()
  826. )
  827. except KeyError:
  828. default_compression_level = -1
  829. try:
  830. loose_compression_level = int(
  831. config.get((b"core",), b"looseCompression").decode()
  832. )
  833. except KeyError:
  834. loose_compression_level = default_compression_level
  835. try:
  836. pack_compression_level = int(
  837. config.get((b"core",), "packCompression").decode()
  838. )
  839. except KeyError:
  840. pack_compression_level = default_compression_level
  841. try:
  842. pack_index_version = int(config.get((b"pack",), b"indexVersion").decode())
  843. except KeyError:
  844. pack_index_version = None
  845. # Read core.commitGraph setting
  846. use_commit_graph = config.get_boolean((b"core",), b"commitGraph", True)
  847. instance = cls(
  848. path, loose_compression_level, pack_compression_level, pack_index_version
  849. )
  850. instance._use_commit_graph = use_commit_graph
  851. return instance
  852. @property
  853. def alternates(self):
  854. if self._alternates is not None:
  855. return self._alternates
  856. self._alternates = []
  857. for path in self._read_alternate_paths():
  858. self._alternates.append(DiskObjectStore(path))
  859. return self._alternates
  860. def _read_alternate_paths(self):
  861. try:
  862. f = GitFile(os.path.join(self.path, INFODIR, "alternates"), "rb")
  863. except FileNotFoundError:
  864. return
  865. with f:
  866. for line in f.readlines():
  867. line = line.rstrip(b"\n")
  868. if line.startswith(b"#"):
  869. continue
  870. if os.path.isabs(line):
  871. yield os.fsdecode(line)
  872. else:
  873. yield os.fsdecode(os.path.join(os.fsencode(self.path), line))
  874. def add_alternate_path(self, path) -> None:
  875. """Add an alternate path to this object store."""
  876. try:
  877. os.mkdir(os.path.join(self.path, INFODIR))
  878. except FileExistsError:
  879. pass
  880. alternates_path = os.path.join(self.path, INFODIR, "alternates")
  881. with GitFile(alternates_path, "wb") as f:
  882. try:
  883. orig_f = open(alternates_path, "rb")
  884. except FileNotFoundError:
  885. pass
  886. else:
  887. with orig_f:
  888. f.write(orig_f.read())
  889. f.write(os.fsencode(path) + b"\n")
  890. if not os.path.isabs(path):
  891. path = os.path.join(self.path, path)
  892. self.alternates.append(DiskObjectStore(path))
  893. def _update_pack_cache(self):
  894. """Read and iterate over new pack files and cache them."""
  895. try:
  896. pack_dir_contents = os.listdir(self.pack_dir)
  897. except FileNotFoundError:
  898. self.close()
  899. return []
  900. pack_files = set()
  901. for name in pack_dir_contents:
  902. if name.startswith("pack-") and name.endswith(".pack"):
  903. # verify that idx exists first (otherwise the pack was not yet
  904. # fully written)
  905. idx_name = os.path.splitext(name)[0] + ".idx"
  906. if idx_name in pack_dir_contents:
  907. pack_name = name[: -len(".pack")]
  908. pack_files.add(pack_name)
  909. # Open newly appeared pack files
  910. new_packs = []
  911. for f in pack_files:
  912. if f not in self._pack_cache:
  913. pack = Pack(os.path.join(self.pack_dir, f))
  914. new_packs.append(pack)
  915. self._pack_cache[f] = pack
  916. # Remove disappeared pack files
  917. for f in set(self._pack_cache) - pack_files:
  918. self._pack_cache.pop(f).close()
  919. return new_packs
  920. def _get_shafile_path(self, sha):
  921. # Check from object dir
  922. return hex_to_filename(self.path, sha)
  923. def _iter_loose_objects(self):
  924. for base in os.listdir(self.path):
  925. if len(base) != 2:
  926. continue
  927. for rest in os.listdir(os.path.join(self.path, base)):
  928. sha = os.fsencode(base + rest)
  929. if not valid_hexsha(sha):
  930. continue
  931. yield sha
  932. def count_loose_objects(self) -> int:
  933. """Count the number of loose objects in the object store.
  934. Returns:
  935. Number of loose objects
  936. """
  937. count = 0
  938. if not os.path.exists(self.path):
  939. return 0
  940. for i in range(256):
  941. subdir = os.path.join(self.path, f"{i:02x}")
  942. try:
  943. count += len(
  944. [
  945. name
  946. for name in os.listdir(subdir)
  947. if len(name) == 38 # 40 - 2 for the prefix
  948. ]
  949. )
  950. except FileNotFoundError:
  951. # Directory may have been removed or is inaccessible
  952. continue
  953. return count
  954. def _get_loose_object(self, sha):
  955. path = self._get_shafile_path(sha)
  956. try:
  957. return ShaFile.from_path(path)
  958. except FileNotFoundError:
  959. return None
  960. def delete_loose_object(self, sha) -> None:
  961. os.remove(self._get_shafile_path(sha))
  962. def get_object_mtime(self, sha):
  963. """Get the modification time of an object.
  964. Args:
  965. sha: SHA1 of the object
  966. Returns:
  967. Modification time as seconds since epoch
  968. Raises:
  969. KeyError: if the object is not found
  970. """
  971. # First check if it's a loose object
  972. if self.contains_loose(sha):
  973. path = self._get_shafile_path(sha)
  974. try:
  975. return os.path.getmtime(path)
  976. except FileNotFoundError:
  977. pass
  978. # Check if it's in a pack file
  979. for pack in self.packs:
  980. try:
  981. if sha in pack:
  982. # Use the pack file's mtime for packed objects
  983. pack_path = pack._data_path
  984. try:
  985. return os.path.getmtime(pack_path)
  986. except (FileNotFoundError, AttributeError):
  987. pass
  988. except PackFileDisappeared:
  989. pass
  990. raise KeyError(sha)
  991. def _remove_pack(self, pack) -> None:
  992. try:
  993. del self._pack_cache[os.path.basename(pack._basename)]
  994. except KeyError:
  995. pass
  996. pack.close()
  997. os.remove(pack.data.path)
  998. os.remove(pack.index.path)
  999. def _get_pack_basepath(self, entries):
  1000. suffix = iter_sha1(entry[0] for entry in entries)
  1001. # TODO: Handle self.pack_dir being bytes
  1002. suffix = suffix.decode("ascii")
  1003. return os.path.join(self.pack_dir, "pack-" + suffix)
  1004. def _complete_pack(self, f, path, num_objects, indexer, progress=None):
  1005. """Move a specific file containing a pack into the pack directory.
  1006. Note: The file should be on the same file system as the
  1007. packs directory.
  1008. Args:
  1009. f: Open file object for the pack.
  1010. path: Path to the pack file.
  1011. indexer: A PackIndexer for indexing the pack.
  1012. """
  1013. entries = []
  1014. for i, entry in enumerate(indexer):
  1015. if progress is not None:
  1016. progress(f"generating index: {i}/{num_objects}\r".encode("ascii"))
  1017. entries.append(entry)
  1018. pack_sha, extra_entries = extend_pack(
  1019. f,
  1020. indexer.ext_refs(),
  1021. get_raw=self.get_raw,
  1022. compression_level=self.pack_compression_level,
  1023. progress=progress,
  1024. )
  1025. f.flush()
  1026. try:
  1027. fileno = f.fileno()
  1028. except AttributeError:
  1029. pass
  1030. else:
  1031. os.fsync(fileno)
  1032. f.close()
  1033. entries.extend(extra_entries)
  1034. # Move the pack in.
  1035. entries.sort()
  1036. pack_base_name = self._get_pack_basepath(entries)
  1037. for pack in self.packs:
  1038. if pack._basename == pack_base_name:
  1039. return pack
  1040. target_pack_path = pack_base_name + ".pack"
  1041. target_index_path = pack_base_name + ".idx"
  1042. if sys.platform == "win32":
  1043. # Windows might have the target pack file lingering. Attempt
  1044. # removal, silently passing if the target does not exist.
  1045. with suppress(FileNotFoundError):
  1046. os.remove(target_pack_path)
  1047. os.rename(path, target_pack_path)
  1048. # Write the index.
  1049. with GitFile(target_index_path, "wb", mask=PACK_MODE) as index_file:
  1050. write_pack_index(
  1051. index_file, entries, pack_sha, version=self.pack_index_version
  1052. )
  1053. # Add the pack to the store and return it.
  1054. final_pack = Pack(pack_base_name)
  1055. final_pack.check_length_and_checksum()
  1056. self._add_cached_pack(pack_base_name, final_pack)
  1057. return final_pack
  1058. def add_thin_pack(self, read_all, read_some, progress=None):
  1059. """Add a new thin pack to this object store.
  1060. Thin packs are packs that contain deltas with parents that exist
  1061. outside the pack. They should never be placed in the object store
  1062. directly, and always indexed and completed as they are copied.
  1063. Args:
  1064. read_all: Read function that blocks until the number of
  1065. requested bytes are read.
  1066. read_some: Read function that returns at least one byte, but may
  1067. not return the number of bytes requested.
  1068. Returns: A Pack object pointing at the now-completed thin pack in the
  1069. objects/pack directory.
  1070. """
  1071. import tempfile
  1072. fd, path = tempfile.mkstemp(dir=self.path, prefix="tmp_pack_")
  1073. with os.fdopen(fd, "w+b") as f:
  1074. os.chmod(path, PACK_MODE)
  1075. indexer = PackIndexer(f, resolve_ext_ref=self.get_raw)
  1076. copier = PackStreamCopier(read_all, read_some, f, delta_iter=indexer)
  1077. copier.verify(progress=progress)
  1078. return self._complete_pack(f, path, len(copier), indexer, progress=progress)
  1079. def add_pack(self):
  1080. """Add a new pack to this object store.
  1081. Returns: Fileobject to write to, a commit function to
  1082. call when the pack is finished and an abort
  1083. function.
  1084. """
  1085. import tempfile
  1086. fd, path = tempfile.mkstemp(dir=self.pack_dir, suffix=".pack")
  1087. f = os.fdopen(fd, "w+b")
  1088. os.chmod(path, PACK_MODE)
  1089. def commit():
  1090. if f.tell() > 0:
  1091. f.seek(0)
  1092. with PackData(path, f) as pd:
  1093. indexer = PackIndexer.for_pack_data(
  1094. pd, resolve_ext_ref=self.get_raw
  1095. )
  1096. return self._complete_pack(f, path, len(pd), indexer)
  1097. else:
  1098. f.close()
  1099. os.remove(path)
  1100. return None
  1101. def abort() -> None:
  1102. f.close()
  1103. os.remove(path)
  1104. return f, commit, abort
  1105. def add_object(self, obj) -> None:
  1106. """Add a single object to this object store.
  1107. Args:
  1108. obj: Object to add
  1109. """
  1110. path = self._get_shafile_path(obj.id)
  1111. dir = os.path.dirname(path)
  1112. try:
  1113. os.mkdir(dir)
  1114. except FileExistsError:
  1115. pass
  1116. if os.path.exists(path):
  1117. return # Already there, no need to write again
  1118. with GitFile(path, "wb", mask=PACK_MODE) as f:
  1119. f.write(
  1120. obj.as_legacy_object(compression_level=self.loose_compression_level)
  1121. )
  1122. @classmethod
  1123. def init(cls, path: Union[str, os.PathLike]):
  1124. try:
  1125. os.mkdir(path)
  1126. except FileExistsError:
  1127. pass
  1128. os.mkdir(os.path.join(path, "info"))
  1129. os.mkdir(os.path.join(path, PACKDIR))
  1130. return cls(path)
  1131. def iter_prefix(self, prefix):
  1132. if len(prefix) < 2:
  1133. yield from super().iter_prefix(prefix)
  1134. return
  1135. seen = set()
  1136. dir = prefix[:2].decode()
  1137. rest = prefix[2:].decode()
  1138. try:
  1139. for name in os.listdir(os.path.join(self.path, dir)):
  1140. if name.startswith(rest):
  1141. sha = os.fsencode(dir + name)
  1142. if sha not in seen:
  1143. seen.add(sha)
  1144. yield sha
  1145. except FileNotFoundError:
  1146. pass
  1147. for p in self.packs:
  1148. bin_prefix = (
  1149. binascii.unhexlify(prefix)
  1150. if len(prefix) % 2 == 0
  1151. else binascii.unhexlify(prefix[:-1])
  1152. )
  1153. for sha in p.index.iter_prefix(bin_prefix):
  1154. sha = sha_to_hex(sha)
  1155. if sha.startswith(prefix) and sha not in seen:
  1156. seen.add(sha)
  1157. yield sha
  1158. for alternate in self.alternates:
  1159. for sha in alternate.iter_prefix(prefix):
  1160. if sha not in seen:
  1161. seen.add(sha)
  1162. yield sha
  1163. def get_commit_graph(self):
  1164. """Get the commit graph for this object store.
  1165. Returns:
  1166. CommitGraph object if available, None otherwise
  1167. """
  1168. if not self._use_commit_graph:
  1169. return None
  1170. if self._commit_graph is None:
  1171. from .commit_graph import read_commit_graph
  1172. # Look for commit graph in our objects directory
  1173. graph_file = os.path.join(self.path, "info", "commit-graph")
  1174. if os.path.exists(graph_file):
  1175. self._commit_graph = read_commit_graph(graph_file)
  1176. return self._commit_graph
  1177. def write_commit_graph(self, refs=None, reachable=True) -> None:
  1178. """Write a commit graph file for this object store.
  1179. Args:
  1180. refs: List of refs to include. If None, includes all refs from object store.
  1181. reachable: If True, includes all commits reachable from refs.
  1182. If False, only includes the direct ref targets.
  1183. """
  1184. from .commit_graph import get_reachable_commits
  1185. if refs is None:
  1186. # Get all commit objects from the object store
  1187. all_refs = []
  1188. # Iterate through all objects to find commits
  1189. for sha in self:
  1190. try:
  1191. obj = self[sha]
  1192. if obj.type_name == b"commit":
  1193. all_refs.append(sha)
  1194. except KeyError:
  1195. continue
  1196. else:
  1197. # Use provided refs
  1198. all_refs = refs
  1199. if not all_refs:
  1200. return # No commits to include
  1201. if reachable:
  1202. # Get all reachable commits
  1203. commit_ids = get_reachable_commits(self, all_refs)
  1204. else:
  1205. # Just use the direct ref targets - ensure they're hex ObjectIDs
  1206. commit_ids = []
  1207. for ref in all_refs:
  1208. if isinstance(ref, bytes) and len(ref) == 40:
  1209. # Already hex ObjectID
  1210. commit_ids.append(ref)
  1211. elif isinstance(ref, bytes) and len(ref) == 20:
  1212. # Binary SHA, convert to hex ObjectID
  1213. from .objects import sha_to_hex
  1214. commit_ids.append(sha_to_hex(ref))
  1215. else:
  1216. # Assume it's already correct format
  1217. commit_ids.append(ref)
  1218. if commit_ids:
  1219. # Write commit graph directly to our object store path
  1220. # Generate the commit graph
  1221. from .commit_graph import generate_commit_graph
  1222. graph = generate_commit_graph(self, commit_ids)
  1223. if graph.entries:
  1224. # Ensure the info directory exists
  1225. info_dir = os.path.join(self.path, "info")
  1226. os.makedirs(info_dir, exist_ok=True)
  1227. # Write using GitFile for atomic operation
  1228. graph_path = os.path.join(info_dir, "commit-graph")
  1229. with GitFile(graph_path, "wb") as f:
  1230. graph.write_to_file(f)
  1231. # Clear cached commit graph so it gets reloaded
  1232. self._commit_graph = None
  1233. def prune(self, grace_period: Optional[int] = None) -> None:
  1234. """Prune/clean up this object store.
  1235. This removes temporary files that were left behind by interrupted
  1236. pack operations. These are files that start with ``tmp_pack_`` in the
  1237. repository directory or files with .pack extension but no corresponding
  1238. .idx file in the pack directory.
  1239. Args:
  1240. grace_period: Grace period in seconds for removing temporary files.
  1241. If None, uses DEFAULT_TEMPFILE_GRACE_PERIOD.
  1242. """
  1243. import glob
  1244. if grace_period is None:
  1245. grace_period = DEFAULT_TEMPFILE_GRACE_PERIOD
  1246. # Clean up tmp_pack_* files in the repository directory
  1247. for tmp_file in glob.glob(os.path.join(self.path, "tmp_pack_*")):
  1248. # Check if file is old enough (more than grace period)
  1249. mtime = os.path.getmtime(tmp_file)
  1250. if time.time() - mtime > grace_period:
  1251. os.remove(tmp_file)
  1252. # Clean up orphaned .pack files without corresponding .idx files
  1253. try:
  1254. pack_dir_contents = os.listdir(self.pack_dir)
  1255. except FileNotFoundError:
  1256. return
  1257. pack_files = {}
  1258. idx_files = set()
  1259. for name in pack_dir_contents:
  1260. if name.endswith(".pack"):
  1261. base_name = name[:-5] # Remove .pack extension
  1262. pack_files[base_name] = name
  1263. elif name.endswith(".idx"):
  1264. base_name = name[:-4] # Remove .idx extension
  1265. idx_files.add(base_name)
  1266. # Remove .pack files without corresponding .idx files
  1267. for base_name, pack_name in pack_files.items():
  1268. if base_name not in idx_files:
  1269. pack_path = os.path.join(self.pack_dir, pack_name)
  1270. # Check if file is old enough (more than grace period)
  1271. mtime = os.path.getmtime(pack_path)
  1272. if time.time() - mtime > grace_period:
  1273. os.remove(pack_path)
  1274. class MemoryObjectStore(BaseObjectStore):
  1275. """Object store that keeps all objects in memory."""
  1276. def __init__(self) -> None:
  1277. super().__init__()
  1278. self._data: dict[str, ShaFile] = {}
  1279. self.pack_compression_level = -1
  1280. def _to_hexsha(self, sha):
  1281. if len(sha) == 40:
  1282. return sha
  1283. elif len(sha) == 20:
  1284. return sha_to_hex(sha)
  1285. else:
  1286. raise ValueError(f"Invalid sha {sha!r}")
  1287. def contains_loose(self, sha):
  1288. """Check if a particular object is present by SHA1 and is loose."""
  1289. return self._to_hexsha(sha) in self._data
  1290. def contains_packed(self, sha) -> bool:
  1291. """Check if a particular object is present by SHA1 and is packed."""
  1292. return False
  1293. def __iter__(self):
  1294. """Iterate over the SHAs that are present in this store."""
  1295. return iter(self._data.keys())
  1296. @property
  1297. def packs(self):
  1298. """List with pack objects."""
  1299. return []
  1300. def get_raw(self, name: ObjectID):
  1301. """Obtain the raw text for an object.
  1302. Args:
  1303. name: sha for the object.
  1304. Returns: tuple with numeric type and object contents.
  1305. """
  1306. obj = self[self._to_hexsha(name)]
  1307. return obj.type_num, obj.as_raw_string()
  1308. def __getitem__(self, name: ObjectID):
  1309. return self._data[self._to_hexsha(name)].copy()
  1310. def __delitem__(self, name: ObjectID) -> None:
  1311. """Delete an object from this store, for testing only."""
  1312. del self._data[self._to_hexsha(name)]
  1313. def add_object(self, obj) -> None:
  1314. """Add a single object to this object store."""
  1315. self._data[obj.id] = obj.copy()
  1316. def add_objects(self, objects, progress=None) -> None:
  1317. """Add a set of objects to this object store.
  1318. Args:
  1319. objects: Iterable over a list of (object, path) tuples
  1320. """
  1321. for obj, path in objects:
  1322. self.add_object(obj)
  1323. def add_pack(self):
  1324. """Add a new pack to this object store.
  1325. Because this object store doesn't support packs, we extract and add the
  1326. individual objects.
  1327. Returns: Fileobject to write to and a commit function to
  1328. call when the pack is finished.
  1329. """
  1330. from tempfile import SpooledTemporaryFile
  1331. f = SpooledTemporaryFile(max_size=PACK_SPOOL_FILE_MAX_SIZE, prefix="incoming-")
  1332. def commit() -> None:
  1333. size = f.tell()
  1334. if size > 0:
  1335. f.seek(0)
  1336. p = PackData.from_file(f, size)
  1337. for obj in PackInflater.for_pack_data(p, self.get_raw):
  1338. self.add_object(obj)
  1339. p.close()
  1340. f.close()
  1341. else:
  1342. f.close()
  1343. def abort() -> None:
  1344. f.close()
  1345. return f, commit, abort
  1346. def add_pack_data(
  1347. self, count: int, unpacked_objects: Iterator[UnpackedObject], progress=None
  1348. ) -> None:
  1349. """Add pack data to this object store.
  1350. Args:
  1351. count: Number of items to add
  1352. """
  1353. if count == 0:
  1354. return
  1355. # Since MemoryObjectStore doesn't support pack files, we need to
  1356. # extract individual objects. To handle deltas properly, we write
  1357. # to a temporary pack and then use PackInflater to resolve them.
  1358. f, commit, abort = self.add_pack()
  1359. try:
  1360. write_pack_data(
  1361. f.write,
  1362. unpacked_objects,
  1363. num_records=count,
  1364. progress=progress,
  1365. )
  1366. except BaseException:
  1367. abort()
  1368. raise
  1369. else:
  1370. commit()
  1371. def add_thin_pack(self, read_all, read_some, progress=None) -> None:
  1372. """Add a new thin pack to this object store.
  1373. Thin packs are packs that contain deltas with parents that exist
  1374. outside the pack. Because this object store doesn't support packs, we
  1375. extract and add the individual objects.
  1376. Args:
  1377. read_all: Read function that blocks until the number of
  1378. requested bytes are read.
  1379. read_some: Read function that returns at least one byte, but may
  1380. not return the number of bytes requested.
  1381. """
  1382. f, commit, abort = self.add_pack()
  1383. try:
  1384. copier = PackStreamCopier(read_all, read_some, f)
  1385. copier.verify()
  1386. except BaseException:
  1387. abort()
  1388. raise
  1389. else:
  1390. commit()
  1391. class ObjectIterator(Protocol):
  1392. """Interface for iterating over objects."""
  1393. def iterobjects(self) -> Iterator[ShaFile]:
  1394. raise NotImplementedError(self.iterobjects)
  1395. def tree_lookup_path(lookup_obj, root_sha, path):
  1396. """Look up an object in a Git tree.
  1397. Args:
  1398. lookup_obj: Callback for retrieving object by SHA1
  1399. root_sha: SHA1 of the root tree
  1400. path: Path to lookup
  1401. Returns: A tuple of (mode, SHA) of the resulting path.
  1402. """
  1403. tree = lookup_obj(root_sha)
  1404. if not isinstance(tree, Tree):
  1405. raise NotTreeError(root_sha)
  1406. return tree.lookup_path(lookup_obj, path)
  1407. def _collect_filetree_revs(
  1408. obj_store: ObjectContainer, tree_sha: ObjectID, kset: set[ObjectID]
  1409. ) -> None:
  1410. """Collect SHA1s of files and directories for specified tree.
  1411. Args:
  1412. obj_store: Object store to get objects by SHA from
  1413. tree_sha: tree reference to walk
  1414. kset: set to fill with references to files and directories
  1415. """
  1416. filetree = obj_store[tree_sha]
  1417. assert isinstance(filetree, Tree)
  1418. for name, mode, sha in filetree.iteritems():
  1419. if not S_ISGITLINK(mode) and sha not in kset:
  1420. kset.add(sha)
  1421. if stat.S_ISDIR(mode):
  1422. _collect_filetree_revs(obj_store, sha, kset)
  1423. def _split_commits_and_tags(
  1424. obj_store: ObjectContainer, lst, *, ignore_unknown=False
  1425. ) -> tuple[set[bytes], set[bytes], set[bytes]]:
  1426. """Split object id list into three lists with commit, tag, and other SHAs.
  1427. Commits referenced by tags are included into commits
  1428. list as well. Only SHA1s known in this repository will get
  1429. through, and unless ignore_unknown argument is True, KeyError
  1430. is thrown for SHA1 missing in the repository
  1431. Args:
  1432. obj_store: Object store to get objects by SHA1 from
  1433. lst: Collection of commit and tag SHAs
  1434. ignore_unknown: True to skip SHA1 missing in the repository
  1435. silently.
  1436. Returns: A tuple of (commits, tags, others) SHA1s
  1437. """
  1438. commits: set[bytes] = set()
  1439. tags: set[bytes] = set()
  1440. others: set[bytes] = set()
  1441. for e in lst:
  1442. try:
  1443. o = obj_store[e]
  1444. except KeyError:
  1445. if not ignore_unknown:
  1446. raise
  1447. else:
  1448. if isinstance(o, Commit):
  1449. commits.add(e)
  1450. elif isinstance(o, Tag):
  1451. tags.add(e)
  1452. tagged = o.object[1]
  1453. c, t, os = _split_commits_and_tags(
  1454. obj_store, [tagged], ignore_unknown=ignore_unknown
  1455. )
  1456. commits |= c
  1457. tags |= t
  1458. others |= os
  1459. else:
  1460. others.add(e)
  1461. return (commits, tags, others)
  1462. class MissingObjectFinder:
  1463. """Find the objects missing from another object store.
  1464. Args:
  1465. object_store: Object store containing at least all objects to be
  1466. sent
  1467. haves: SHA1s of commits not to send (already present in target)
  1468. wants: SHA1s of commits to send
  1469. progress: Optional function to report progress to.
  1470. get_tagged: Function that returns a dict of pointed-to sha -> tag
  1471. sha for including tags.
  1472. get_parents: Optional function for getting the parents of a commit.
  1473. """
  1474. def __init__(
  1475. self,
  1476. object_store,
  1477. haves,
  1478. wants,
  1479. *,
  1480. shallow=None,
  1481. progress=None,
  1482. get_tagged=None,
  1483. get_parents=lambda commit: commit.parents,
  1484. ) -> None:
  1485. self.object_store = object_store
  1486. if shallow is None:
  1487. shallow = set()
  1488. self._get_parents = get_parents
  1489. # process Commits and Tags differently
  1490. # Note, while haves may list commits/tags not available locally,
  1491. # and such SHAs would get filtered out by _split_commits_and_tags,
  1492. # wants shall list only known SHAs, and otherwise
  1493. # _split_commits_and_tags fails with KeyError
  1494. have_commits, have_tags, have_others = _split_commits_and_tags(
  1495. object_store, haves, ignore_unknown=True
  1496. )
  1497. want_commits, want_tags, want_others = _split_commits_and_tags(
  1498. object_store, wants, ignore_unknown=False
  1499. )
  1500. # all_ancestors is a set of commits that shall not be sent
  1501. # (complete repository up to 'haves')
  1502. all_ancestors = _collect_ancestors(
  1503. object_store, have_commits, shallow=shallow, get_parents=self._get_parents
  1504. )[0]
  1505. # all_missing - complete set of commits between haves and wants
  1506. # common - commits from all_ancestors we hit into while
  1507. # traversing parent hierarchy of wants
  1508. missing_commits, common_commits = _collect_ancestors(
  1509. object_store,
  1510. want_commits,
  1511. all_ancestors,
  1512. shallow=shallow,
  1513. get_parents=self._get_parents,
  1514. )
  1515. self.remote_has: set[bytes] = set()
  1516. # Now, fill sha_done with commits and revisions of
  1517. # files and directories known to be both locally
  1518. # and on target. Thus these commits and files
  1519. # won't get selected for fetch
  1520. for h in common_commits:
  1521. self.remote_has.add(h)
  1522. cmt = object_store[h]
  1523. _collect_filetree_revs(object_store, cmt.tree, self.remote_has)
  1524. # record tags we have as visited, too
  1525. for t in have_tags:
  1526. self.remote_has.add(t)
  1527. self.sha_done = set(self.remote_has)
  1528. # in fact, what we 'want' is commits, tags, and others
  1529. # we've found missing
  1530. self.objects_to_send: set[
  1531. tuple[ObjectID, Optional[bytes], Optional[int], bool]
  1532. ] = {(w, None, Commit.type_num, False) for w in missing_commits}
  1533. missing_tags = want_tags.difference(have_tags)
  1534. self.objects_to_send.update(
  1535. {(w, None, Tag.type_num, False) for w in missing_tags}
  1536. )
  1537. missing_others = want_others.difference(have_others)
  1538. self.objects_to_send.update({(w, None, None, False) for w in missing_others})
  1539. if progress is None:
  1540. self.progress = lambda x: None
  1541. else:
  1542. self.progress = progress
  1543. self._tagged = (get_tagged and get_tagged()) or {}
  1544. def get_remote_has(self):
  1545. return self.remote_has
  1546. def add_todo(
  1547. self, entries: Iterable[tuple[ObjectID, Optional[bytes], Optional[int], bool]]
  1548. ) -> None:
  1549. self.objects_to_send.update([e for e in entries if e[0] not in self.sha_done])
  1550. def __next__(self) -> tuple[bytes, Optional[PackHint]]:
  1551. while True:
  1552. if not self.objects_to_send:
  1553. self.progress(
  1554. f"counting objects: {len(self.sha_done)}, done.\n".encode("ascii")
  1555. )
  1556. raise StopIteration
  1557. (sha, name, type_num, leaf) = self.objects_to_send.pop()
  1558. if sha not in self.sha_done:
  1559. break
  1560. if not leaf:
  1561. o = self.object_store[sha]
  1562. if isinstance(o, Commit):
  1563. self.add_todo([(o.tree, b"", Tree.type_num, False)])
  1564. elif isinstance(o, Tree):
  1565. self.add_todo(
  1566. [
  1567. (
  1568. s,
  1569. n,
  1570. (Blob.type_num if stat.S_ISREG(m) else Tree.type_num),
  1571. not stat.S_ISDIR(m),
  1572. )
  1573. for n, m, s in o.iteritems()
  1574. if not S_ISGITLINK(m)
  1575. ]
  1576. )
  1577. elif isinstance(o, Tag):
  1578. self.add_todo([(o.object[1], None, o.object[0].type_num, False)])
  1579. if sha in self._tagged:
  1580. self.add_todo([(self._tagged[sha], None, None, True)])
  1581. self.sha_done.add(sha)
  1582. if len(self.sha_done) % 1000 == 0:
  1583. self.progress(f"counting objects: {len(self.sha_done)}\r".encode("ascii"))
  1584. if type_num is None:
  1585. pack_hint = None
  1586. else:
  1587. pack_hint = (type_num, name)
  1588. return (sha, pack_hint)
  1589. def __iter__(self):
  1590. return self
  1591. class ObjectStoreGraphWalker:
  1592. """Graph walker that finds what commits are missing from an object store."""
  1593. heads: set[ObjectID]
  1594. """Revisions without descendants in the local repo."""
  1595. get_parents: Callable[[ObjectID], ObjectID]
  1596. """Function to retrieve parents in the local repo."""
  1597. shallow: set[ObjectID]
  1598. def __init__(
  1599. self,
  1600. local_heads: Iterable[ObjectID],
  1601. get_parents,
  1602. shallow: Optional[set[ObjectID]] = None,
  1603. update_shallow=None,
  1604. ) -> None:
  1605. """Create a new instance.
  1606. Args:
  1607. local_heads: Heads to start search with
  1608. get_parents: Function for finding the parents of a SHA1.
  1609. """
  1610. self.heads = set(local_heads)
  1611. self.get_parents = get_parents
  1612. self.parents: dict[ObjectID, Optional[list[ObjectID]]] = {}
  1613. if shallow is None:
  1614. shallow = set()
  1615. self.shallow = shallow
  1616. self.update_shallow = update_shallow
  1617. def nak(self) -> None:
  1618. """Nothing in common was found."""
  1619. def ack(self, sha: ObjectID) -> None:
  1620. """Ack that a revision and its ancestors are present in the source."""
  1621. if len(sha) != 40:
  1622. raise ValueError(f"unexpected sha {sha!r} received")
  1623. ancestors = {sha}
  1624. # stop if we run out of heads to remove
  1625. while self.heads:
  1626. for a in ancestors:
  1627. if a in self.heads:
  1628. self.heads.remove(a)
  1629. # collect all ancestors
  1630. new_ancestors = set()
  1631. for a in ancestors:
  1632. ps = self.parents.get(a)
  1633. if ps is not None:
  1634. new_ancestors.update(ps)
  1635. self.parents[a] = None
  1636. # no more ancestors; stop
  1637. if not new_ancestors:
  1638. break
  1639. ancestors = new_ancestors
  1640. def next(self):
  1641. """Iterate over ancestors of heads in the target."""
  1642. if self.heads:
  1643. ret = self.heads.pop()
  1644. try:
  1645. ps = self.get_parents(ret)
  1646. except KeyError:
  1647. return None
  1648. self.parents[ret] = ps
  1649. self.heads.update([p for p in ps if p not in self.parents])
  1650. return ret
  1651. return None
  1652. __next__ = next
  1653. def commit_tree_changes(object_store, tree, changes):
  1654. """Commit a specified set of changes to a tree structure.
  1655. This will apply a set of changes on top of an existing tree, storing new
  1656. objects in object_store.
  1657. changes are a list of tuples with (path, mode, object_sha).
  1658. Paths can be both blobs and trees. See the mode and
  1659. object sha to None deletes the path.
  1660. This method works especially well if there are only a small
  1661. number of changes to a big tree. For a large number of changes
  1662. to a large tree, use e.g. commit_tree.
  1663. Args:
  1664. object_store: Object store to store new objects in
  1665. and retrieve old ones from.
  1666. tree: Original tree root
  1667. changes: changes to apply
  1668. Returns: New tree root object
  1669. """
  1670. # TODO(jelmer): Save up the objects and add them using .add_objects
  1671. # rather than with individual calls to .add_object.
  1672. nested_changes = {}
  1673. for path, new_mode, new_sha in changes:
  1674. try:
  1675. (dirname, subpath) = path.split(b"/", 1)
  1676. except ValueError:
  1677. if new_sha is None:
  1678. del tree[path]
  1679. else:
  1680. tree[path] = (new_mode, new_sha)
  1681. else:
  1682. nested_changes.setdefault(dirname, []).append((subpath, new_mode, new_sha))
  1683. for name, subchanges in nested_changes.items():
  1684. try:
  1685. orig_subtree = object_store[tree[name][1]]
  1686. except KeyError:
  1687. orig_subtree = Tree()
  1688. subtree = commit_tree_changes(object_store, orig_subtree, subchanges)
  1689. if len(subtree) == 0:
  1690. del tree[name]
  1691. else:
  1692. tree[name] = (stat.S_IFDIR, subtree.id)
  1693. object_store.add_object(tree)
  1694. return tree
  1695. class OverlayObjectStore(BaseObjectStore):
  1696. """Object store that can overlay multiple object stores."""
  1697. def __init__(self, bases, add_store=None) -> None:
  1698. self.bases = bases
  1699. self.add_store = add_store
  1700. def add_object(self, object):
  1701. if self.add_store is None:
  1702. raise NotImplementedError(self.add_object)
  1703. return self.add_store.add_object(object)
  1704. def add_objects(self, objects, progress=None):
  1705. if self.add_store is None:
  1706. raise NotImplementedError(self.add_object)
  1707. return self.add_store.add_objects(objects, progress)
  1708. @property
  1709. def packs(self):
  1710. ret = []
  1711. for b in self.bases:
  1712. ret.extend(b.packs)
  1713. return ret
  1714. def __iter__(self):
  1715. done = set()
  1716. for b in self.bases:
  1717. for o_id in b:
  1718. if o_id not in done:
  1719. yield o_id
  1720. done.add(o_id)
  1721. def iterobjects_subset(
  1722. self, shas: Iterable[bytes], *, allow_missing: bool = False
  1723. ) -> Iterator[ShaFile]:
  1724. todo = set(shas)
  1725. found: set[bytes] = set()
  1726. for b in self.bases:
  1727. # Create a copy of todo for each base to avoid modifying
  1728. # the set while iterating through it
  1729. current_todo = todo - found
  1730. for o in b.iterobjects_subset(current_todo, allow_missing=True):
  1731. yield o
  1732. found.add(o.id)
  1733. # Check for any remaining objects not found
  1734. missing = todo - found
  1735. if missing and not allow_missing:
  1736. raise KeyError(next(iter(missing)))
  1737. def iter_unpacked_subset(
  1738. self,
  1739. shas: Iterable[bytes],
  1740. *,
  1741. include_comp=False,
  1742. allow_missing: bool = False,
  1743. convert_ofs_delta=True,
  1744. ) -> Iterator[ShaFile]:
  1745. todo = set(shas)
  1746. for b in self.bases:
  1747. for o in b.iter_unpacked_subset(
  1748. todo,
  1749. include_comp=include_comp,
  1750. allow_missing=True,
  1751. convert_ofs_delta=convert_ofs_delta,
  1752. ):
  1753. yield o
  1754. todo.remove(o.id)
  1755. if todo and not allow_missing:
  1756. raise KeyError(o.id)
  1757. def get_raw(self, sha_id):
  1758. for b in self.bases:
  1759. try:
  1760. return b.get_raw(sha_id)
  1761. except KeyError:
  1762. pass
  1763. raise KeyError(sha_id)
  1764. def contains_packed(self, sha) -> bool:
  1765. for b in self.bases:
  1766. if b.contains_packed(sha):
  1767. return True
  1768. return False
  1769. def contains_loose(self, sha) -> bool:
  1770. for b in self.bases:
  1771. if b.contains_loose(sha):
  1772. return True
  1773. return False
  1774. def read_packs_file(f):
  1775. """Yield the packs listed in a packs file."""
  1776. for line in f.read().splitlines():
  1777. if not line:
  1778. continue
  1779. (kind, name) = line.split(b" ", 1)
  1780. if kind != b"P":
  1781. continue
  1782. yield os.fsdecode(name)
  1783. class BucketBasedObjectStore(PackBasedObjectStore):
  1784. """Object store implementation that uses a bucket store like S3 as backend."""
  1785. def _iter_loose_objects(self):
  1786. """Iterate over the SHAs of all loose objects."""
  1787. return iter([])
  1788. def _get_loose_object(self, sha) -> None:
  1789. return None
  1790. def delete_loose_object(self, sha) -> None:
  1791. # Doesn't exist..
  1792. pass
  1793. def _remove_pack(self, name) -> None:
  1794. raise NotImplementedError(self._remove_pack)
  1795. def _iter_pack_names(self) -> Iterator[str]:
  1796. raise NotImplementedError(self._iter_pack_names)
  1797. def _get_pack(self, name) -> Pack:
  1798. raise NotImplementedError(self._get_pack)
  1799. def _update_pack_cache(self):
  1800. pack_files = set(self._iter_pack_names())
  1801. # Open newly appeared pack files
  1802. new_packs = []
  1803. for f in pack_files:
  1804. if f not in self._pack_cache:
  1805. pack = self._get_pack(f)
  1806. new_packs.append(pack)
  1807. self._pack_cache[f] = pack
  1808. # Remove disappeared pack files
  1809. for f in set(self._pack_cache) - pack_files:
  1810. self._pack_cache.pop(f).close()
  1811. return new_packs
  1812. def _upload_pack(self, basename, pack_file, index_file) -> None:
  1813. raise NotImplementedError
  1814. def add_pack(self):
  1815. """Add a new pack to this object store.
  1816. Returns: Fileobject to write to, a commit function to
  1817. call when the pack is finished and an abort
  1818. function.
  1819. """
  1820. import tempfile
  1821. pf = tempfile.SpooledTemporaryFile(
  1822. max_size=PACK_SPOOL_FILE_MAX_SIZE, prefix="incoming-"
  1823. )
  1824. def commit():
  1825. if pf.tell() == 0:
  1826. pf.close()
  1827. return None
  1828. pf.seek(0)
  1829. p = PackData(pf.name, pf)
  1830. entries = p.sorted_entries()
  1831. basename = iter_sha1(entry[0] for entry in entries).decode("ascii")
  1832. idxf = tempfile.SpooledTemporaryFile(
  1833. max_size=PACK_SPOOL_FILE_MAX_SIZE, prefix="incoming-"
  1834. )
  1835. checksum = p.get_stored_checksum()
  1836. write_pack_index(idxf, entries, checksum, version=self.pack_index_version)
  1837. idxf.seek(0)
  1838. idx = load_pack_index_file(basename + ".idx", idxf)
  1839. for pack in self.packs:
  1840. if pack.get_stored_checksum() == p.get_stored_checksum():
  1841. p.close()
  1842. idx.close()
  1843. pf.close()
  1844. idxf.close()
  1845. return pack
  1846. pf.seek(0)
  1847. idxf.seek(0)
  1848. self._upload_pack(basename, pf, idxf)
  1849. final_pack = Pack.from_objects(p, idx)
  1850. self._add_cached_pack(basename, final_pack)
  1851. pf.close()
  1852. idxf.close()
  1853. return final_pack
  1854. return pf, commit, pf.close
  1855. def _collect_ancestors(
  1856. store: ObjectContainer,
  1857. heads,
  1858. common: frozenset[ObjectID] = frozenset(),
  1859. shallow: frozenset[ObjectID] = frozenset(),
  1860. get_parents=lambda commit: commit.parents,
  1861. ):
  1862. """Collect all ancestors of heads up to (excluding) those in common.
  1863. Args:
  1864. heads: commits to start from
  1865. common: commits to end at, or empty set to walk repository
  1866. completely
  1867. get_parents: Optional function for getting the parents of a
  1868. commit.
  1869. Returns: a tuple (A, B) where A - all commits reachable
  1870. from heads but not present in common, B - common (shared) elements
  1871. that are directly reachable from heads
  1872. """
  1873. bases = set()
  1874. commits = set()
  1875. queue = []
  1876. queue.extend(heads)
  1877. # Try to use commit graph if available
  1878. commit_graph = store.get_commit_graph()
  1879. while queue:
  1880. e = queue.pop(0)
  1881. if e in common:
  1882. bases.add(e)
  1883. elif e not in commits:
  1884. commits.add(e)
  1885. if e in shallow:
  1886. continue
  1887. # Try to use commit graph for parent lookup
  1888. parents = None
  1889. if commit_graph:
  1890. parents = commit_graph.get_parents(e)
  1891. if parents is None:
  1892. # Fall back to loading the object
  1893. cmt = store[e]
  1894. parents = get_parents(cmt)
  1895. queue.extend(parents)
  1896. return (commits, bases)
  1897. def iter_tree_contents(
  1898. store: ObjectContainer, tree_id: Optional[ObjectID], *, include_trees: bool = False
  1899. ):
  1900. """Iterate the contents of a tree and all subtrees.
  1901. Iteration is depth-first pre-order, as in e.g. os.walk.
  1902. Args:
  1903. tree_id: SHA1 of the tree.
  1904. include_trees: If True, include tree objects in the iteration.
  1905. Returns: Iterator over TreeEntry namedtuples for all the objects in a
  1906. tree.
  1907. """
  1908. if tree_id is None:
  1909. return
  1910. # This could be fairly easily generalized to >2 trees if we find a use
  1911. # case.
  1912. todo = [TreeEntry(b"", stat.S_IFDIR, tree_id)]
  1913. while todo:
  1914. entry = todo.pop()
  1915. if stat.S_ISDIR(entry.mode):
  1916. extra = []
  1917. tree = store[entry.sha]
  1918. assert isinstance(tree, Tree)
  1919. for subentry in tree.iteritems(name_order=True):
  1920. extra.append(subentry.in_path(entry.path))
  1921. todo.extend(reversed(extra))
  1922. if not stat.S_ISDIR(entry.mode) or include_trees:
  1923. yield entry
  1924. def peel_sha(store: ObjectContainer, sha: bytes) -> tuple[ShaFile, ShaFile]:
  1925. """Peel all tags from a SHA.
  1926. Args:
  1927. sha: The object SHA to peel.
  1928. Returns: The fully-peeled SHA1 of a tag object, after peeling all
  1929. intermediate tags; if the original ref does not point to a tag,
  1930. this will equal the original SHA1.
  1931. """
  1932. unpeeled = obj = store[sha]
  1933. obj_class = object_class(obj.type_name)
  1934. while obj_class is Tag:
  1935. assert isinstance(obj, Tag)
  1936. obj_class, sha = obj.object
  1937. obj = store[sha]
  1938. return unpeeled, obj