object_store.py 41 KB

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