object_store.py 85 KB

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