object_store.py 100 KB

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