object_store.py 130 KB

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