object_store.py 66 KB

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