object_store.py 35 KB

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