object_store.py 51 KB

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