object_store.py 59 KB

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