object_store.py 91 KB

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