object_store.py 91 KB

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