object_store.py 47 KB

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