2
0

object_store.py 57 KB

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