object_store.py 115 KB

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