object_store.py 35 KB

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