object_store.py 45 KB

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