object_store.py 36 KB

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