object_store.py 56 KB

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