object_store.py 100 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972
  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. fsync_object_files: bool = False,
  1039. ) -> None:
  1040. """Open an object store.
  1041. Args:
  1042. path: Path of the object store.
  1043. loose_compression_level: zlib compression level for loose objects
  1044. pack_compression_level: zlib compression level for pack objects
  1045. pack_index_version: pack index version to use (1, 2, or 3)
  1046. pack_delta_window_size: sliding window size for delta compression
  1047. pack_window_memory: memory limit for delta window operations
  1048. pack_delta_cache_size: size of cache for delta operations
  1049. pack_depth: maximum delta chain depth
  1050. pack_threads: number of threads for pack operations
  1051. pack_big_file_threshold: threshold for treating files as big
  1052. fsync_object_files: whether to fsync object files for durability
  1053. """
  1054. super().__init__(
  1055. pack_compression_level=pack_compression_level,
  1056. pack_index_version=pack_index_version,
  1057. pack_delta_window_size=pack_delta_window_size,
  1058. pack_window_memory=pack_window_memory,
  1059. pack_delta_cache_size=pack_delta_cache_size,
  1060. pack_depth=pack_depth,
  1061. pack_threads=pack_threads,
  1062. pack_big_file_threshold=pack_big_file_threshold,
  1063. )
  1064. self.path = path
  1065. self.pack_dir = os.path.join(self.path, PACKDIR)
  1066. self._alternates = None
  1067. self.loose_compression_level = loose_compression_level
  1068. self.pack_compression_level = pack_compression_level
  1069. self.pack_index_version = pack_index_version
  1070. self.fsync_object_files = fsync_object_files
  1071. # Commit graph support - lazy loaded
  1072. self._commit_graph = None
  1073. self._use_commit_graph = True # Default to true
  1074. def __repr__(self) -> str:
  1075. """Return string representation of DiskObjectStore.
  1076. Returns:
  1077. String representation including the store path
  1078. """
  1079. return f"<{self.__class__.__name__}({self.path!r})>"
  1080. @classmethod
  1081. def from_config(
  1082. cls, path: Union[str, os.PathLike[str]], config: "Config"
  1083. ) -> "DiskObjectStore":
  1084. """Create a DiskObjectStore from a configuration object.
  1085. Args:
  1086. path: Path to the object store directory
  1087. config: Configuration object to read settings from
  1088. Returns:
  1089. New DiskObjectStore instance configured according to config
  1090. """
  1091. try:
  1092. default_compression_level = int(
  1093. config.get((b"core",), b"compression").decode()
  1094. )
  1095. except KeyError:
  1096. default_compression_level = -1
  1097. try:
  1098. loose_compression_level = int(
  1099. config.get((b"core",), b"looseCompression").decode()
  1100. )
  1101. except KeyError:
  1102. loose_compression_level = default_compression_level
  1103. try:
  1104. pack_compression_level = int(
  1105. config.get((b"core",), "packCompression").decode()
  1106. )
  1107. except KeyError:
  1108. pack_compression_level = default_compression_level
  1109. try:
  1110. pack_index_version = int(config.get((b"pack",), b"indexVersion").decode())
  1111. except KeyError:
  1112. pack_index_version = None
  1113. # Read pack configuration options
  1114. try:
  1115. pack_delta_window_size = int(
  1116. config.get((b"pack",), b"deltaWindowSize").decode()
  1117. )
  1118. except KeyError:
  1119. pack_delta_window_size = None
  1120. try:
  1121. pack_window_memory = int(config.get((b"pack",), b"windowMemory").decode())
  1122. except KeyError:
  1123. pack_window_memory = None
  1124. try:
  1125. pack_delta_cache_size = int(
  1126. config.get((b"pack",), b"deltaCacheSize").decode()
  1127. )
  1128. except KeyError:
  1129. pack_delta_cache_size = None
  1130. try:
  1131. pack_depth = int(config.get((b"pack",), b"depth").decode())
  1132. except KeyError:
  1133. pack_depth = None
  1134. try:
  1135. pack_threads = int(config.get((b"pack",), b"threads").decode())
  1136. except KeyError:
  1137. pack_threads = None
  1138. try:
  1139. pack_big_file_threshold = int(
  1140. config.get((b"pack",), b"bigFileThreshold").decode()
  1141. )
  1142. except KeyError:
  1143. pack_big_file_threshold = None
  1144. # Read core.commitGraph setting
  1145. use_commit_graph = config.get_boolean((b"core",), b"commitGraph", True)
  1146. # Read core.fsyncObjectFiles setting
  1147. fsync_object_files = config.get_boolean((b"core",), b"fsyncObjectFiles", False)
  1148. instance = cls(
  1149. path,
  1150. loose_compression_level,
  1151. pack_compression_level,
  1152. pack_index_version,
  1153. pack_delta_window_size,
  1154. pack_window_memory,
  1155. pack_delta_cache_size,
  1156. pack_depth,
  1157. pack_threads,
  1158. pack_big_file_threshold,
  1159. fsync_object_files,
  1160. )
  1161. instance._use_commit_graph = use_commit_graph
  1162. return instance
  1163. @property
  1164. def alternates(self) -> list["BaseObjectStore"]:
  1165. """Get the list of alternate object stores.
  1166. Reads from .git/objects/info/alternates if not already cached.
  1167. Returns:
  1168. List of DiskObjectStore instances for alternate object directories
  1169. """
  1170. if self._alternates is not None:
  1171. return self._alternates
  1172. self._alternates = []
  1173. for path in self._read_alternate_paths():
  1174. self._alternates.append(DiskObjectStore(path))
  1175. return self._alternates
  1176. def _read_alternate_paths(self) -> Iterator[str]:
  1177. try:
  1178. f = GitFile(os.path.join(self.path, INFODIR, "alternates"), "rb")
  1179. except FileNotFoundError:
  1180. return
  1181. with f:
  1182. for line in f.readlines():
  1183. line = line.rstrip(b"\n")
  1184. if line.startswith(b"#"):
  1185. continue
  1186. if os.path.isabs(line):
  1187. yield os.fsdecode(line)
  1188. else:
  1189. yield os.fsdecode(os.path.join(os.fsencode(self.path), line))
  1190. def add_alternate_path(self, path: Union[str, os.PathLike[str]]) -> None:
  1191. """Add an alternate path to this object store."""
  1192. try:
  1193. os.mkdir(os.path.join(self.path, INFODIR))
  1194. except FileExistsError:
  1195. pass
  1196. alternates_path = os.path.join(self.path, INFODIR, "alternates")
  1197. with GitFile(alternates_path, "wb") as f:
  1198. try:
  1199. orig_f = open(alternates_path, "rb")
  1200. except FileNotFoundError:
  1201. pass
  1202. else:
  1203. with orig_f:
  1204. f.write(orig_f.read())
  1205. f.write(os.fsencode(path) + b"\n")
  1206. if not os.path.isabs(path):
  1207. path = os.path.join(self.path, path)
  1208. self.alternates.append(DiskObjectStore(path))
  1209. def _update_pack_cache(self) -> list[Pack]:
  1210. """Read and iterate over new pack files and cache them."""
  1211. try:
  1212. pack_dir_contents = os.listdir(self.pack_dir)
  1213. except FileNotFoundError:
  1214. self.close()
  1215. return []
  1216. pack_files = set()
  1217. for name in pack_dir_contents:
  1218. if name.startswith("pack-") and name.endswith(".pack"):
  1219. # verify that idx exists first (otherwise the pack was not yet
  1220. # fully written)
  1221. idx_name = os.path.splitext(name)[0] + ".idx"
  1222. if idx_name in pack_dir_contents:
  1223. pack_name = name[: -len(".pack")]
  1224. pack_files.add(pack_name)
  1225. # Open newly appeared pack files
  1226. new_packs = []
  1227. for f in pack_files:
  1228. if f not in self._pack_cache:
  1229. pack = Pack(
  1230. os.path.join(self.pack_dir, f),
  1231. delta_window_size=self.pack_delta_window_size,
  1232. window_memory=self.pack_window_memory,
  1233. delta_cache_size=self.pack_delta_cache_size,
  1234. depth=self.pack_depth,
  1235. threads=self.pack_threads,
  1236. big_file_threshold=self.pack_big_file_threshold,
  1237. )
  1238. new_packs.append(pack)
  1239. self._pack_cache[f] = pack
  1240. # Remove disappeared pack files
  1241. for f in set(self._pack_cache) - pack_files:
  1242. self._pack_cache.pop(f).close()
  1243. return new_packs
  1244. def _get_shafile_path(self, sha: bytes) -> str:
  1245. # Check from object dir
  1246. return hex_to_filename(os.fspath(self.path), sha)
  1247. def _iter_loose_objects(self) -> Iterator[bytes]:
  1248. for base in os.listdir(self.path):
  1249. if len(base) != 2:
  1250. continue
  1251. for rest in os.listdir(os.path.join(self.path, base)):
  1252. sha = os.fsencode(base + rest)
  1253. if not valid_hexsha(sha):
  1254. continue
  1255. yield sha
  1256. def count_loose_objects(self) -> int:
  1257. """Count the number of loose objects in the object store.
  1258. Returns:
  1259. Number of loose objects
  1260. """
  1261. count = 0
  1262. if not os.path.exists(self.path):
  1263. return 0
  1264. for i in range(256):
  1265. subdir = os.path.join(self.path, f"{i:02x}")
  1266. try:
  1267. count += len(
  1268. [
  1269. name
  1270. for name in os.listdir(subdir)
  1271. if len(name) == 38 # 40 - 2 for the prefix
  1272. ]
  1273. )
  1274. except FileNotFoundError:
  1275. # Directory may have been removed or is inaccessible
  1276. continue
  1277. return count
  1278. def _get_loose_object(self, sha: bytes) -> Optional[ShaFile]:
  1279. path = self._get_shafile_path(sha)
  1280. try:
  1281. return ShaFile.from_path(path)
  1282. except FileNotFoundError:
  1283. return None
  1284. def delete_loose_object(self, sha: bytes) -> None:
  1285. """Delete a loose object from disk.
  1286. Args:
  1287. sha: SHA1 of the object to delete
  1288. Raises:
  1289. FileNotFoundError: If the object file doesn't exist
  1290. """
  1291. os.remove(self._get_shafile_path(sha))
  1292. def get_object_mtime(self, sha: bytes) -> float:
  1293. """Get the modification time of an object.
  1294. Args:
  1295. sha: SHA1 of the object
  1296. Returns:
  1297. Modification time as seconds since epoch
  1298. Raises:
  1299. KeyError: if the object is not found
  1300. """
  1301. # First check if it's a loose object
  1302. if self.contains_loose(sha):
  1303. path = self._get_shafile_path(sha)
  1304. try:
  1305. return os.path.getmtime(path)
  1306. except FileNotFoundError:
  1307. pass
  1308. # Check if it's in a pack file
  1309. for pack in self.packs:
  1310. try:
  1311. if sha in pack:
  1312. # Use the pack file's mtime for packed objects
  1313. pack_path = pack._data_path
  1314. try:
  1315. return os.path.getmtime(pack_path)
  1316. except (FileNotFoundError, AttributeError):
  1317. pass
  1318. except PackFileDisappeared:
  1319. pass
  1320. raise KeyError(sha)
  1321. def _remove_pack(self, pack: Pack) -> None:
  1322. try:
  1323. del self._pack_cache[os.path.basename(pack._basename)]
  1324. except KeyError:
  1325. pass
  1326. pack.close()
  1327. os.remove(pack.data.path)
  1328. if hasattr(pack.index, "path"):
  1329. os.remove(pack.index.path)
  1330. def _get_pack_basepath(
  1331. self, entries: Iterable[tuple[bytes, int, Union[int, None]]]
  1332. ) -> str:
  1333. suffix_bytes = iter_sha1(entry[0] for entry in entries)
  1334. # TODO: Handle self.pack_dir being bytes
  1335. suffix = suffix_bytes.decode("ascii")
  1336. return os.path.join(self.pack_dir, "pack-" + suffix)
  1337. def _complete_pack(
  1338. self,
  1339. f: BinaryIO,
  1340. path: str,
  1341. num_objects: int,
  1342. indexer: PackIndexer,
  1343. progress: Optional[Callable[..., None]] = None,
  1344. ) -> Pack:
  1345. """Move a specific file containing a pack into the pack directory.
  1346. Note: The file should be on the same file system as the
  1347. packs directory.
  1348. Args:
  1349. f: Open file object for the pack.
  1350. path: Path to the pack file.
  1351. num_objects: Number of objects in the pack.
  1352. indexer: A PackIndexer for indexing the pack.
  1353. progress: Optional progress reporting function.
  1354. """
  1355. entries = []
  1356. for i, entry in enumerate(indexer):
  1357. if progress is not None:
  1358. progress(f"generating index: {i}/{num_objects}\r".encode("ascii"))
  1359. entries.append(entry)
  1360. pack_sha, extra_entries = extend_pack(
  1361. f,
  1362. set(indexer.ext_refs()),
  1363. get_raw=self.get_raw,
  1364. compression_level=self.pack_compression_level,
  1365. progress=progress,
  1366. )
  1367. f.flush()
  1368. if self.fsync_object_files:
  1369. try:
  1370. fileno = f.fileno()
  1371. except AttributeError as e:
  1372. raise OSError("fsync requested but file has no fileno()") from e
  1373. else:
  1374. os.fsync(fileno)
  1375. f.close()
  1376. entries.extend(extra_entries)
  1377. # Move the pack in.
  1378. entries.sort()
  1379. pack_base_name = self._get_pack_basepath(entries)
  1380. for pack in self.packs:
  1381. if pack._basename == pack_base_name:
  1382. return pack
  1383. target_pack_path = pack_base_name + ".pack"
  1384. target_index_path = pack_base_name + ".idx"
  1385. if sys.platform == "win32":
  1386. # Windows might have the target pack file lingering. Attempt
  1387. # removal, silently passing if the target does not exist.
  1388. with suppress(FileNotFoundError):
  1389. os.remove(target_pack_path)
  1390. os.rename(path, target_pack_path)
  1391. # Write the index.
  1392. with GitFile(
  1393. target_index_path, "wb", mask=PACK_MODE, fsync=self.fsync_object_files
  1394. ) as index_file:
  1395. write_pack_index(
  1396. index_file, entries, pack_sha, version=self.pack_index_version
  1397. )
  1398. # Add the pack to the store and return it.
  1399. final_pack = Pack(
  1400. pack_base_name,
  1401. delta_window_size=self.pack_delta_window_size,
  1402. window_memory=self.pack_window_memory,
  1403. delta_cache_size=self.pack_delta_cache_size,
  1404. depth=self.pack_depth,
  1405. threads=self.pack_threads,
  1406. big_file_threshold=self.pack_big_file_threshold,
  1407. )
  1408. final_pack.check_length_and_checksum()
  1409. self._add_cached_pack(pack_base_name, final_pack)
  1410. return final_pack
  1411. def add_thin_pack(
  1412. self,
  1413. read_all: Callable[[int], bytes],
  1414. read_some: Optional[Callable[[int], bytes]],
  1415. progress: Optional[Callable[..., None]] = None,
  1416. ) -> "Pack":
  1417. """Add a new thin pack to this object store.
  1418. Thin packs are packs that contain deltas with parents that exist
  1419. outside the pack. They should never be placed in the object store
  1420. directly, and always indexed and completed as they are copied.
  1421. Args:
  1422. read_all: Read function that blocks until the number of
  1423. requested bytes are read.
  1424. read_some: Read function that returns at least one byte, but may
  1425. not return the number of bytes requested.
  1426. progress: Optional progress reporting function.
  1427. Returns: A Pack object pointing at the now-completed thin pack in the
  1428. objects/pack directory.
  1429. """
  1430. import tempfile
  1431. fd, path = tempfile.mkstemp(dir=self.path, prefix="tmp_pack_")
  1432. with os.fdopen(fd, "w+b") as f:
  1433. os.chmod(path, PACK_MODE)
  1434. indexer = PackIndexer(f, resolve_ext_ref=self.get_raw) # type: ignore[arg-type]
  1435. copier = PackStreamCopier(read_all, read_some, f, delta_iter=indexer) # type: ignore[arg-type]
  1436. copier.verify(progress=progress)
  1437. return self._complete_pack(f, path, len(copier), indexer, progress=progress)
  1438. def add_pack(
  1439. self,
  1440. ) -> tuple[BinaryIO, Callable[[], None], Callable[[], None]]:
  1441. """Add a new pack to this object store.
  1442. Returns: Fileobject to write to, a commit function to
  1443. call when the pack is finished and an abort
  1444. function.
  1445. """
  1446. import tempfile
  1447. fd, path = tempfile.mkstemp(dir=self.pack_dir, suffix=".pack")
  1448. f = os.fdopen(fd, "w+b")
  1449. os.chmod(path, PACK_MODE)
  1450. def commit() -> Optional["Pack"]:
  1451. if f.tell() > 0:
  1452. f.seek(0)
  1453. with PackData(path, f) as pd:
  1454. indexer = PackIndexer.for_pack_data(
  1455. pd,
  1456. resolve_ext_ref=self.get_raw, # type: ignore[arg-type]
  1457. )
  1458. return self._complete_pack(f, path, len(pd), indexer) # type: ignore[arg-type]
  1459. else:
  1460. f.close()
  1461. os.remove(path)
  1462. return None
  1463. def abort() -> None:
  1464. f.close()
  1465. os.remove(path)
  1466. return f, commit, abort # type: ignore[return-value]
  1467. def add_object(self, obj: ShaFile) -> None:
  1468. """Add a single object to this object store.
  1469. Args:
  1470. obj: Object to add
  1471. """
  1472. path = self._get_shafile_path(obj.id)
  1473. dir = os.path.dirname(path)
  1474. try:
  1475. os.mkdir(dir)
  1476. except FileExistsError:
  1477. pass
  1478. if os.path.exists(path):
  1479. return # Already there, no need to write again
  1480. with GitFile(path, "wb", mask=PACK_MODE, fsync=self.fsync_object_files) as f:
  1481. f.write(
  1482. obj.as_legacy_object(compression_level=self.loose_compression_level)
  1483. )
  1484. @classmethod
  1485. def init(cls, path: Union[str, os.PathLike[str]]) -> "DiskObjectStore":
  1486. """Initialize a new disk object store.
  1487. Creates the necessary directory structure for a Git object store.
  1488. Args:
  1489. path: Path where the object store should be created
  1490. Returns:
  1491. New DiskObjectStore instance
  1492. """
  1493. try:
  1494. os.mkdir(path)
  1495. except FileExistsError:
  1496. pass
  1497. os.mkdir(os.path.join(path, "info"))
  1498. os.mkdir(os.path.join(path, PACKDIR))
  1499. return cls(path)
  1500. def iter_prefix(self, prefix: bytes) -> Iterator[bytes]:
  1501. """Iterate over all object SHAs with the given prefix.
  1502. Args:
  1503. prefix: Hex prefix to search for (as bytes)
  1504. Returns:
  1505. Iterator of object SHAs (as bytes) matching the prefix
  1506. """
  1507. if len(prefix) < 2:
  1508. yield from super().iter_prefix(prefix)
  1509. return
  1510. seen = set()
  1511. dir = prefix[:2].decode()
  1512. rest = prefix[2:].decode()
  1513. try:
  1514. for name in os.listdir(os.path.join(self.path, dir)):
  1515. if name.startswith(rest):
  1516. sha = os.fsencode(dir + name)
  1517. if sha not in seen:
  1518. seen.add(sha)
  1519. yield sha
  1520. except FileNotFoundError:
  1521. pass
  1522. for p in self.packs:
  1523. bin_prefix = (
  1524. binascii.unhexlify(prefix)
  1525. if len(prefix) % 2 == 0
  1526. else binascii.unhexlify(prefix[:-1])
  1527. )
  1528. for sha in p.index.iter_prefix(bin_prefix):
  1529. sha = sha_to_hex(sha)
  1530. if sha.startswith(prefix) and sha not in seen:
  1531. seen.add(sha)
  1532. yield sha
  1533. for alternate in self.alternates:
  1534. for sha in alternate.iter_prefix(prefix):
  1535. if sha not in seen:
  1536. seen.add(sha)
  1537. yield sha
  1538. def get_commit_graph(self) -> Optional["CommitGraph"]:
  1539. """Get the commit graph for this object store.
  1540. Returns:
  1541. CommitGraph object if available, None otherwise
  1542. """
  1543. if not self._use_commit_graph:
  1544. return None
  1545. if self._commit_graph is None:
  1546. from .commit_graph import read_commit_graph
  1547. # Look for commit graph in our objects directory
  1548. graph_file = os.path.join(self.path, "info", "commit-graph")
  1549. if os.path.exists(graph_file):
  1550. self._commit_graph = read_commit_graph(graph_file)
  1551. return self._commit_graph
  1552. def write_commit_graph(
  1553. self, refs: Optional[Iterable[bytes]] = None, reachable: bool = True
  1554. ) -> None:
  1555. """Write a commit graph file for this object store.
  1556. Args:
  1557. refs: List of refs to include. If None, includes all refs from object store.
  1558. reachable: If True, includes all commits reachable from refs.
  1559. If False, only includes the direct ref targets.
  1560. """
  1561. from .commit_graph import get_reachable_commits
  1562. if refs is None:
  1563. # Get all commit objects from the object store
  1564. all_refs = []
  1565. # Iterate through all objects to find commits
  1566. for sha in self:
  1567. try:
  1568. obj = self[sha]
  1569. if obj.type_name == b"commit":
  1570. all_refs.append(sha)
  1571. except KeyError:
  1572. continue
  1573. else:
  1574. # Use provided refs
  1575. all_refs = list(refs)
  1576. if not all_refs:
  1577. return # No commits to include
  1578. if reachable:
  1579. # Get all reachable commits
  1580. commit_ids = get_reachable_commits(self, all_refs)
  1581. else:
  1582. # Just use the direct ref targets - ensure they're hex ObjectIDs
  1583. commit_ids = []
  1584. for ref in all_refs:
  1585. if isinstance(ref, bytes) and len(ref) == 40:
  1586. # Already hex ObjectID
  1587. commit_ids.append(ref)
  1588. elif isinstance(ref, bytes) and len(ref) == 20:
  1589. # Binary SHA, convert to hex ObjectID
  1590. from .objects import sha_to_hex
  1591. commit_ids.append(sha_to_hex(ref))
  1592. else:
  1593. # Assume it's already correct format
  1594. commit_ids.append(ref)
  1595. if commit_ids:
  1596. # Write commit graph directly to our object store path
  1597. # Generate the commit graph
  1598. from .commit_graph import generate_commit_graph
  1599. graph = generate_commit_graph(self, commit_ids)
  1600. if graph.entries:
  1601. # Ensure the info directory exists
  1602. info_dir = os.path.join(self.path, "info")
  1603. os.makedirs(info_dir, exist_ok=True)
  1604. # Write using GitFile for atomic operation
  1605. graph_path = os.path.join(info_dir, "commit-graph")
  1606. with GitFile(graph_path, "wb") as f:
  1607. assert isinstance(
  1608. f, _GitFile
  1609. ) # GitFile in write mode always returns _GitFile
  1610. graph.write_to_file(f)
  1611. # Clear cached commit graph so it gets reloaded
  1612. self._commit_graph = None
  1613. def prune(self, grace_period: Optional[int] = None) -> None:
  1614. """Prune/clean up this object store.
  1615. This removes temporary files that were left behind by interrupted
  1616. pack operations. These are files that start with ``tmp_pack_`` in the
  1617. repository directory or files with .pack extension but no corresponding
  1618. .idx file in the pack directory.
  1619. Args:
  1620. grace_period: Grace period in seconds for removing temporary files.
  1621. If None, uses DEFAULT_TEMPFILE_GRACE_PERIOD.
  1622. """
  1623. import glob
  1624. if grace_period is None:
  1625. grace_period = DEFAULT_TEMPFILE_GRACE_PERIOD
  1626. # Clean up tmp_pack_* files in the repository directory
  1627. for tmp_file in glob.glob(os.path.join(self.path, "tmp_pack_*")):
  1628. # Check if file is old enough (more than grace period)
  1629. mtime = os.path.getmtime(tmp_file)
  1630. if time.time() - mtime > grace_period:
  1631. os.remove(tmp_file)
  1632. # Clean up orphaned .pack files without corresponding .idx files
  1633. try:
  1634. pack_dir_contents = os.listdir(self.pack_dir)
  1635. except FileNotFoundError:
  1636. return
  1637. pack_files = {}
  1638. idx_files = set()
  1639. for name in pack_dir_contents:
  1640. if name.endswith(".pack"):
  1641. base_name = name[:-5] # Remove .pack extension
  1642. pack_files[base_name] = name
  1643. elif name.endswith(".idx"):
  1644. base_name = name[:-4] # Remove .idx extension
  1645. idx_files.add(base_name)
  1646. # Remove .pack files without corresponding .idx files
  1647. for base_name, pack_name in pack_files.items():
  1648. if base_name not in idx_files:
  1649. pack_path = os.path.join(self.pack_dir, pack_name)
  1650. # Check if file is old enough (more than grace period)
  1651. mtime = os.path.getmtime(pack_path)
  1652. if time.time() - mtime > grace_period:
  1653. os.remove(pack_path)
  1654. class MemoryObjectStore(PackCapableObjectStore):
  1655. """Object store that keeps all objects in memory."""
  1656. def __init__(self) -> None:
  1657. """Initialize a MemoryObjectStore.
  1658. Creates an empty in-memory object store.
  1659. """
  1660. super().__init__()
  1661. self._data: dict[bytes, ShaFile] = {}
  1662. self.pack_compression_level = -1
  1663. def _to_hexsha(self, sha: bytes) -> bytes:
  1664. if len(sha) == 40:
  1665. return sha
  1666. elif len(sha) == 20:
  1667. return sha_to_hex(sha)
  1668. else:
  1669. raise ValueError(f"Invalid sha {sha!r}")
  1670. def contains_loose(self, sha: bytes) -> bool:
  1671. """Check if a particular object is present by SHA1 and is loose."""
  1672. return self._to_hexsha(sha) in self._data
  1673. def contains_packed(self, sha: bytes) -> bool:
  1674. """Check if a particular object is present by SHA1 and is packed."""
  1675. return False
  1676. def __iter__(self) -> Iterator[bytes]:
  1677. """Iterate over the SHAs that are present in this store."""
  1678. return iter(self._data.keys())
  1679. @property
  1680. def packs(self) -> list[Pack]:
  1681. """List with pack objects."""
  1682. return []
  1683. def get_raw(self, name: ObjectID) -> tuple[int, bytes]:
  1684. """Obtain the raw text for an object.
  1685. Args:
  1686. name: sha for the object.
  1687. Returns: tuple with numeric type and object contents.
  1688. """
  1689. obj = self[self._to_hexsha(name)]
  1690. return obj.type_num, obj.as_raw_string()
  1691. def __getitem__(self, name: ObjectID) -> ShaFile:
  1692. """Retrieve an object by SHA.
  1693. Args:
  1694. name: SHA of the object (as hex string or bytes)
  1695. Returns:
  1696. Copy of the ShaFile object
  1697. Raises:
  1698. KeyError: If the object is not found
  1699. """
  1700. return self._data[self._to_hexsha(name)].copy()
  1701. def __delitem__(self, name: ObjectID) -> None:
  1702. """Delete an object from this store, for testing only."""
  1703. del self._data[self._to_hexsha(name)]
  1704. def add_object(self, obj: ShaFile) -> None:
  1705. """Add a single object to this object store."""
  1706. self._data[obj.id] = obj.copy()
  1707. def add_objects(
  1708. self,
  1709. objects: Iterable[tuple[ShaFile, Optional[str]]],
  1710. progress: Optional[Callable[[str], None]] = None,
  1711. ) -> None:
  1712. """Add a set of objects to this object store.
  1713. Args:
  1714. objects: Iterable over a list of (object, path) tuples
  1715. progress: Optional progress reporting function.
  1716. """
  1717. for obj, path in objects:
  1718. self.add_object(obj)
  1719. def add_pack(self) -> tuple[BinaryIO, Callable[[], None], Callable[[], None]]:
  1720. """Add a new pack to this object store.
  1721. Because this object store doesn't support packs, we extract and add the
  1722. individual objects.
  1723. Returns: Fileobject to write to and a commit function to
  1724. call when the pack is finished.
  1725. """
  1726. from tempfile import SpooledTemporaryFile
  1727. f = SpooledTemporaryFile(max_size=PACK_SPOOL_FILE_MAX_SIZE, prefix="incoming-")
  1728. def commit() -> None:
  1729. size = f.tell()
  1730. if size > 0:
  1731. f.seek(0)
  1732. p = PackData.from_file(f, size)
  1733. for obj in PackInflater.for_pack_data(p, self.get_raw): # type: ignore[arg-type]
  1734. self.add_object(obj)
  1735. p.close()
  1736. f.close()
  1737. else:
  1738. f.close()
  1739. def abort() -> None:
  1740. f.close()
  1741. return f, commit, abort # type: ignore[return-value]
  1742. def add_pack_data(
  1743. self,
  1744. count: int,
  1745. unpacked_objects: Iterator[UnpackedObject],
  1746. progress: Optional[Callable[[str], None]] = None,
  1747. ) -> None:
  1748. """Add pack data to this object store.
  1749. Args:
  1750. count: Number of items to add
  1751. unpacked_objects: Iterator of UnpackedObject instances
  1752. progress: Optional progress reporting function.
  1753. """
  1754. if count == 0:
  1755. return
  1756. # Since MemoryObjectStore doesn't support pack files, we need to
  1757. # extract individual objects. To handle deltas properly, we write
  1758. # to a temporary pack and then use PackInflater to resolve them.
  1759. f, commit, abort = self.add_pack()
  1760. try:
  1761. write_pack_data(
  1762. f.write,
  1763. unpacked_objects,
  1764. num_records=count,
  1765. progress=progress,
  1766. )
  1767. except BaseException:
  1768. abort()
  1769. raise
  1770. else:
  1771. commit()
  1772. def add_thin_pack(
  1773. self,
  1774. read_all: Callable[[], bytes],
  1775. read_some: Callable[[int], bytes],
  1776. progress: Optional[Callable[[str], None]] = None,
  1777. ) -> None:
  1778. """Add a new thin pack to this object store.
  1779. Thin packs are packs that contain deltas with parents that exist
  1780. outside the pack. Because this object store doesn't support packs, we
  1781. extract and add the individual objects.
  1782. Args:
  1783. read_all: Read function that blocks until the number of
  1784. requested bytes are read.
  1785. read_some: Read function that returns at least one byte, but may
  1786. not return the number of bytes requested.
  1787. progress: Optional progress reporting function.
  1788. """
  1789. f, commit, abort = self.add_pack()
  1790. try:
  1791. copier = PackStreamCopier(read_all, read_some, f) # type: ignore[arg-type]
  1792. copier.verify()
  1793. except BaseException:
  1794. abort()
  1795. raise
  1796. else:
  1797. commit()
  1798. class ObjectIterator(Protocol):
  1799. """Interface for iterating over objects."""
  1800. def iterobjects(self) -> Iterator[ShaFile]:
  1801. """Iterate over all objects.
  1802. Returns:
  1803. Iterator of ShaFile objects
  1804. """
  1805. raise NotImplementedError(self.iterobjects)
  1806. def tree_lookup_path(
  1807. lookup_obj: Callable[[bytes], ShaFile], root_sha: bytes, path: bytes
  1808. ) -> tuple[int, bytes]:
  1809. """Look up an object in a Git tree.
  1810. Args:
  1811. lookup_obj: Callback for retrieving object by SHA1
  1812. root_sha: SHA1 of the root tree
  1813. path: Path to lookup
  1814. Returns: A tuple of (mode, SHA) of the resulting path.
  1815. """
  1816. tree = lookup_obj(root_sha)
  1817. if not isinstance(tree, Tree):
  1818. raise NotTreeError(root_sha)
  1819. return tree.lookup_path(lookup_obj, path)
  1820. def _collect_filetree_revs(
  1821. obj_store: ObjectContainer, tree_sha: ObjectID, kset: set[ObjectID]
  1822. ) -> None:
  1823. """Collect SHA1s of files and directories for specified tree.
  1824. Args:
  1825. obj_store: Object store to get objects by SHA from
  1826. tree_sha: tree reference to walk
  1827. kset: set to fill with references to files and directories
  1828. """
  1829. filetree = obj_store[tree_sha]
  1830. assert isinstance(filetree, Tree)
  1831. for name, mode, sha in filetree.iteritems():
  1832. assert mode is not None
  1833. assert sha is not None
  1834. if not S_ISGITLINK(mode) and sha not in kset:
  1835. kset.add(sha)
  1836. if stat.S_ISDIR(mode):
  1837. _collect_filetree_revs(obj_store, sha, kset)
  1838. def _split_commits_and_tags(
  1839. obj_store: ObjectContainer, lst: Iterable[bytes], *, ignore_unknown: bool = False
  1840. ) -> tuple[set[bytes], set[bytes], set[bytes]]:
  1841. """Split object id list into three lists with commit, tag, and other SHAs.
  1842. Commits referenced by tags are included into commits
  1843. list as well. Only SHA1s known in this repository will get
  1844. through, and unless ignore_unknown argument is True, KeyError
  1845. is thrown for SHA1 missing in the repository
  1846. Args:
  1847. obj_store: Object store to get objects by SHA1 from
  1848. lst: Collection of commit and tag SHAs
  1849. ignore_unknown: True to skip SHA1 missing in the repository
  1850. silently.
  1851. Returns: A tuple of (commits, tags, others) SHA1s
  1852. """
  1853. commits: set[bytes] = set()
  1854. tags: set[bytes] = set()
  1855. others: set[bytes] = set()
  1856. for e in lst:
  1857. try:
  1858. o = obj_store[e]
  1859. except KeyError:
  1860. if not ignore_unknown:
  1861. raise
  1862. else:
  1863. if isinstance(o, Commit):
  1864. commits.add(e)
  1865. elif isinstance(o, Tag):
  1866. tags.add(e)
  1867. tagged = o.object[1]
  1868. c, t, os = _split_commits_and_tags(
  1869. obj_store, [tagged], ignore_unknown=ignore_unknown
  1870. )
  1871. commits |= c
  1872. tags |= t
  1873. others |= os
  1874. else:
  1875. others.add(e)
  1876. return (commits, tags, others)
  1877. class MissingObjectFinder:
  1878. """Find the objects missing from another object store.
  1879. Args:
  1880. object_store: Object store containing at least all objects to be
  1881. sent
  1882. haves: SHA1s of commits not to send (already present in target)
  1883. wants: SHA1s of commits to send
  1884. progress: Optional function to report progress to.
  1885. get_tagged: Function that returns a dict of pointed-to sha -> tag
  1886. sha for including tags.
  1887. get_parents: Optional function for getting the parents of a commit.
  1888. """
  1889. def __init__(
  1890. self,
  1891. object_store: BaseObjectStore,
  1892. haves: Iterable[bytes],
  1893. wants: Iterable[bytes],
  1894. *,
  1895. shallow: Optional[Set[bytes]] = None,
  1896. progress: Optional[Callable[[bytes], None]] = None,
  1897. get_tagged: Optional[Callable[[], dict[bytes, bytes]]] = None,
  1898. get_parents: Callable[[Commit], list[bytes]] = lambda commit: commit.parents,
  1899. ) -> None:
  1900. """Initialize a MissingObjectFinder.
  1901. Args:
  1902. object_store: Object store containing objects
  1903. haves: SHA1s of objects already present in target
  1904. wants: SHA1s of objects to send
  1905. shallow: Set of shallow commit SHA1s
  1906. progress: Optional progress reporting callback
  1907. get_tagged: Function returning dict of pointed-to sha -> tag sha
  1908. get_parents: Function for getting commit parents
  1909. """
  1910. self.object_store = object_store
  1911. if shallow is None:
  1912. shallow = set()
  1913. self._get_parents = get_parents
  1914. # process Commits and Tags differently
  1915. # Note, while haves may list commits/tags not available locally,
  1916. # and such SHAs would get filtered out by _split_commits_and_tags,
  1917. # wants shall list only known SHAs, and otherwise
  1918. # _split_commits_and_tags fails with KeyError
  1919. have_commits, have_tags, have_others = _split_commits_and_tags(
  1920. object_store, haves, ignore_unknown=True
  1921. )
  1922. want_commits, want_tags, want_others = _split_commits_and_tags(
  1923. object_store, wants, ignore_unknown=False
  1924. )
  1925. # all_ancestors is a set of commits that shall not be sent
  1926. # (complete repository up to 'haves')
  1927. all_ancestors = _collect_ancestors(
  1928. object_store,
  1929. have_commits,
  1930. shallow=frozenset(shallow),
  1931. get_parents=self._get_parents,
  1932. )[0]
  1933. # all_missing - complete set of commits between haves and wants
  1934. # common - commits from all_ancestors we hit into while
  1935. # traversing parent hierarchy of wants
  1936. missing_commits, common_commits = _collect_ancestors(
  1937. object_store,
  1938. want_commits,
  1939. frozenset(all_ancestors),
  1940. shallow=frozenset(shallow),
  1941. get_parents=self._get_parents,
  1942. )
  1943. self.remote_has: set[bytes] = set()
  1944. # Now, fill sha_done with commits and revisions of
  1945. # files and directories known to be both locally
  1946. # and on target. Thus these commits and files
  1947. # won't get selected for fetch
  1948. for h in common_commits:
  1949. self.remote_has.add(h)
  1950. cmt = object_store[h]
  1951. assert isinstance(cmt, Commit)
  1952. _collect_filetree_revs(object_store, cmt.tree, self.remote_has)
  1953. # record tags we have as visited, too
  1954. for t in have_tags:
  1955. self.remote_has.add(t)
  1956. self.sha_done = set(self.remote_has)
  1957. # in fact, what we 'want' is commits, tags, and others
  1958. # we've found missing
  1959. self.objects_to_send: set[
  1960. tuple[ObjectID, Optional[bytes], Optional[int], bool]
  1961. ] = {(w, None, Commit.type_num, False) for w in missing_commits}
  1962. missing_tags = want_tags.difference(have_tags)
  1963. self.objects_to_send.update(
  1964. {(w, None, Tag.type_num, False) for w in missing_tags}
  1965. )
  1966. missing_others = want_others.difference(have_others)
  1967. self.objects_to_send.update({(w, None, None, False) for w in missing_others})
  1968. if progress is None:
  1969. self.progress: Callable[[bytes], None] = lambda x: None
  1970. else:
  1971. self.progress = progress
  1972. self._tagged = (get_tagged and get_tagged()) or {}
  1973. def get_remote_has(self) -> set[bytes]:
  1974. """Get the set of SHAs the remote has.
  1975. Returns:
  1976. Set of SHA1s that the remote side already has
  1977. """
  1978. return self.remote_has
  1979. def add_todo(
  1980. self, entries: Iterable[tuple[ObjectID, Optional[bytes], Optional[int], bool]]
  1981. ) -> None:
  1982. """Add objects to the todo list.
  1983. Args:
  1984. entries: Iterable of tuples (sha, name, type_num, is_leaf)
  1985. """
  1986. self.objects_to_send.update([e for e in entries if e[0] not in self.sha_done])
  1987. def __next__(self) -> tuple[bytes, Optional[PackHint]]:
  1988. """Get the next object to send.
  1989. Returns:
  1990. Tuple of (sha, pack_hint)
  1991. Raises:
  1992. StopIteration: When no more objects to send
  1993. """
  1994. while True:
  1995. if not self.objects_to_send:
  1996. self.progress(
  1997. f"counting objects: {len(self.sha_done)}, done.\n".encode("ascii")
  1998. )
  1999. raise StopIteration
  2000. (sha, name, type_num, leaf) = self.objects_to_send.pop()
  2001. if sha not in self.sha_done:
  2002. break
  2003. if not leaf:
  2004. o = self.object_store[sha]
  2005. if isinstance(o, Commit):
  2006. self.add_todo([(o.tree, b"", Tree.type_num, False)])
  2007. elif isinstance(o, Tree):
  2008. todos = []
  2009. for n, m, s in o.iteritems():
  2010. assert m is not None
  2011. assert n is not None
  2012. assert s is not None
  2013. if not S_ISGITLINK(m):
  2014. todos.append(
  2015. (
  2016. s,
  2017. n,
  2018. (Blob.type_num if stat.S_ISREG(m) else Tree.type_num),
  2019. not stat.S_ISDIR(m),
  2020. )
  2021. )
  2022. self.add_todo(todos)
  2023. elif isinstance(o, Tag):
  2024. self.add_todo([(o.object[1], None, o.object[0].type_num, False)])
  2025. if sha in self._tagged:
  2026. self.add_todo([(self._tagged[sha], None, None, True)])
  2027. self.sha_done.add(sha)
  2028. if len(self.sha_done) % 1000 == 0:
  2029. self.progress(f"counting objects: {len(self.sha_done)}\r".encode("ascii"))
  2030. if type_num is None:
  2031. pack_hint = None
  2032. else:
  2033. pack_hint = (type_num, name)
  2034. return (sha, pack_hint)
  2035. def __iter__(self) -> Iterator[tuple[bytes, Optional[PackHint]]]:
  2036. """Return iterator over objects to send.
  2037. Returns:
  2038. Self (this class implements the iterator protocol)
  2039. """
  2040. return self
  2041. class ObjectStoreGraphWalker:
  2042. """Graph walker that finds what commits are missing from an object store."""
  2043. heads: set[ObjectID]
  2044. """Revisions without descendants in the local repo."""
  2045. get_parents: Callable[[ObjectID], list[ObjectID]]
  2046. """Function to retrieve parents in the local repo."""
  2047. shallow: set[ObjectID]
  2048. def __init__(
  2049. self,
  2050. local_heads: Iterable[ObjectID],
  2051. get_parents: Callable[[ObjectID], list[ObjectID]],
  2052. shallow: Optional[set[ObjectID]] = None,
  2053. update_shallow: Optional[
  2054. Callable[[Optional[set[ObjectID]], Optional[set[ObjectID]]], None]
  2055. ] = None,
  2056. ) -> None:
  2057. """Create a new instance.
  2058. Args:
  2059. local_heads: Heads to start search with
  2060. get_parents: Function for finding the parents of a SHA1.
  2061. shallow: Set of shallow commits.
  2062. update_shallow: Function to update shallow commits.
  2063. """
  2064. self.heads = set(local_heads)
  2065. self.get_parents = get_parents
  2066. self.parents: dict[ObjectID, Optional[list[ObjectID]]] = {}
  2067. if shallow is None:
  2068. shallow = set()
  2069. self.shallow = shallow
  2070. self.update_shallow = update_shallow
  2071. def nak(self) -> None:
  2072. """Nothing in common was found."""
  2073. def ack(self, sha: ObjectID) -> None:
  2074. """Ack that a revision and its ancestors are present in the source."""
  2075. if len(sha) != 40:
  2076. raise ValueError(f"unexpected sha {sha!r} received")
  2077. ancestors = {sha}
  2078. # stop if we run out of heads to remove
  2079. while self.heads:
  2080. for a in ancestors:
  2081. if a in self.heads:
  2082. self.heads.remove(a)
  2083. # collect all ancestors
  2084. new_ancestors = set()
  2085. for a in ancestors:
  2086. ps = self.parents.get(a)
  2087. if ps is not None:
  2088. new_ancestors.update(ps)
  2089. self.parents[a] = None
  2090. # no more ancestors; stop
  2091. if not new_ancestors:
  2092. break
  2093. ancestors = new_ancestors
  2094. def next(self) -> Optional[ObjectID]:
  2095. """Iterate over ancestors of heads in the target."""
  2096. if self.heads:
  2097. ret = self.heads.pop()
  2098. try:
  2099. ps = self.get_parents(ret)
  2100. except KeyError:
  2101. return None
  2102. self.parents[ret] = ps
  2103. self.heads.update([p for p in ps if p not in self.parents])
  2104. return ret
  2105. return None
  2106. __next__ = next
  2107. def commit_tree_changes(
  2108. object_store: BaseObjectStore,
  2109. tree: Union[ObjectID, Tree],
  2110. changes: Sequence[tuple[bytes, Optional[int], Optional[bytes]]],
  2111. ) -> ObjectID:
  2112. """Commit a specified set of changes to a tree structure.
  2113. This will apply a set of changes on top of an existing tree, storing new
  2114. objects in object_store.
  2115. changes are a list of tuples with (path, mode, object_sha).
  2116. Paths can be both blobs and trees. See the mode and
  2117. object sha to None deletes the path.
  2118. This method works especially well if there are only a small
  2119. number of changes to a big tree. For a large number of changes
  2120. to a large tree, use e.g. commit_tree.
  2121. Args:
  2122. object_store: Object store to store new objects in
  2123. and retrieve old ones from.
  2124. tree: Original tree root (SHA or Tree object)
  2125. changes: changes to apply
  2126. Returns: New tree root object
  2127. """
  2128. # TODO(jelmer): Save up the objects and add them using .add_objects
  2129. # rather than with individual calls to .add_object.
  2130. # Handle both Tree object and SHA
  2131. if isinstance(tree, Tree):
  2132. tree_obj: Tree = tree
  2133. else:
  2134. sha_obj = object_store[tree]
  2135. assert isinstance(sha_obj, Tree)
  2136. tree_obj = sha_obj
  2137. nested_changes: dict[bytes, list[tuple[bytes, Optional[int], Optional[bytes]]]] = {}
  2138. for path, new_mode, new_sha in changes:
  2139. try:
  2140. (dirname, subpath) = path.split(b"/", 1)
  2141. except ValueError:
  2142. if new_sha is None:
  2143. del tree_obj[path]
  2144. else:
  2145. assert new_mode is not None
  2146. tree_obj[path] = (new_mode, new_sha)
  2147. else:
  2148. nested_changes.setdefault(dirname, []).append((subpath, new_mode, new_sha))
  2149. for name, subchanges in nested_changes.items():
  2150. try:
  2151. orig_subtree_id: Union[bytes, Tree] = tree_obj[name][1]
  2152. except KeyError:
  2153. # For new directories, pass an empty Tree object
  2154. orig_subtree_id = Tree()
  2155. subtree_id = commit_tree_changes(object_store, orig_subtree_id, subchanges)
  2156. subtree = object_store[subtree_id]
  2157. assert isinstance(subtree, Tree)
  2158. if len(subtree) == 0:
  2159. del tree_obj[name]
  2160. else:
  2161. tree_obj[name] = (stat.S_IFDIR, subtree.id)
  2162. object_store.add_object(tree_obj)
  2163. return tree_obj.id
  2164. class OverlayObjectStore(BaseObjectStore):
  2165. """Object store that can overlay multiple object stores."""
  2166. def __init__(
  2167. self,
  2168. bases: list[BaseObjectStore],
  2169. add_store: Optional[BaseObjectStore] = None,
  2170. ) -> None:
  2171. """Initialize an OverlayObjectStore.
  2172. Args:
  2173. bases: List of base object stores to overlay
  2174. add_store: Optional store to write new objects to
  2175. """
  2176. self.bases = bases
  2177. self.add_store = add_store
  2178. def add_object(self, object: ShaFile) -> None:
  2179. """Add a single object to the store.
  2180. Args:
  2181. object: Object to add
  2182. Raises:
  2183. NotImplementedError: If no add_store was provided
  2184. """
  2185. if self.add_store is None:
  2186. raise NotImplementedError(self.add_object)
  2187. return self.add_store.add_object(object)
  2188. def add_objects(
  2189. self,
  2190. objects: Sequence[tuple[ShaFile, Optional[str]]],
  2191. progress: Optional[Callable[[str], None]] = None,
  2192. ) -> Optional[Pack]:
  2193. """Add multiple objects to the store.
  2194. Args:
  2195. objects: Iterator of objects to add
  2196. progress: Optional progress reporting callback
  2197. Raises:
  2198. NotImplementedError: If no add_store was provided
  2199. """
  2200. if self.add_store is None:
  2201. raise NotImplementedError(self.add_object)
  2202. return self.add_store.add_objects(objects, progress)
  2203. @property
  2204. def packs(self) -> list[Pack]:
  2205. """Get the list of packs from all overlaid stores.
  2206. Returns:
  2207. Combined list of packs from all base stores
  2208. """
  2209. ret = []
  2210. for b in self.bases:
  2211. ret.extend(b.packs)
  2212. return ret
  2213. def __iter__(self) -> Iterator[ObjectID]:
  2214. """Iterate over all object SHAs in the overlaid stores.
  2215. Returns:
  2216. Iterator of object SHAs (deduped across stores)
  2217. """
  2218. done = set()
  2219. for b in self.bases:
  2220. for o_id in b:
  2221. if o_id not in done:
  2222. yield o_id
  2223. done.add(o_id)
  2224. def iterobjects_subset(
  2225. self, shas: Iterable[bytes], *, allow_missing: bool = False
  2226. ) -> Iterator[ShaFile]:
  2227. """Iterate over a subset of objects from the overlaid stores.
  2228. Args:
  2229. shas: Iterable of object SHAs to retrieve
  2230. allow_missing: If True, skip missing objects; if False, raise KeyError
  2231. Returns:
  2232. Iterator of ShaFile objects
  2233. Raises:
  2234. KeyError: If an object is missing and allow_missing is False
  2235. """
  2236. todo = set(shas)
  2237. found: set[bytes] = set()
  2238. for b in self.bases:
  2239. # Create a copy of todo for each base to avoid modifying
  2240. # the set while iterating through it
  2241. current_todo = todo - found
  2242. for o in b.iterobjects_subset(current_todo, allow_missing=True):
  2243. yield o
  2244. found.add(o.id)
  2245. # Check for any remaining objects not found
  2246. missing = todo - found
  2247. if missing and not allow_missing:
  2248. raise KeyError(next(iter(missing)))
  2249. def iter_unpacked_subset(
  2250. self,
  2251. shas: Iterable[bytes],
  2252. include_comp: bool = False,
  2253. allow_missing: bool = False,
  2254. convert_ofs_delta: bool = True,
  2255. ) -> Iterator[UnpackedObject]:
  2256. """Iterate over unpacked objects from the overlaid stores.
  2257. Args:
  2258. shas: Iterable of object SHAs to retrieve
  2259. include_comp: Whether to include compressed data
  2260. allow_missing: If True, skip missing objects; if False, raise KeyError
  2261. convert_ofs_delta: Whether to convert OFS_DELTA objects
  2262. Returns:
  2263. Iterator of unpacked objects
  2264. Raises:
  2265. KeyError: If an object is missing and allow_missing is False
  2266. """
  2267. todo = set(shas)
  2268. for b in self.bases:
  2269. for o in b.iter_unpacked_subset(
  2270. todo,
  2271. include_comp=include_comp,
  2272. allow_missing=True,
  2273. convert_ofs_delta=convert_ofs_delta,
  2274. ):
  2275. yield o
  2276. todo.remove(o.sha())
  2277. if todo and not allow_missing:
  2278. raise KeyError(next(iter(todo)))
  2279. def get_raw(self, sha_id: ObjectID) -> tuple[int, bytes]:
  2280. """Get the raw object data from the overlaid stores.
  2281. Args:
  2282. sha_id: SHA of the object
  2283. Returns:
  2284. Tuple of (type_num, raw_data)
  2285. Raises:
  2286. KeyError: If object not found in any base store
  2287. """
  2288. for b in self.bases:
  2289. try:
  2290. return b.get_raw(sha_id)
  2291. except KeyError:
  2292. pass
  2293. raise KeyError(sha_id)
  2294. def contains_packed(self, sha: bytes) -> bool:
  2295. """Check if an object is packed in any base store.
  2296. Args:
  2297. sha: SHA of the object
  2298. Returns:
  2299. True if object is packed in any base store
  2300. """
  2301. for b in self.bases:
  2302. if b.contains_packed(sha):
  2303. return True
  2304. return False
  2305. def contains_loose(self, sha: bytes) -> bool:
  2306. """Check if an object is loose in any base store.
  2307. Args:
  2308. sha: SHA of the object
  2309. Returns:
  2310. True if object is loose in any base store
  2311. """
  2312. for b in self.bases:
  2313. if b.contains_loose(sha):
  2314. return True
  2315. return False
  2316. def read_packs_file(f: BinaryIO) -> Iterator[str]:
  2317. """Yield the packs listed in a packs file."""
  2318. for line in f.read().splitlines():
  2319. if not line:
  2320. continue
  2321. (kind, name) = line.split(b" ", 1)
  2322. if kind != b"P":
  2323. continue
  2324. yield os.fsdecode(name)
  2325. class BucketBasedObjectStore(PackBasedObjectStore):
  2326. """Object store implementation that uses a bucket store like S3 as backend."""
  2327. def _iter_loose_objects(self) -> Iterator[bytes]:
  2328. """Iterate over the SHAs of all loose objects."""
  2329. return iter([])
  2330. def _get_loose_object(self, sha: bytes) -> None:
  2331. return None
  2332. def delete_loose_object(self, sha: bytes) -> None:
  2333. """Delete a loose object (no-op for bucket stores).
  2334. Bucket-based stores don't have loose objects, so this is a no-op.
  2335. Args:
  2336. sha: SHA of the object to delete
  2337. """
  2338. # Doesn't exist..
  2339. def pack_loose_objects(
  2340. self, progress: Optional[Callable[[str], None]] = None
  2341. ) -> int:
  2342. """Pack loose objects. Returns number of objects packed.
  2343. BucketBasedObjectStore doesn't support loose objects, so this is a no-op.
  2344. Args:
  2345. progress: Optional progress reporting callback (ignored)
  2346. """
  2347. return 0
  2348. def _remove_pack_by_name(self, name: str) -> None:
  2349. """Remove a pack by name. Subclasses should implement this."""
  2350. raise NotImplementedError(self._remove_pack_by_name)
  2351. def _iter_pack_names(self) -> Iterator[str]:
  2352. raise NotImplementedError(self._iter_pack_names)
  2353. def _get_pack(self, name: str) -> Pack:
  2354. raise NotImplementedError(self._get_pack)
  2355. def _update_pack_cache(self) -> list[Pack]:
  2356. pack_files = set(self._iter_pack_names())
  2357. # Open newly appeared pack files
  2358. new_packs = []
  2359. for f in pack_files:
  2360. if f not in self._pack_cache:
  2361. pack = self._get_pack(f)
  2362. new_packs.append(pack)
  2363. self._pack_cache[f] = pack
  2364. # Remove disappeared pack files
  2365. for f in set(self._pack_cache) - pack_files:
  2366. self._pack_cache.pop(f).close()
  2367. return new_packs
  2368. def _upload_pack(
  2369. self, basename: str, pack_file: BinaryIO, index_file: BinaryIO
  2370. ) -> None:
  2371. raise NotImplementedError
  2372. def add_pack(self) -> tuple[BinaryIO, Callable[[], None], Callable[[], None]]:
  2373. """Add a new pack to this object store.
  2374. Returns: Fileobject to write to, a commit function to
  2375. call when the pack is finished and an abort
  2376. function.
  2377. """
  2378. import tempfile
  2379. pf = tempfile.SpooledTemporaryFile(
  2380. max_size=PACK_SPOOL_FILE_MAX_SIZE, prefix="incoming-"
  2381. )
  2382. def commit() -> Optional[Pack]:
  2383. if pf.tell() == 0:
  2384. pf.close()
  2385. return None
  2386. pf.seek(0)
  2387. p = PackData(pf.name, pf)
  2388. entries = p.sorted_entries()
  2389. basename = iter_sha1(entry[0] for entry in entries).decode("ascii")
  2390. idxf = tempfile.SpooledTemporaryFile(
  2391. max_size=PACK_SPOOL_FILE_MAX_SIZE, prefix="incoming-"
  2392. )
  2393. checksum = p.get_stored_checksum()
  2394. write_pack_index(idxf, entries, checksum, version=self.pack_index_version)
  2395. idxf.seek(0)
  2396. idx = load_pack_index_file(basename + ".idx", idxf)
  2397. for pack in self.packs:
  2398. if pack.get_stored_checksum() == p.get_stored_checksum():
  2399. p.close()
  2400. idx.close()
  2401. pf.close()
  2402. idxf.close()
  2403. return pack
  2404. pf.seek(0)
  2405. idxf.seek(0)
  2406. self._upload_pack(basename, pf, idxf) # type: ignore[arg-type]
  2407. final_pack = Pack.from_objects(p, idx)
  2408. self._add_cached_pack(basename, final_pack)
  2409. pf.close()
  2410. idxf.close()
  2411. return final_pack
  2412. return pf, commit, pf.close # type: ignore[return-value]
  2413. def _collect_ancestors(
  2414. store: ObjectContainer,
  2415. heads: Iterable[ObjectID],
  2416. common: frozenset[ObjectID] = frozenset(),
  2417. shallow: frozenset[ObjectID] = frozenset(),
  2418. get_parents: Callable[[Commit], list[bytes]] = lambda commit: commit.parents,
  2419. ) -> tuple[set[ObjectID], set[ObjectID]]:
  2420. """Collect all ancestors of heads up to (excluding) those in common.
  2421. Args:
  2422. store: Object store to get commits from
  2423. heads: commits to start from
  2424. common: commits to end at, or empty set to walk repository
  2425. completely
  2426. shallow: Set of shallow commits
  2427. get_parents: Optional function for getting the parents of a
  2428. commit.
  2429. Returns: a tuple (A, B) where A - all commits reachable
  2430. from heads but not present in common, B - common (shared) elements
  2431. that are directly reachable from heads
  2432. """
  2433. bases = set()
  2434. commits = set()
  2435. queue: list[ObjectID] = []
  2436. queue.extend(heads)
  2437. # Try to use commit graph if available
  2438. commit_graph = store.get_commit_graph()
  2439. while queue:
  2440. e = queue.pop(0)
  2441. if e in common:
  2442. bases.add(e)
  2443. elif e not in commits:
  2444. commits.add(e)
  2445. if e in shallow:
  2446. continue
  2447. # Try to use commit graph for parent lookup
  2448. parents = None
  2449. if commit_graph:
  2450. parents = commit_graph.get_parents(e)
  2451. if parents is None:
  2452. # Fall back to loading the object
  2453. cmt = store[e]
  2454. assert isinstance(cmt, Commit)
  2455. parents = get_parents(cmt)
  2456. queue.extend(parents)
  2457. return (commits, bases)
  2458. def iter_tree_contents(
  2459. store: ObjectContainer, tree_id: Optional[ObjectID], *, include_trees: bool = False
  2460. ) -> Iterator[TreeEntry]:
  2461. """Iterate the contents of a tree and all subtrees.
  2462. Iteration is depth-first pre-order, as in e.g. os.walk.
  2463. Args:
  2464. store: Object store to get trees from
  2465. tree_id: SHA1 of the tree.
  2466. include_trees: If True, include tree objects in the iteration.
  2467. Yields: TreeEntry namedtuples for all the objects in a tree.
  2468. """
  2469. if tree_id is None:
  2470. return
  2471. # This could be fairly easily generalized to >2 trees if we find a use
  2472. # case.
  2473. todo = [TreeEntry(b"", stat.S_IFDIR, tree_id)]
  2474. while todo:
  2475. entry = todo.pop()
  2476. assert entry.mode is not None
  2477. if stat.S_ISDIR(entry.mode):
  2478. extra = []
  2479. assert entry.sha is not None
  2480. tree = store[entry.sha]
  2481. assert isinstance(tree, Tree)
  2482. for subentry in tree.iteritems(name_order=True):
  2483. assert entry.path is not None
  2484. extra.append(subentry.in_path(entry.path))
  2485. todo.extend(reversed(extra))
  2486. if not stat.S_ISDIR(entry.mode) or include_trees:
  2487. yield entry
  2488. def iter_commit_contents(
  2489. store: ObjectContainer,
  2490. commit: Union[Commit, bytes],
  2491. *,
  2492. include: Optional[Sequence[Union[str, bytes, Path]]] = None,
  2493. ) -> Iterator[TreeEntry]:
  2494. """Iterate the contents of the repository at the specified commit.
  2495. This is a wrapper around iter_tree_contents() and
  2496. tree_lookup_path() to simplify the common task of getting the
  2497. contest of a repo at a particular commit. See also
  2498. dulwich.index.build_file_from_blob() for writing individual files
  2499. to disk.
  2500. Args:
  2501. store: Object store to get trees from
  2502. commit: Commit object, or SHA1 of a commit
  2503. include: if provided, only the entries whose paths are in the
  2504. list, or whose parent tree is in the list, will be
  2505. included. Note that duplicate or overlapping paths
  2506. (e.g. ["foo", "foo/bar"]) may result in duplicate entries
  2507. Yields: TreeEntry namedtuples for all matching files in a commit.
  2508. """
  2509. sha = commit.id if isinstance(commit, Commit) else commit
  2510. if not isinstance(obj := store[sha], Commit):
  2511. raise TypeError(
  2512. f"{sha.decode('ascii')} should be ID of a Commit, but is {type(obj)}"
  2513. )
  2514. commit = obj
  2515. encoding = commit.encoding or "utf-8"
  2516. include_bytes: list[bytes] = (
  2517. [
  2518. path if isinstance(path, bytes) else str(path).encode(encoding)
  2519. for path in include
  2520. ]
  2521. if include is not None
  2522. else [b""]
  2523. )
  2524. for path in include_bytes:
  2525. mode, obj_id = tree_lookup_path(store.__getitem__, commit.tree, path)
  2526. # Iterate all contained files if path points to a dir, otherwise just get that
  2527. # single file
  2528. if isinstance(store[obj_id], Tree):
  2529. for entry in iter_tree_contents(store, obj_id):
  2530. yield entry.in_path(path)
  2531. else:
  2532. yield TreeEntry(path, mode, obj_id)
  2533. def peel_sha(store: ObjectContainer, sha: bytes) -> tuple[ShaFile, ShaFile]:
  2534. """Peel all tags from a SHA.
  2535. Args:
  2536. store: Object store to get objects from
  2537. sha: The object SHA to peel.
  2538. Returns: The fully-peeled SHA1 of a tag object, after peeling all
  2539. intermediate tags; if the original ref does not point to a tag,
  2540. this will equal the original SHA1.
  2541. """
  2542. unpeeled = obj = store[sha]
  2543. obj_class = object_class(obj.type_name)
  2544. while obj_class is Tag:
  2545. assert isinstance(obj, Tag)
  2546. obj_class, sha = obj.object
  2547. obj = store[sha]
  2548. return unpeeled, obj