object_store.py 51 KB

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