object_store.py 50 KB

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