object_store.py 91 KB

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