object_store.py 55 KB

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