object_store.py 51 KB

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