object_store.py 130 KB

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