object_store.py 107 KB

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