object_store.py 89 KB

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