object_store.py 53 KB

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