object_store.py 118 KB

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