object_store.py 119 KB

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