object_store.py 130 KB

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