object_store.py 57 KB

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