object_store.py 125 KB

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