object_store.py 105 KB

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