object_store.py 51 KB

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