object_store.py 36 KB

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