object_store.py 51 KB

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