object_store.py 44 KB

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