object_store.py 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924
  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 public 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 warnings
  28. from collections.abc import Iterable, Iterator, Sequence
  29. from contextlib import suppress
  30. from io import BytesIO
  31. from typing import (
  32. Callable,
  33. Optional,
  34. Protocol,
  35. cast,
  36. )
  37. from .errors import NotTreeError
  38. from .file import GitFile
  39. from .objects import (
  40. S_ISGITLINK,
  41. ZERO_SHA,
  42. Blob,
  43. Commit,
  44. ObjectID,
  45. ShaFile,
  46. Tag,
  47. Tree,
  48. TreeEntry,
  49. hex_to_filename,
  50. hex_to_sha,
  51. object_class,
  52. sha_to_hex,
  53. valid_hexsha,
  54. )
  55. from .pack import (
  56. PACK_SPOOL_FILE_MAX_SIZE,
  57. ObjectContainer,
  58. Pack,
  59. PackData,
  60. PackedObjectContainer,
  61. PackFileDisappeared,
  62. PackHint,
  63. PackIndexer,
  64. PackInflater,
  65. PackStreamCopier,
  66. UnpackedObject,
  67. extend_pack,
  68. full_unpacked_object,
  69. generate_unpacked_objects,
  70. iter_sha1,
  71. load_pack_index_file,
  72. pack_objects_to_data,
  73. write_pack_data,
  74. write_pack_index,
  75. )
  76. from .protocol import DEPTH_INFINITE
  77. from .refs import PEELED_TAG_SUFFIX, Ref
  78. INFODIR = "info"
  79. PACKDIR = "pack"
  80. # use permissions consistent with Git; just readable by everyone
  81. # TODO: should packs also be non-writable on Windows? if so, that
  82. # would requite some rather significant adjustments to the test suite
  83. PACK_MODE = 0o444 if sys.platform != "win32" else 0o644
  84. class PackContainer(Protocol):
  85. def add_pack(self) -> tuple[BytesIO, Callable[[], None], Callable[[], None]]:
  86. """Add a new pack."""
  87. class BaseObjectStore:
  88. """Object store interface."""
  89. def determine_wants_all(
  90. self, refs: dict[Ref, ObjectID], depth: Optional[int] = None
  91. ) -> list[ObjectID]:
  92. def _want_deepen(sha):
  93. if not depth:
  94. return False
  95. if depth == DEPTH_INFINITE:
  96. return True
  97. return depth > self._get_depth(sha)
  98. return [
  99. sha
  100. for (ref, sha) in refs.items()
  101. if (sha not in self or _want_deepen(sha))
  102. and not ref.endswith(PEELED_TAG_SUFFIX)
  103. and not sha == ZERO_SHA
  104. ]
  105. def contains_loose(self, sha) -> bool:
  106. """Check if a particular object is present by SHA1 and is loose."""
  107. raise NotImplementedError(self.contains_loose)
  108. def __contains__(self, sha1: bytes) -> bool:
  109. """Check if a particular object is present by SHA1.
  110. This method makes no distinction between loose and packed objects.
  111. """
  112. return self.contains_loose(sha1)
  113. @property
  114. def packs(self):
  115. """Iterable of pack objects."""
  116. raise NotImplementedError
  117. def get_raw(self, name) -> tuple[int, bytes]:
  118. """Obtain the raw text for an object.
  119. Args:
  120. name: sha for the object.
  121. Returns: tuple with numeric type and object contents.
  122. """
  123. raise NotImplementedError(self.get_raw)
  124. def __getitem__(self, sha1: ObjectID) -> ShaFile:
  125. """Obtain an object by SHA1."""
  126. type_num, uncomp = self.get_raw(sha1)
  127. return ShaFile.from_raw_string(type_num, uncomp, sha=sha1)
  128. def __iter__(self):
  129. """Iterate over the SHAs that are present in this store."""
  130. raise NotImplementedError(self.__iter__)
  131. def add_object(self, obj) -> None:
  132. """Add a single object to this object store."""
  133. raise NotImplementedError(self.add_object)
  134. def add_objects(self, objects, progress=None) -> None:
  135. """Add a set of objects to this object store.
  136. Args:
  137. objects: Iterable over a list of (object, path) tuples
  138. """
  139. raise NotImplementedError(self.add_objects)
  140. def tree_changes(
  141. self,
  142. source,
  143. target,
  144. want_unchanged=False,
  145. include_trees=False,
  146. change_type_same=False,
  147. rename_detector=None,
  148. ):
  149. """Find the differences between the contents of two trees.
  150. Args:
  151. source: SHA1 of the source tree
  152. target: SHA1 of the target tree
  153. want_unchanged: Whether unchanged files should be reported
  154. include_trees: Whether to include trees
  155. change_type_same: Whether to report files changing
  156. type in the same entry.
  157. Returns: Iterator over tuples with
  158. (oldpath, newpath), (oldmode, newmode), (oldsha, newsha)
  159. """
  160. from .diff_tree import tree_changes
  161. for change in tree_changes(
  162. self,
  163. source,
  164. target,
  165. want_unchanged=want_unchanged,
  166. include_trees=include_trees,
  167. change_type_same=change_type_same,
  168. rename_detector=rename_detector,
  169. ):
  170. yield (
  171. (change.old.path, change.new.path),
  172. (change.old.mode, change.new.mode),
  173. (change.old.sha, change.new.sha),
  174. )
  175. def iter_tree_contents(self, tree_id, include_trees=False):
  176. """Iterate the contents of a tree and all subtrees.
  177. Iteration is depth-first pre-order, as in e.g. os.walk.
  178. Args:
  179. tree_id: SHA1 of the tree.
  180. include_trees: If True, include tree objects in the iteration.
  181. Returns: Iterator over TreeEntry namedtuples for all the objects in a
  182. tree.
  183. """
  184. warnings.warn(
  185. "Please use dulwich.object_store.iter_tree_contents",
  186. DeprecationWarning,
  187. stacklevel=2,
  188. )
  189. return iter_tree_contents(self, tree_id, include_trees=include_trees)
  190. def iterobjects_subset(
  191. self, shas: Iterable[bytes], *, allow_missing: bool = False
  192. ) -> Iterator[ShaFile]:
  193. for sha in shas:
  194. try:
  195. yield self[sha]
  196. except KeyError:
  197. if not allow_missing:
  198. raise
  199. def find_missing_objects(
  200. self,
  201. haves,
  202. wants,
  203. shallow=None,
  204. progress=None,
  205. get_tagged=None,
  206. get_parents=lambda commit: commit.parents,
  207. ):
  208. """Find the missing objects required for a set of revisions.
  209. Args:
  210. haves: Iterable over SHAs already in common.
  211. wants: Iterable over SHAs of objects to fetch.
  212. shallow: Set of shallow commit SHA1s to skip
  213. progress: Simple progress function that will be called with
  214. updated progress strings.
  215. get_tagged: Function that returns a dict of pointed-to sha ->
  216. tag sha for including tags.
  217. get_parents: Optional function for getting the parents of a
  218. commit.
  219. Returns: Iterator over (sha, path) pairs.
  220. """
  221. warnings.warn("Please use MissingObjectFinder(store)", DeprecationWarning)
  222. finder = MissingObjectFinder(
  223. self,
  224. haves=haves,
  225. wants=wants,
  226. shallow=shallow,
  227. progress=progress,
  228. get_tagged=get_tagged,
  229. get_parents=get_parents,
  230. )
  231. return iter(finder)
  232. def find_common_revisions(self, graphwalker):
  233. """Find which revisions this store has in common using graphwalker.
  234. Args:
  235. graphwalker: A graphwalker object.
  236. Returns: List of SHAs that are in common
  237. """
  238. haves = []
  239. sha = next(graphwalker)
  240. while sha:
  241. if sha in self:
  242. haves.append(sha)
  243. graphwalker.ack(sha)
  244. sha = next(graphwalker)
  245. return haves
  246. def generate_pack_data(
  247. self, have, want, shallow=None, progress=None, ofs_delta=True
  248. ) -> tuple[int, Iterator[UnpackedObject]]:
  249. """Generate pack data objects for a set of wants/haves.
  250. Args:
  251. have: List of SHA1s of objects that should not be sent
  252. want: List of SHA1s of objects that should be sent
  253. shallow: Set of shallow commit SHA1s to skip
  254. ofs_delta: Whether OFS deltas can be included
  255. progress: Optional progress reporting method
  256. """
  257. # Note that the pack-specific implementation below is more efficient,
  258. # as it reuses deltas
  259. missing_objects = MissingObjectFinder(
  260. self, haves=have, wants=want, shallow=shallow, progress=progress
  261. )
  262. object_ids = list(missing_objects)
  263. return pack_objects_to_data(
  264. [(self[oid], path) for oid, path in object_ids],
  265. ofs_delta=ofs_delta,
  266. progress=progress,
  267. )
  268. def peel_sha(self, sha):
  269. """Peel all tags from a SHA.
  270. Args:
  271. sha: The object SHA to peel.
  272. Returns: The fully-peeled SHA1 of a tag object, after peeling all
  273. intermediate tags; if the original ref does not point to a tag,
  274. this will equal the original SHA1.
  275. """
  276. warnings.warn(
  277. "Please use dulwich.object_store.peel_sha()",
  278. DeprecationWarning,
  279. stacklevel=2,
  280. )
  281. return peel_sha(self, sha)[1]
  282. def _get_depth(
  283. self,
  284. head,
  285. get_parents=lambda commit: commit.parents,
  286. max_depth=None,
  287. ):
  288. """Return the current available depth for the given head.
  289. For commits with multiple parents, the largest possible depth will be
  290. returned.
  291. Args:
  292. head: commit to start from
  293. get_parents: optional function for getting the parents of a commit
  294. max_depth: maximum depth to search
  295. """
  296. if head not in self:
  297. return 0
  298. current_depth = 1
  299. queue = [(head, current_depth)]
  300. while queue and (max_depth is None or current_depth < max_depth):
  301. e, depth = queue.pop(0)
  302. current_depth = max(current_depth, depth)
  303. cmt = self[e]
  304. if isinstance(cmt, Tag):
  305. _cls, sha = cmt.object
  306. cmt = self[sha]
  307. queue.extend(
  308. (parent, depth + 1) for parent in get_parents(cmt) if parent in self
  309. )
  310. return current_depth
  311. def close(self) -> None:
  312. """Close any files opened by this object store."""
  313. # Default implementation is a NO-OP
  314. def iter_prefix(self, prefix: bytes) -> Iterator[ObjectID]:
  315. """Iterate over all SHA1s that start with a given prefix.
  316. The default implementation is a naive iteration over all objects.
  317. However, subclasses may override this method with more efficient
  318. implementations.
  319. """
  320. for sha in self:
  321. if sha.startswith(prefix):
  322. yield sha
  323. def get_commit_graph(self):
  324. """Get the commit graph for this object store.
  325. Returns:
  326. CommitGraph object if available, None otherwise
  327. """
  328. return None
  329. def write_commit_graph(self, refs=None, reachable=True) -> None:
  330. """Write a commit graph file for this object store.
  331. Args:
  332. refs: List of refs to include. If None, includes all refs from object store.
  333. reachable: If True, includes all commits reachable from refs.
  334. If False, only includes the direct ref targets.
  335. Note:
  336. Default implementation does nothing. Subclasses should override
  337. this method to provide commit graph writing functionality.
  338. """
  339. raise NotImplementedError(self.write_commit_graph)
  340. class PackBasedObjectStore(BaseObjectStore):
  341. def __init__(self, pack_compression_level=-1) -> None:
  342. self._pack_cache: dict[str, Pack] = {}
  343. self.pack_compression_level = pack_compression_level
  344. def add_pack(self) -> tuple[BytesIO, Callable[[], None], Callable[[], None]]:
  345. """Add a new pack to this object store."""
  346. raise NotImplementedError(self.add_pack)
  347. def add_pack_data(
  348. self, count: int, unpacked_objects: Iterator[UnpackedObject], progress=None
  349. ) -> None:
  350. """Add pack data to this object store.
  351. Args:
  352. count: Number of items to add
  353. """
  354. if count == 0:
  355. # Don't bother writing an empty pack file
  356. return
  357. f, commit, abort = self.add_pack()
  358. try:
  359. write_pack_data(
  360. f.write,
  361. unpacked_objects,
  362. num_records=count,
  363. progress=progress,
  364. compression_level=self.pack_compression_level,
  365. )
  366. except BaseException:
  367. abort()
  368. raise
  369. else:
  370. return commit()
  371. @property
  372. def alternates(self):
  373. return []
  374. def contains_packed(self, sha) -> bool:
  375. """Check if a particular object is present by SHA1 and is packed.
  376. This does not check alternates.
  377. """
  378. for pack in self.packs:
  379. try:
  380. if sha in pack:
  381. return True
  382. except PackFileDisappeared:
  383. pass
  384. return False
  385. def __contains__(self, sha) -> bool:
  386. """Check if a particular object is present by SHA1.
  387. This method makes no distinction between loose and packed objects.
  388. """
  389. if self.contains_packed(sha) or self.contains_loose(sha):
  390. return True
  391. for alternate in self.alternates:
  392. if sha in alternate:
  393. return True
  394. return False
  395. def _add_cached_pack(self, base_name, pack) -> None:
  396. """Add a newly appeared pack to the cache by path."""
  397. prev_pack = self._pack_cache.get(base_name)
  398. if prev_pack is not pack:
  399. self._pack_cache[base_name] = pack
  400. if prev_pack:
  401. prev_pack.close()
  402. def generate_pack_data(
  403. self, have, want, shallow=None, progress=None, ofs_delta=True
  404. ) -> tuple[int, Iterator[UnpackedObject]]:
  405. """Generate pack data objects for a set of wants/haves.
  406. Args:
  407. have: List of SHA1s of objects that should not be sent
  408. want: List of SHA1s of objects that should be sent
  409. shallow: Set of shallow commit SHA1s to skip
  410. ofs_delta: Whether OFS deltas can be included
  411. progress: Optional progress reporting method
  412. """
  413. missing_objects = MissingObjectFinder(
  414. self, haves=have, wants=want, shallow=shallow, progress=progress
  415. )
  416. remote_has = missing_objects.get_remote_has()
  417. object_ids = list(missing_objects)
  418. return len(object_ids), generate_unpacked_objects(
  419. cast(PackedObjectContainer, self),
  420. object_ids,
  421. progress=progress,
  422. ofs_delta=ofs_delta,
  423. other_haves=remote_has,
  424. )
  425. def _clear_cached_packs(self) -> None:
  426. pack_cache = self._pack_cache
  427. self._pack_cache = {}
  428. while pack_cache:
  429. (name, pack) = pack_cache.popitem()
  430. pack.close()
  431. def _iter_cached_packs(self):
  432. return self._pack_cache.values()
  433. def _update_pack_cache(self) -> list[Pack]:
  434. raise NotImplementedError(self._update_pack_cache)
  435. def close(self) -> None:
  436. self._clear_cached_packs()
  437. @property
  438. def packs(self):
  439. """List with pack objects."""
  440. return list(self._iter_cached_packs()) + list(self._update_pack_cache())
  441. def _iter_alternate_objects(self):
  442. """Iterate over the SHAs of all the objects in alternate stores."""
  443. for alternate in self.alternates:
  444. yield from alternate
  445. def _iter_loose_objects(self):
  446. """Iterate over the SHAs of all loose objects."""
  447. raise NotImplementedError(self._iter_loose_objects)
  448. def _get_loose_object(self, sha) -> Optional[ShaFile]:
  449. raise NotImplementedError(self._get_loose_object)
  450. def _remove_loose_object(self, sha) -> None:
  451. raise NotImplementedError(self._remove_loose_object)
  452. def _remove_pack(self, name) -> None:
  453. raise NotImplementedError(self._remove_pack)
  454. def pack_loose_objects(self):
  455. """Pack loose objects.
  456. Returns: Number of objects packed
  457. """
  458. objects = set()
  459. for sha in self._iter_loose_objects():
  460. objects.add((self._get_loose_object(sha), None))
  461. self.add_objects(list(objects))
  462. for obj, path in objects:
  463. self._remove_loose_object(obj.id)
  464. return len(objects)
  465. def repack(self):
  466. """Repack the packs in this repository.
  467. Note that this implementation is fairly naive and currently keeps all
  468. objects in memory while it repacks.
  469. """
  470. loose_objects = set()
  471. for sha in self._iter_loose_objects():
  472. loose_objects.add(self._get_loose_object(sha))
  473. objects = {(obj, None) for obj in loose_objects}
  474. old_packs = {p.name(): p for p in self.packs}
  475. for name, pack in old_packs.items():
  476. objects.update((obj, None) for obj in pack.iterobjects())
  477. # The name of the consolidated pack might match the name of a
  478. # pre-existing pack. Take care not to remove the newly created
  479. # consolidated pack.
  480. consolidated = self.add_objects(objects)
  481. old_packs.pop(consolidated.name(), None)
  482. for obj in loose_objects:
  483. self._remove_loose_object(obj.id)
  484. for name, pack in old_packs.items():
  485. self._remove_pack(pack)
  486. self._update_pack_cache()
  487. return len(objects)
  488. def __iter__(self):
  489. """Iterate over the SHAs that are present in this store."""
  490. self._update_pack_cache()
  491. for pack in self._iter_cached_packs():
  492. try:
  493. yield from pack
  494. except PackFileDisappeared:
  495. pass
  496. yield from self._iter_loose_objects()
  497. yield from self._iter_alternate_objects()
  498. def contains_loose(self, sha):
  499. """Check if a particular object is present by SHA1 and is loose.
  500. This does not check alternates.
  501. """
  502. return self._get_loose_object(sha) is not None
  503. def get_raw(self, name):
  504. """Obtain the raw fulltext for an object.
  505. Args:
  506. name: sha for the object.
  507. Returns: tuple with numeric type and object contents.
  508. """
  509. if name == ZERO_SHA:
  510. raise KeyError(name)
  511. if len(name) == 40:
  512. sha = hex_to_sha(name)
  513. hexsha = name
  514. elif len(name) == 20:
  515. sha = name
  516. hexsha = None
  517. else:
  518. raise AssertionError(f"Invalid object name {name!r}")
  519. for pack in self._iter_cached_packs():
  520. try:
  521. return pack.get_raw(sha)
  522. except (KeyError, PackFileDisappeared):
  523. pass
  524. if hexsha is None:
  525. hexsha = sha_to_hex(name)
  526. ret = self._get_loose_object(hexsha)
  527. if ret is not None:
  528. return ret.type_num, ret.as_raw_string()
  529. # Maybe something else has added a pack with the object
  530. # in the mean time?
  531. for pack in self._update_pack_cache():
  532. try:
  533. return pack.get_raw(sha)
  534. except KeyError:
  535. pass
  536. for alternate in self.alternates:
  537. try:
  538. return alternate.get_raw(hexsha)
  539. except KeyError:
  540. pass
  541. raise KeyError(hexsha)
  542. def iter_unpacked_subset(
  543. self,
  544. shas,
  545. *,
  546. include_comp=False,
  547. allow_missing: bool = False,
  548. convert_ofs_delta: bool = True,
  549. ) -> Iterator[UnpackedObject]:
  550. todo: set[bytes] = set(shas)
  551. for p in self._iter_cached_packs():
  552. for unpacked in p.iter_unpacked_subset(
  553. todo,
  554. include_comp=include_comp,
  555. allow_missing=True,
  556. convert_ofs_delta=convert_ofs_delta,
  557. ):
  558. yield unpacked
  559. hexsha = sha_to_hex(unpacked.sha())
  560. todo.remove(hexsha)
  561. # Maybe something else has added a pack with the object
  562. # in the mean time?
  563. for p in self._update_pack_cache():
  564. for unpacked in p.iter_unpacked_subset(
  565. todo,
  566. include_comp=include_comp,
  567. allow_missing=True,
  568. convert_ofs_delta=convert_ofs_delta,
  569. ):
  570. yield unpacked
  571. hexsha = sha_to_hex(unpacked.sha())
  572. todo.remove(hexsha)
  573. for alternate in self.alternates:
  574. for unpacked in alternate.iter_unpacked_subset(
  575. todo,
  576. include_comp=include_comp,
  577. allow_missing=True,
  578. convert_ofs_delta=convert_ofs_delta,
  579. ):
  580. yield unpacked
  581. hexsha = sha_to_hex(unpacked.sha())
  582. todo.remove(hexsha)
  583. def iterobjects_subset(
  584. self, shas: Iterable[bytes], *, allow_missing: bool = False
  585. ) -> Iterator[ShaFile]:
  586. todo: set[bytes] = set(shas)
  587. for p in self._iter_cached_packs():
  588. for o in p.iterobjects_subset(todo, allow_missing=True):
  589. yield o
  590. todo.remove(o.id)
  591. # Maybe something else has added a pack with the object
  592. # in the mean time?
  593. for p in self._update_pack_cache():
  594. for o in p.iterobjects_subset(todo, allow_missing=True):
  595. yield o
  596. todo.remove(o.id)
  597. for alternate in self.alternates:
  598. for o in alternate.iterobjects_subset(todo, allow_missing=True):
  599. yield o
  600. todo.remove(o.id)
  601. for oid in todo:
  602. o = self._get_loose_object(oid)
  603. if o is not None:
  604. yield o
  605. elif not allow_missing:
  606. raise KeyError(oid)
  607. def get_unpacked_object(
  608. self, sha1: bytes, *, include_comp: bool = False
  609. ) -> UnpackedObject:
  610. """Obtain the unpacked object.
  611. Args:
  612. sha1: sha for the object.
  613. """
  614. if sha1 == ZERO_SHA:
  615. raise KeyError(sha1)
  616. if len(sha1) == 40:
  617. sha = hex_to_sha(sha1)
  618. hexsha = sha1
  619. elif len(sha1) == 20:
  620. sha = sha1
  621. hexsha = None
  622. else:
  623. raise AssertionError(f"Invalid object sha1 {sha1!r}")
  624. for pack in self._iter_cached_packs():
  625. try:
  626. return pack.get_unpacked_object(sha, include_comp=include_comp)
  627. except (KeyError, PackFileDisappeared):
  628. pass
  629. if hexsha is None:
  630. hexsha = sha_to_hex(sha1)
  631. # Maybe something else has added a pack with the object
  632. # in the mean time?
  633. for pack in self._update_pack_cache():
  634. try:
  635. return pack.get_unpacked_object(sha, include_comp=include_comp)
  636. except KeyError:
  637. pass
  638. for alternate in self.alternates:
  639. try:
  640. return alternate.get_unpacked_object(hexsha, include_comp=include_comp)
  641. except KeyError:
  642. pass
  643. raise KeyError(hexsha)
  644. def add_objects(
  645. self,
  646. objects: Sequence[tuple[ShaFile, Optional[str]]],
  647. progress: Optional[Callable[[str], None]] = None,
  648. ) -> None:
  649. """Add a set of objects to this object store.
  650. Args:
  651. objects: Iterable over (object, path) tuples, should support
  652. __len__.
  653. Returns: Pack object of the objects written.
  654. """
  655. count = len(objects)
  656. record_iter = (full_unpacked_object(o) for (o, p) in objects)
  657. return self.add_pack_data(count, record_iter, progress=progress)
  658. class DiskObjectStore(PackBasedObjectStore):
  659. """Git-style object store that exists on disk."""
  660. def __init__(
  661. self, path, loose_compression_level=-1, pack_compression_level=-1
  662. ) -> None:
  663. """Open an object store.
  664. Args:
  665. path: Path of the object store.
  666. loose_compression_level: zlib compression level for loose objects
  667. pack_compression_level: zlib compression level for pack objects
  668. """
  669. super().__init__(pack_compression_level=pack_compression_level)
  670. self.path = path
  671. self.pack_dir = os.path.join(self.path, PACKDIR)
  672. self._alternates = None
  673. self.loose_compression_level = loose_compression_level
  674. self.pack_compression_level = pack_compression_level
  675. # Commit graph support - lazy loaded
  676. self._commit_graph = None
  677. def __repr__(self) -> str:
  678. return f"<{self.__class__.__name__}({self.path!r})>"
  679. @classmethod
  680. def from_config(cls, path, config):
  681. try:
  682. default_compression_level = int(
  683. config.get((b"core",), b"compression").decode()
  684. )
  685. except KeyError:
  686. default_compression_level = -1
  687. try:
  688. loose_compression_level = int(
  689. config.get((b"core",), b"looseCompression").decode()
  690. )
  691. except KeyError:
  692. loose_compression_level = default_compression_level
  693. try:
  694. pack_compression_level = int(
  695. config.get((b"core",), "packCompression").decode()
  696. )
  697. except KeyError:
  698. pack_compression_level = default_compression_level
  699. return cls(path, loose_compression_level, pack_compression_level)
  700. @property
  701. def alternates(self):
  702. if self._alternates is not None:
  703. return self._alternates
  704. self._alternates = []
  705. for path in self._read_alternate_paths():
  706. self._alternates.append(DiskObjectStore(path))
  707. return self._alternates
  708. def _read_alternate_paths(self):
  709. try:
  710. f = GitFile(os.path.join(self.path, INFODIR, "alternates"), "rb")
  711. except FileNotFoundError:
  712. return
  713. with f:
  714. for line in f.readlines():
  715. line = line.rstrip(b"\n")
  716. if line.startswith(b"#"):
  717. continue
  718. if os.path.isabs(line):
  719. yield os.fsdecode(line)
  720. else:
  721. yield os.fsdecode(os.path.join(os.fsencode(self.path), line))
  722. def add_alternate_path(self, path) -> None:
  723. """Add an alternate path to this object store."""
  724. try:
  725. os.mkdir(os.path.join(self.path, INFODIR))
  726. except FileExistsError:
  727. pass
  728. alternates_path = os.path.join(self.path, INFODIR, "alternates")
  729. with GitFile(alternates_path, "wb") as f:
  730. try:
  731. orig_f = open(alternates_path, "rb")
  732. except FileNotFoundError:
  733. pass
  734. else:
  735. with orig_f:
  736. f.write(orig_f.read())
  737. f.write(os.fsencode(path) + b"\n")
  738. if not os.path.isabs(path):
  739. path = os.path.join(self.path, path)
  740. self.alternates.append(DiskObjectStore(path))
  741. def _update_pack_cache(self):
  742. """Read and iterate over new pack files and cache them."""
  743. try:
  744. pack_dir_contents = os.listdir(self.pack_dir)
  745. except FileNotFoundError:
  746. self.close()
  747. return []
  748. pack_files = set()
  749. for name in pack_dir_contents:
  750. if name.startswith("pack-") and name.endswith(".pack"):
  751. # verify that idx exists first (otherwise the pack was not yet
  752. # fully written)
  753. idx_name = os.path.splitext(name)[0] + ".idx"
  754. if idx_name in pack_dir_contents:
  755. pack_name = name[: -len(".pack")]
  756. pack_files.add(pack_name)
  757. # Open newly appeared pack files
  758. new_packs = []
  759. for f in pack_files:
  760. if f not in self._pack_cache:
  761. pack = Pack(os.path.join(self.pack_dir, f))
  762. new_packs.append(pack)
  763. self._pack_cache[f] = pack
  764. # Remove disappeared pack files
  765. for f in set(self._pack_cache) - pack_files:
  766. self._pack_cache.pop(f).close()
  767. return new_packs
  768. def _get_shafile_path(self, sha):
  769. # Check from object dir
  770. return hex_to_filename(self.path, sha)
  771. def _iter_loose_objects(self):
  772. for base in os.listdir(self.path):
  773. if len(base) != 2:
  774. continue
  775. for rest in os.listdir(os.path.join(self.path, base)):
  776. sha = os.fsencode(base + rest)
  777. if not valid_hexsha(sha):
  778. continue
  779. yield sha
  780. def _get_loose_object(self, sha):
  781. path = self._get_shafile_path(sha)
  782. try:
  783. return ShaFile.from_path(path)
  784. except FileNotFoundError:
  785. return None
  786. def _remove_loose_object(self, sha) -> None:
  787. os.remove(self._get_shafile_path(sha))
  788. def _remove_pack(self, pack) -> None:
  789. try:
  790. del self._pack_cache[os.path.basename(pack._basename)]
  791. except KeyError:
  792. pass
  793. pack.close()
  794. os.remove(pack.data.path)
  795. os.remove(pack.index.path)
  796. def _get_pack_basepath(self, entries):
  797. suffix = iter_sha1(entry[0] for entry in entries)
  798. # TODO: Handle self.pack_dir being bytes
  799. suffix = suffix.decode("ascii")
  800. return os.path.join(self.pack_dir, "pack-" + suffix)
  801. def _complete_pack(self, f, path, num_objects, indexer, progress=None):
  802. """Move a specific file containing a pack into the pack directory.
  803. Note: The file should be on the same file system as the
  804. packs directory.
  805. Args:
  806. f: Open file object for the pack.
  807. path: Path to the pack file.
  808. indexer: A PackIndexer for indexing the pack.
  809. """
  810. entries = []
  811. for i, entry in enumerate(indexer):
  812. if progress is not None:
  813. progress(f"generating index: {i}/{num_objects}\r".encode("ascii"))
  814. entries.append(entry)
  815. pack_sha, extra_entries = extend_pack(
  816. f,
  817. indexer.ext_refs(),
  818. get_raw=self.get_raw,
  819. compression_level=self.pack_compression_level,
  820. progress=progress,
  821. )
  822. f.flush()
  823. try:
  824. fileno = f.fileno()
  825. except AttributeError:
  826. pass
  827. else:
  828. os.fsync(fileno)
  829. f.close()
  830. entries.extend(extra_entries)
  831. # Move the pack in.
  832. entries.sort()
  833. pack_base_name = self._get_pack_basepath(entries)
  834. for pack in self.packs:
  835. if pack._basename == pack_base_name:
  836. return pack
  837. target_pack_path = pack_base_name + ".pack"
  838. target_index_path = pack_base_name + ".idx"
  839. if sys.platform == "win32":
  840. # Windows might have the target pack file lingering. Attempt
  841. # removal, silently passing if the target does not exist.
  842. with suppress(FileNotFoundError):
  843. os.remove(target_pack_path)
  844. os.rename(path, target_pack_path)
  845. # Write the index.
  846. with GitFile(target_index_path, "wb", mask=PACK_MODE) as index_file:
  847. write_pack_index(index_file, entries, pack_sha)
  848. # Add the pack to the store and return it.
  849. final_pack = Pack(pack_base_name)
  850. final_pack.check_length_and_checksum()
  851. self._add_cached_pack(pack_base_name, final_pack)
  852. return final_pack
  853. def add_thin_pack(self, read_all, read_some, progress=None):
  854. """Add a new thin pack to this object store.
  855. Thin packs are packs that contain deltas with parents that exist
  856. outside the pack. They should never be placed in the object store
  857. directly, and always indexed and completed as they are copied.
  858. Args:
  859. read_all: Read function that blocks until the number of
  860. requested bytes are read.
  861. read_some: Read function that returns at least one byte, but may
  862. not return the number of bytes requested.
  863. Returns: A Pack object pointing at the now-completed thin pack in the
  864. objects/pack directory.
  865. """
  866. import tempfile
  867. fd, path = tempfile.mkstemp(dir=self.path, prefix="tmp_pack_")
  868. with os.fdopen(fd, "w+b") as f:
  869. os.chmod(path, PACK_MODE)
  870. indexer = PackIndexer(f, resolve_ext_ref=self.get_raw)
  871. copier = PackStreamCopier(read_all, read_some, f, delta_iter=indexer)
  872. copier.verify(progress=progress)
  873. return self._complete_pack(f, path, len(copier), indexer, progress=progress)
  874. def add_pack(self):
  875. """Add a new pack to this object store.
  876. Returns: Fileobject to write to, a commit function to
  877. call when the pack is finished and an abort
  878. function.
  879. """
  880. import tempfile
  881. fd, path = tempfile.mkstemp(dir=self.pack_dir, suffix=".pack")
  882. f = os.fdopen(fd, "w+b")
  883. os.chmod(path, PACK_MODE)
  884. def commit():
  885. if f.tell() > 0:
  886. f.seek(0)
  887. with PackData(path, f) as pd:
  888. indexer = PackIndexer.for_pack_data(
  889. pd, resolve_ext_ref=self.get_raw
  890. )
  891. return self._complete_pack(f, path, len(pd), indexer)
  892. else:
  893. f.close()
  894. os.remove(path)
  895. return None
  896. def abort() -> None:
  897. f.close()
  898. os.remove(path)
  899. return f, commit, abort
  900. def add_object(self, obj) -> None:
  901. """Add a single object to this object store.
  902. Args:
  903. obj: Object to add
  904. """
  905. path = self._get_shafile_path(obj.id)
  906. dir = os.path.dirname(path)
  907. try:
  908. os.mkdir(dir)
  909. except FileExistsError:
  910. pass
  911. if os.path.exists(path):
  912. return # Already there, no need to write again
  913. with GitFile(path, "wb", mask=PACK_MODE) as f:
  914. f.write(
  915. obj.as_legacy_object(compression_level=self.loose_compression_level)
  916. )
  917. @classmethod
  918. def init(cls, path):
  919. try:
  920. os.mkdir(path)
  921. except FileExistsError:
  922. pass
  923. os.mkdir(os.path.join(path, "info"))
  924. os.mkdir(os.path.join(path, PACKDIR))
  925. return cls(path)
  926. def iter_prefix(self, prefix):
  927. if len(prefix) < 2:
  928. yield from super().iter_prefix(prefix)
  929. return
  930. seen = set()
  931. dir = prefix[:2].decode()
  932. rest = prefix[2:].decode()
  933. try:
  934. for name in os.listdir(os.path.join(self.path, dir)):
  935. if name.startswith(rest):
  936. sha = os.fsencode(dir + name)
  937. if sha not in seen:
  938. seen.add(sha)
  939. yield sha
  940. except FileNotFoundError:
  941. pass
  942. for p in self.packs:
  943. bin_prefix = (
  944. binascii.unhexlify(prefix)
  945. if len(prefix) % 2 == 0
  946. else binascii.unhexlify(prefix[:-1])
  947. )
  948. for sha in p.index.iter_prefix(bin_prefix):
  949. sha = sha_to_hex(sha)
  950. if sha.startswith(prefix) and sha not in seen:
  951. seen.add(sha)
  952. yield sha
  953. for alternate in self.alternates:
  954. for sha in alternate.iter_prefix(prefix):
  955. if sha not in seen:
  956. seen.add(sha)
  957. yield sha
  958. def get_commit_graph(self):
  959. """Get the commit graph for this object store.
  960. Returns:
  961. CommitGraph object if available, None otherwise
  962. """
  963. if self._commit_graph is None:
  964. from .commit_graph import read_commit_graph
  965. # Look for commit graph in our objects directory
  966. graph_file = os.path.join(self.path, "info", "commit-graph")
  967. if os.path.exists(graph_file):
  968. self._commit_graph = read_commit_graph(graph_file)
  969. return self._commit_graph
  970. def write_commit_graph(self, refs=None, reachable=True) -> None:
  971. """Write a commit graph file for this object store.
  972. Args:
  973. refs: List of refs to include. If None, includes all refs from object store.
  974. reachable: If True, includes all commits reachable from refs.
  975. If False, only includes the direct ref targets.
  976. """
  977. from .commit_graph import get_reachable_commits
  978. if refs is None:
  979. # Get all commit objects from the object store
  980. all_refs = []
  981. # Iterate through all objects to find commits
  982. for sha in self:
  983. try:
  984. obj = self[sha]
  985. if obj.type_name == b"commit":
  986. all_refs.append(sha)
  987. except KeyError:
  988. continue
  989. else:
  990. # Use provided refs
  991. all_refs = refs
  992. if not all_refs:
  993. return # No commits to include
  994. if reachable:
  995. # Get all reachable commits
  996. commit_ids = get_reachable_commits(self, all_refs)
  997. else:
  998. # Just use the direct ref targets - ensure they're hex ObjectIDs
  999. commit_ids = []
  1000. for ref in all_refs:
  1001. if isinstance(ref, bytes) and len(ref) == 40:
  1002. # Already hex ObjectID
  1003. commit_ids.append(ref)
  1004. elif isinstance(ref, bytes) and len(ref) == 20:
  1005. # Binary SHA, convert to hex ObjectID
  1006. from .objects import sha_to_hex
  1007. commit_ids.append(sha_to_hex(ref))
  1008. else:
  1009. # Assume it's already correct format
  1010. commit_ids.append(ref)
  1011. if commit_ids:
  1012. # Write commit graph directly to our object store path
  1013. # Generate the commit graph
  1014. from .commit_graph import generate_commit_graph
  1015. graph = generate_commit_graph(self, commit_ids)
  1016. if graph.entries:
  1017. # Ensure the info directory exists
  1018. info_dir = os.path.join(self.path, "info")
  1019. os.makedirs(info_dir, exist_ok=True)
  1020. # Write using GitFile for atomic operation
  1021. graph_path = os.path.join(info_dir, "commit-graph")
  1022. with GitFile(graph_path, "wb") as f:
  1023. graph.write_to_file(f)
  1024. # Clear cached commit graph so it gets reloaded
  1025. self._commit_graph = None
  1026. class MemoryObjectStore(BaseObjectStore):
  1027. """Object store that keeps all objects in memory."""
  1028. def __init__(self) -> None:
  1029. super().__init__()
  1030. self._data: dict[str, ShaFile] = {}
  1031. self.pack_compression_level = -1
  1032. def _to_hexsha(self, sha):
  1033. if len(sha) == 40:
  1034. return sha
  1035. elif len(sha) == 20:
  1036. return sha_to_hex(sha)
  1037. else:
  1038. raise ValueError(f"Invalid sha {sha!r}")
  1039. def contains_loose(self, sha):
  1040. """Check if a particular object is present by SHA1 and is loose."""
  1041. return self._to_hexsha(sha) in self._data
  1042. def contains_packed(self, sha) -> bool:
  1043. """Check if a particular object is present by SHA1 and is packed."""
  1044. return False
  1045. def __iter__(self):
  1046. """Iterate over the SHAs that are present in this store."""
  1047. return iter(self._data.keys())
  1048. @property
  1049. def packs(self):
  1050. """List with pack objects."""
  1051. return []
  1052. def get_raw(self, name: ObjectID):
  1053. """Obtain the raw text for an object.
  1054. Args:
  1055. name: sha for the object.
  1056. Returns: tuple with numeric type and object contents.
  1057. """
  1058. obj = self[self._to_hexsha(name)]
  1059. return obj.type_num, obj.as_raw_string()
  1060. def __getitem__(self, name: ObjectID):
  1061. return self._data[self._to_hexsha(name)].copy()
  1062. def __delitem__(self, name: ObjectID) -> None:
  1063. """Delete an object from this store, for testing only."""
  1064. del self._data[self._to_hexsha(name)]
  1065. def add_object(self, obj) -> None:
  1066. """Add a single object to this object store."""
  1067. self._data[obj.id] = obj.copy()
  1068. def add_objects(self, objects, progress=None) -> None:
  1069. """Add a set of objects to this object store.
  1070. Args:
  1071. objects: Iterable over a list of (object, path) tuples
  1072. """
  1073. for obj, path in objects:
  1074. self.add_object(obj)
  1075. def add_pack(self):
  1076. """Add a new pack to this object store.
  1077. Because this object store doesn't support packs, we extract and add the
  1078. individual objects.
  1079. Returns: Fileobject to write to and a commit function to
  1080. call when the pack is finished.
  1081. """
  1082. from tempfile import SpooledTemporaryFile
  1083. f = SpooledTemporaryFile(max_size=PACK_SPOOL_FILE_MAX_SIZE, prefix="incoming-")
  1084. def commit() -> None:
  1085. size = f.tell()
  1086. if size > 0:
  1087. f.seek(0)
  1088. p = PackData.from_file(f, size)
  1089. for obj in PackInflater.for_pack_data(p, self.get_raw):
  1090. self.add_object(obj)
  1091. p.close()
  1092. f.close()
  1093. else:
  1094. f.close()
  1095. def abort() -> None:
  1096. f.close()
  1097. return f, commit, abort
  1098. def add_pack_data(
  1099. self, count: int, unpacked_objects: Iterator[UnpackedObject], progress=None
  1100. ) -> None:
  1101. """Add pack data to this object store.
  1102. Args:
  1103. count: Number of items to add
  1104. """
  1105. for unpacked_object in unpacked_objects:
  1106. self.add_object(unpacked_object.sha_file())
  1107. def add_thin_pack(self, read_all, read_some, progress=None) -> None:
  1108. """Add a new thin pack to this object store.
  1109. Thin packs are packs that contain deltas with parents that exist
  1110. outside the pack. Because this object store doesn't support packs, we
  1111. extract and add the individual objects.
  1112. Args:
  1113. read_all: Read function that blocks until the number of
  1114. requested bytes are read.
  1115. read_some: Read function that returns at least one byte, but may
  1116. not return the number of bytes requested.
  1117. """
  1118. f, commit, abort = self.add_pack()
  1119. try:
  1120. copier = PackStreamCopier(read_all, read_some, f)
  1121. copier.verify()
  1122. except BaseException:
  1123. abort()
  1124. raise
  1125. else:
  1126. commit()
  1127. class ObjectIterator(Protocol):
  1128. """Interface for iterating over objects."""
  1129. def iterobjects(self) -> Iterator[ShaFile]:
  1130. raise NotImplementedError(self.iterobjects)
  1131. def tree_lookup_path(lookup_obj, root_sha, path):
  1132. """Look up an object in a Git tree.
  1133. Args:
  1134. lookup_obj: Callback for retrieving object by SHA1
  1135. root_sha: SHA1 of the root tree
  1136. path: Path to lookup
  1137. Returns: A tuple of (mode, SHA) of the resulting path.
  1138. """
  1139. tree = lookup_obj(root_sha)
  1140. if not isinstance(tree, Tree):
  1141. raise NotTreeError(root_sha)
  1142. return tree.lookup_path(lookup_obj, path)
  1143. def _collect_filetree_revs(
  1144. obj_store: ObjectContainer, tree_sha: ObjectID, kset: set[ObjectID]
  1145. ) -> None:
  1146. """Collect SHA1s of files and directories for specified tree.
  1147. Args:
  1148. obj_store: Object store to get objects by SHA from
  1149. tree_sha: tree reference to walk
  1150. kset: set to fill with references to files and directories
  1151. """
  1152. filetree = obj_store[tree_sha]
  1153. assert isinstance(filetree, Tree)
  1154. for name, mode, sha in filetree.iteritems():
  1155. if not S_ISGITLINK(mode) and sha not in kset:
  1156. kset.add(sha)
  1157. if stat.S_ISDIR(mode):
  1158. _collect_filetree_revs(obj_store, sha, kset)
  1159. def _split_commits_and_tags(
  1160. obj_store: ObjectContainer, lst, *, ignore_unknown=False
  1161. ) -> tuple[set[bytes], set[bytes], set[bytes]]:
  1162. """Split object id list into three lists with commit, tag, and other SHAs.
  1163. Commits referenced by tags are included into commits
  1164. list as well. Only SHA1s known in this repository will get
  1165. through, and unless ignore_unknown argument is True, KeyError
  1166. is thrown for SHA1 missing in the repository
  1167. Args:
  1168. obj_store: Object store to get objects by SHA1 from
  1169. lst: Collection of commit and tag SHAs
  1170. ignore_unknown: True to skip SHA1 missing in the repository
  1171. silently.
  1172. Returns: A tuple of (commits, tags, others) SHA1s
  1173. """
  1174. commits: set[bytes] = set()
  1175. tags: set[bytes] = set()
  1176. others: set[bytes] = set()
  1177. for e in lst:
  1178. try:
  1179. o = obj_store[e]
  1180. except KeyError:
  1181. if not ignore_unknown:
  1182. raise
  1183. else:
  1184. if isinstance(o, Commit):
  1185. commits.add(e)
  1186. elif isinstance(o, Tag):
  1187. tags.add(e)
  1188. tagged = o.object[1]
  1189. c, t, os = _split_commits_and_tags(
  1190. obj_store, [tagged], ignore_unknown=ignore_unknown
  1191. )
  1192. commits |= c
  1193. tags |= t
  1194. others |= os
  1195. else:
  1196. others.add(e)
  1197. return (commits, tags, others)
  1198. class MissingObjectFinder:
  1199. """Find the objects missing from another object store.
  1200. Args:
  1201. object_store: Object store containing at least all objects to be
  1202. sent
  1203. haves: SHA1s of commits not to send (already present in target)
  1204. wants: SHA1s of commits to send
  1205. progress: Optional function to report progress to.
  1206. get_tagged: Function that returns a dict of pointed-to sha -> tag
  1207. sha for including tags.
  1208. get_parents: Optional function for getting the parents of a commit.
  1209. """
  1210. def __init__(
  1211. self,
  1212. object_store,
  1213. haves,
  1214. wants,
  1215. *,
  1216. shallow=None,
  1217. progress=None,
  1218. get_tagged=None,
  1219. get_parents=lambda commit: commit.parents,
  1220. ) -> None:
  1221. self.object_store = object_store
  1222. if shallow is None:
  1223. shallow = set()
  1224. self._get_parents = get_parents
  1225. # process Commits and Tags differently
  1226. # Note, while haves may list commits/tags not available locally,
  1227. # and such SHAs would get filtered out by _split_commits_and_tags,
  1228. # wants shall list only known SHAs, and otherwise
  1229. # _split_commits_and_tags fails with KeyError
  1230. have_commits, have_tags, have_others = _split_commits_and_tags(
  1231. object_store, haves, ignore_unknown=True
  1232. )
  1233. want_commits, want_tags, want_others = _split_commits_and_tags(
  1234. object_store, wants, ignore_unknown=False
  1235. )
  1236. # all_ancestors is a set of commits that shall not be sent
  1237. # (complete repository up to 'haves')
  1238. all_ancestors = _collect_ancestors(
  1239. object_store, have_commits, shallow=shallow, get_parents=self._get_parents
  1240. )[0]
  1241. # all_missing - complete set of commits between haves and wants
  1242. # common - commits from all_ancestors we hit into while
  1243. # traversing parent hierarchy of wants
  1244. missing_commits, common_commits = _collect_ancestors(
  1245. object_store,
  1246. want_commits,
  1247. all_ancestors,
  1248. shallow=shallow,
  1249. get_parents=self._get_parents,
  1250. )
  1251. self.remote_has: set[bytes] = set()
  1252. # Now, fill sha_done with commits and revisions of
  1253. # files and directories known to be both locally
  1254. # and on target. Thus these commits and files
  1255. # won't get selected for fetch
  1256. for h in common_commits:
  1257. self.remote_has.add(h)
  1258. cmt = object_store[h]
  1259. _collect_filetree_revs(object_store, cmt.tree, self.remote_has)
  1260. # record tags we have as visited, too
  1261. for t in have_tags:
  1262. self.remote_has.add(t)
  1263. self.sha_done = set(self.remote_has)
  1264. # in fact, what we 'want' is commits, tags, and others
  1265. # we've found missing
  1266. self.objects_to_send: set[
  1267. tuple[ObjectID, Optional[bytes], Optional[int], bool]
  1268. ] = {(w, None, Commit.type_num, False) for w in missing_commits}
  1269. missing_tags = want_tags.difference(have_tags)
  1270. self.objects_to_send.update(
  1271. {(w, None, Tag.type_num, False) for w in missing_tags}
  1272. )
  1273. missing_others = want_others.difference(have_others)
  1274. self.objects_to_send.update({(w, None, None, False) for w in missing_others})
  1275. if progress is None:
  1276. self.progress = lambda x: None
  1277. else:
  1278. self.progress = progress
  1279. self._tagged = (get_tagged and get_tagged()) or {}
  1280. def get_remote_has(self):
  1281. return self.remote_has
  1282. def add_todo(
  1283. self, entries: Iterable[tuple[ObjectID, Optional[bytes], Optional[int], bool]]
  1284. ) -> None:
  1285. self.objects_to_send.update([e for e in entries if e[0] not in self.sha_done])
  1286. def __next__(self) -> tuple[bytes, Optional[PackHint]]:
  1287. while True:
  1288. if not self.objects_to_send:
  1289. self.progress(
  1290. f"counting objects: {len(self.sha_done)}, done.\n".encode("ascii")
  1291. )
  1292. raise StopIteration
  1293. (sha, name, type_num, leaf) = self.objects_to_send.pop()
  1294. if sha not in self.sha_done:
  1295. break
  1296. if not leaf:
  1297. o = self.object_store[sha]
  1298. if isinstance(o, Commit):
  1299. self.add_todo([(o.tree, b"", Tree.type_num, False)])
  1300. elif isinstance(o, Tree):
  1301. self.add_todo(
  1302. [
  1303. (
  1304. s,
  1305. n,
  1306. (Blob.type_num if stat.S_ISREG(m) else Tree.type_num),
  1307. not stat.S_ISDIR(m),
  1308. )
  1309. for n, m, s in o.iteritems()
  1310. if not S_ISGITLINK(m)
  1311. ]
  1312. )
  1313. elif isinstance(o, Tag):
  1314. self.add_todo([(o.object[1], None, o.object[0].type_num, False)])
  1315. if sha in self._tagged:
  1316. self.add_todo([(self._tagged[sha], None, None, True)])
  1317. self.sha_done.add(sha)
  1318. if len(self.sha_done) % 1000 == 0:
  1319. self.progress(f"counting objects: {len(self.sha_done)}\r".encode("ascii"))
  1320. if type_num is None:
  1321. pack_hint = None
  1322. else:
  1323. pack_hint = (type_num, name)
  1324. return (sha, pack_hint)
  1325. def __iter__(self):
  1326. return self
  1327. class ObjectStoreGraphWalker:
  1328. """Graph walker that finds what commits are missing from an object store."""
  1329. heads: set[ObjectID]
  1330. """Revisions without descendants in the local repo."""
  1331. get_parents: Callable[[ObjectID], ObjectID]
  1332. """Function to retrieve parents in the local repo."""
  1333. shallow: set[ObjectID]
  1334. def __init__(
  1335. self,
  1336. local_heads: Iterable[ObjectID],
  1337. get_parents,
  1338. shallow: Optional[set[ObjectID]] = None,
  1339. ) -> None:
  1340. """Create a new instance.
  1341. Args:
  1342. local_heads: Heads to start search with
  1343. get_parents: Function for finding the parents of a SHA1.
  1344. """
  1345. self.heads = set(local_heads)
  1346. self.get_parents = get_parents
  1347. self.parents: dict[ObjectID, Optional[list[ObjectID]]] = {}
  1348. if shallow is None:
  1349. shallow = set()
  1350. self.shallow = shallow
  1351. def nak(self) -> None:
  1352. """Nothing in common was found."""
  1353. def ack(self, sha: ObjectID) -> None:
  1354. """Ack that a revision and its ancestors are present in the source."""
  1355. if len(sha) != 40:
  1356. raise ValueError(f"unexpected sha {sha!r} received")
  1357. ancestors = {sha}
  1358. # stop if we run out of heads to remove
  1359. while self.heads:
  1360. for a in ancestors:
  1361. if a in self.heads:
  1362. self.heads.remove(a)
  1363. # collect all ancestors
  1364. new_ancestors = set()
  1365. for a in ancestors:
  1366. ps = self.parents.get(a)
  1367. if ps is not None:
  1368. new_ancestors.update(ps)
  1369. self.parents[a] = None
  1370. # no more ancestors; stop
  1371. if not new_ancestors:
  1372. break
  1373. ancestors = new_ancestors
  1374. def next(self):
  1375. """Iterate over ancestors of heads in the target."""
  1376. if self.heads:
  1377. ret = self.heads.pop()
  1378. try:
  1379. ps = self.get_parents(ret)
  1380. except KeyError:
  1381. return None
  1382. self.parents[ret] = ps
  1383. self.heads.update([p for p in ps if p not in self.parents])
  1384. return ret
  1385. return None
  1386. __next__ = next
  1387. def commit_tree_changes(object_store, tree, changes):
  1388. """Commit a specified set of changes to a tree structure.
  1389. This will apply a set of changes on top of an existing tree, storing new
  1390. objects in object_store.
  1391. changes are a list of tuples with (path, mode, object_sha).
  1392. Paths can be both blobs and trees. See the mode and
  1393. object sha to None deletes the path.
  1394. This method works especially well if there are only a small
  1395. number of changes to a big tree. For a large number of changes
  1396. to a large tree, use e.g. commit_tree.
  1397. Args:
  1398. object_store: Object store to store new objects in
  1399. and retrieve old ones from.
  1400. tree: Original tree root
  1401. changes: changes to apply
  1402. Returns: New tree root object
  1403. """
  1404. # TODO(jelmer): Save up the objects and add them using .add_objects
  1405. # rather than with individual calls to .add_object.
  1406. nested_changes = {}
  1407. for path, new_mode, new_sha in changes:
  1408. try:
  1409. (dirname, subpath) = path.split(b"/", 1)
  1410. except ValueError:
  1411. if new_sha is None:
  1412. del tree[path]
  1413. else:
  1414. tree[path] = (new_mode, new_sha)
  1415. else:
  1416. nested_changes.setdefault(dirname, []).append((subpath, new_mode, new_sha))
  1417. for name, subchanges in nested_changes.items():
  1418. try:
  1419. orig_subtree = object_store[tree[name][1]]
  1420. except KeyError:
  1421. orig_subtree = Tree()
  1422. subtree = commit_tree_changes(object_store, orig_subtree, subchanges)
  1423. if len(subtree) == 0:
  1424. del tree[name]
  1425. else:
  1426. tree[name] = (stat.S_IFDIR, subtree.id)
  1427. object_store.add_object(tree)
  1428. return tree
  1429. class OverlayObjectStore(BaseObjectStore):
  1430. """Object store that can overlay multiple object stores."""
  1431. def __init__(self, bases, add_store=None) -> None:
  1432. self.bases = bases
  1433. self.add_store = add_store
  1434. def add_object(self, object):
  1435. if self.add_store is None:
  1436. raise NotImplementedError(self.add_object)
  1437. return self.add_store.add_object(object)
  1438. def add_objects(self, objects, progress=None):
  1439. if self.add_store is None:
  1440. raise NotImplementedError(self.add_object)
  1441. return self.add_store.add_objects(objects, progress)
  1442. @property
  1443. def packs(self):
  1444. ret = []
  1445. for b in self.bases:
  1446. ret.extend(b.packs)
  1447. return ret
  1448. def __iter__(self):
  1449. done = set()
  1450. for b in self.bases:
  1451. for o_id in b:
  1452. if o_id not in done:
  1453. yield o_id
  1454. done.add(o_id)
  1455. def iterobjects_subset(
  1456. self, shas: Iterable[bytes], *, allow_missing: bool = False
  1457. ) -> Iterator[ShaFile]:
  1458. todo = set(shas)
  1459. found: set[bytes] = set()
  1460. for b in self.bases:
  1461. # Create a copy of todo for each base to avoid modifying
  1462. # the set while iterating through it
  1463. current_todo = todo - found
  1464. for o in b.iterobjects_subset(current_todo, allow_missing=True):
  1465. yield o
  1466. found.add(o.id)
  1467. # Check for any remaining objects not found
  1468. missing = todo - found
  1469. if missing and not allow_missing:
  1470. raise KeyError(next(iter(missing)))
  1471. def iter_unpacked_subset(
  1472. self,
  1473. shas: Iterable[bytes],
  1474. *,
  1475. include_comp=False,
  1476. allow_missing: bool = False,
  1477. convert_ofs_delta=True,
  1478. ) -> Iterator[ShaFile]:
  1479. todo = set(shas)
  1480. for b in self.bases:
  1481. for o in b.iter_unpacked_subset(
  1482. todo,
  1483. include_comp=include_comp,
  1484. allow_missing=True,
  1485. convert_ofs_delta=convert_ofs_delta,
  1486. ):
  1487. yield o
  1488. todo.remove(o.id)
  1489. if todo and not allow_missing:
  1490. raise KeyError(o.id)
  1491. def get_raw(self, sha_id):
  1492. for b in self.bases:
  1493. try:
  1494. return b.get_raw(sha_id)
  1495. except KeyError:
  1496. pass
  1497. raise KeyError(sha_id)
  1498. def contains_packed(self, sha) -> bool:
  1499. for b in self.bases:
  1500. if b.contains_packed(sha):
  1501. return True
  1502. return False
  1503. def contains_loose(self, sha) -> bool:
  1504. for b in self.bases:
  1505. if b.contains_loose(sha):
  1506. return True
  1507. return False
  1508. def read_packs_file(f):
  1509. """Yield the packs listed in a packs file."""
  1510. for line in f.read().splitlines():
  1511. if not line:
  1512. continue
  1513. (kind, name) = line.split(b" ", 1)
  1514. if kind != b"P":
  1515. continue
  1516. yield os.fsdecode(name)
  1517. class BucketBasedObjectStore(PackBasedObjectStore):
  1518. """Object store implementation that uses a bucket store like S3 as backend."""
  1519. def _iter_loose_objects(self):
  1520. """Iterate over the SHAs of all loose objects."""
  1521. return iter([])
  1522. def _get_loose_object(self, sha) -> None:
  1523. return None
  1524. def _remove_loose_object(self, sha) -> None:
  1525. # Doesn't exist..
  1526. pass
  1527. def _remove_pack(self, name) -> None:
  1528. raise NotImplementedError(self._remove_pack)
  1529. def _iter_pack_names(self) -> Iterator[str]:
  1530. raise NotImplementedError(self._iter_pack_names)
  1531. def _get_pack(self, name) -> Pack:
  1532. raise NotImplementedError(self._get_pack)
  1533. def _update_pack_cache(self):
  1534. pack_files = set(self._iter_pack_names())
  1535. # Open newly appeared pack files
  1536. new_packs = []
  1537. for f in pack_files:
  1538. if f not in self._pack_cache:
  1539. pack = self._get_pack(f)
  1540. new_packs.append(pack)
  1541. self._pack_cache[f] = pack
  1542. # Remove disappeared pack files
  1543. for f in set(self._pack_cache) - pack_files:
  1544. self._pack_cache.pop(f).close()
  1545. return new_packs
  1546. def _upload_pack(self, basename, pack_file, index_file) -> None:
  1547. raise NotImplementedError
  1548. def add_pack(self):
  1549. """Add a new pack to this object store.
  1550. Returns: Fileobject to write to, a commit function to
  1551. call when the pack is finished and an abort
  1552. function.
  1553. """
  1554. import tempfile
  1555. pf = tempfile.SpooledTemporaryFile(
  1556. max_size=PACK_SPOOL_FILE_MAX_SIZE, prefix="incoming-"
  1557. )
  1558. def commit():
  1559. if pf.tell() == 0:
  1560. pf.close()
  1561. return None
  1562. pf.seek(0)
  1563. p = PackData(pf.name, pf)
  1564. entries = p.sorted_entries()
  1565. basename = iter_sha1(entry[0] for entry in entries).decode("ascii")
  1566. idxf = tempfile.SpooledTemporaryFile(
  1567. max_size=PACK_SPOOL_FILE_MAX_SIZE, prefix="incoming-"
  1568. )
  1569. checksum = p.get_stored_checksum()
  1570. write_pack_index(idxf, entries, checksum)
  1571. idxf.seek(0)
  1572. idx = load_pack_index_file(basename + ".idx", idxf)
  1573. for pack in self.packs:
  1574. if pack.get_stored_checksum() == p.get_stored_checksum():
  1575. p.close()
  1576. idx.close()
  1577. pf.close()
  1578. idxf.close()
  1579. return pack
  1580. pf.seek(0)
  1581. idxf.seek(0)
  1582. self._upload_pack(basename, pf, idxf)
  1583. final_pack = Pack.from_objects(p, idx)
  1584. self._add_cached_pack(basename, final_pack)
  1585. pf.close()
  1586. idxf.close()
  1587. return final_pack
  1588. return pf, commit, pf.close
  1589. def _collect_ancestors(
  1590. store: ObjectContainer,
  1591. heads,
  1592. common: frozenset[ObjectID] = frozenset(),
  1593. shallow: frozenset[ObjectID] = frozenset(),
  1594. get_parents=lambda commit: commit.parents,
  1595. ):
  1596. """Collect all ancestors of heads up to (excluding) those in common.
  1597. Args:
  1598. heads: commits to start from
  1599. common: commits to end at, or empty set to walk repository
  1600. completely
  1601. get_parents: Optional function for getting the parents of a
  1602. commit.
  1603. Returns: a tuple (A, B) where A - all commits reachable
  1604. from heads but not present in common, B - common (shared) elements
  1605. that are directly reachable from heads
  1606. """
  1607. bases = set()
  1608. commits = set()
  1609. queue = []
  1610. queue.extend(heads)
  1611. while queue:
  1612. e = queue.pop(0)
  1613. if e in common:
  1614. bases.add(e)
  1615. elif e not in commits:
  1616. commits.add(e)
  1617. if e in shallow:
  1618. continue
  1619. cmt = store[e]
  1620. queue.extend(get_parents(cmt))
  1621. return (commits, bases)
  1622. def iter_tree_contents(
  1623. store: ObjectContainer, tree_id: Optional[ObjectID], *, include_trees: bool = False
  1624. ):
  1625. """Iterate the contents of a tree and all subtrees.
  1626. Iteration is depth-first pre-order, as in e.g. os.walk.
  1627. Args:
  1628. tree_id: SHA1 of the tree.
  1629. include_trees: If True, include tree objects in the iteration.
  1630. Returns: Iterator over TreeEntry namedtuples for all the objects in a
  1631. tree.
  1632. """
  1633. if tree_id is None:
  1634. return
  1635. # This could be fairly easily generalized to >2 trees if we find a use
  1636. # case.
  1637. todo = [TreeEntry(b"", stat.S_IFDIR, tree_id)]
  1638. while todo:
  1639. entry = todo.pop()
  1640. if stat.S_ISDIR(entry.mode):
  1641. extra = []
  1642. tree = store[entry.sha]
  1643. assert isinstance(tree, Tree)
  1644. for subentry in tree.iteritems(name_order=True):
  1645. extra.append(subentry.in_path(entry.path))
  1646. todo.extend(reversed(extra))
  1647. if not stat.S_ISDIR(entry.mode) or include_trees:
  1648. yield entry
  1649. def peel_sha(store: ObjectContainer, sha: bytes) -> tuple[ShaFile, ShaFile]:
  1650. """Peel all tags from a SHA.
  1651. Args:
  1652. sha: The object SHA to peel.
  1653. Returns: The fully-peeled SHA1 of a tag object, after peeling all
  1654. intermediate tags; if the original ref does not point to a tag,
  1655. this will equal the original SHA1.
  1656. """
  1657. unpeeled = obj = store[sha]
  1658. obj_class = object_class(obj.type_name)
  1659. while obj_class is Tag:
  1660. assert isinstance(obj, Tag)
  1661. obj_class, sha = obj.object
  1662. obj = store[sha]
  1663. return unpeeled, obj