object_store.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  1. # object_store.py -- Object store for git objects
  2. # Copyright (C) 2008-2009 Jelmer Vernooij <jelmer@samba.org>
  3. #
  4. # This program is free software; you can redistribute it and/or
  5. # modify it under the terms of the GNU General Public License
  6. # as published by the Free Software Foundation; either version 2
  7. # or (at your option) a later version of the License.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program; if not, write to the Free Software
  16. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  17. # MA 02110-1301, USA.
  18. """Git object store interfaces and implementation."""
  19. import errno
  20. import itertools
  21. import os
  22. import stat
  23. import tempfile
  24. import urllib2
  25. from dulwich.errors import (
  26. NotTreeError,
  27. )
  28. from dulwich.file import GitFile
  29. from dulwich.objects import (
  30. Commit,
  31. ShaFile,
  32. Tag,
  33. Tree,
  34. hex_to_sha,
  35. sha_to_hex,
  36. S_ISGITLINK,
  37. )
  38. from dulwich.pack import (
  39. Pack,
  40. PackData,
  41. iter_sha1,
  42. load_pack_index,
  43. write_pack,
  44. write_pack_data,
  45. write_pack_index_v2,
  46. )
  47. PACKDIR = 'pack'
  48. class BaseObjectStore(object):
  49. """Object store interface."""
  50. def determine_wants_all(self, refs):
  51. return [sha for (ref, sha) in refs.iteritems() if not sha in self and not ref.endswith("^{}")]
  52. def iter_shas(self, shas):
  53. """Iterate over the objects for the specified shas.
  54. :param shas: Iterable object with SHAs
  55. :return: Object iterator
  56. """
  57. return ObjectStoreIterator(self, shas)
  58. def contains_loose(self, sha):
  59. """Check if a particular object is present by SHA1 and is loose."""
  60. raise NotImplementedError(self.contains_loose)
  61. def contains_packed(self, sha):
  62. """Check if a particular object is present by SHA1 and is packed."""
  63. raise NotImplementedError(self.contains_packed)
  64. def __contains__(self, sha):
  65. """Check if a particular object is present by SHA1.
  66. This method makes no distinction between loose and packed objects.
  67. """
  68. return self.contains_packed(sha) or self.contains_loose(sha)
  69. @property
  70. def packs(self):
  71. """Iterable of pack objects."""
  72. raise NotImplementedError
  73. def get_raw(self, name):
  74. """Obtain the raw text for an object.
  75. :param name: sha for the object.
  76. :return: tuple with object type and object contents.
  77. """
  78. raise NotImplementedError(self.get_raw)
  79. def __getitem__(self, sha):
  80. """Obtain an object by SHA1."""
  81. type, uncomp = self.get_raw(sha)
  82. return ShaFile.from_raw_string(type, uncomp)
  83. def __iter__(self):
  84. """Iterate over the SHAs that are present in this store."""
  85. raise NotImplementedError(self.__iter__)
  86. def add_object(self, obj):
  87. """Add a single object to this object store.
  88. """
  89. raise NotImplementedError(self.add_object)
  90. def add_objects(self, objects):
  91. """Add a set of objects to this object store.
  92. :param objects: Iterable over a list of objects.
  93. """
  94. raise NotImplementedError(self.add_objects)
  95. def tree_changes(self, source, target, want_unchanged=False):
  96. """Find the differences between the contents of two trees
  97. :param object_store: Object store to use for retrieving tree contents
  98. :param tree: SHA1 of the root tree
  99. :param want_unchanged: Whether unchanged files should be reported
  100. :return: Iterator over tuples with (oldpath, newpath), (oldmode, newmode), (oldsha, newsha)
  101. """
  102. todo = set([(source, target, "")])
  103. while todo:
  104. (sid, tid, path) = todo.pop()
  105. if sid is not None:
  106. stree = self[sid]
  107. else:
  108. stree = {}
  109. if tid is not None:
  110. ttree = self[tid]
  111. else:
  112. ttree = {}
  113. for name, oldmode, oldhexsha in stree.iteritems():
  114. if path == "":
  115. oldchildpath = name
  116. else:
  117. oldchildpath = "%s/%s" % (path, name)
  118. try:
  119. (newmode, newhexsha) = ttree[name]
  120. newchildpath = oldchildpath
  121. except KeyError:
  122. newmode = None
  123. newhexsha = None
  124. newchildpath = None
  125. if (want_unchanged or oldmode != newmode or
  126. oldhexsha != newhexsha):
  127. if stat.S_ISDIR(oldmode):
  128. if newmode is None or stat.S_ISDIR(newmode):
  129. todo.add((oldhexsha, newhexsha, oldchildpath))
  130. else:
  131. # entry became a file
  132. todo.add((oldhexsha, None, oldchildpath))
  133. yield ((None, newchildpath), (None, newmode), (None, newhexsha))
  134. else:
  135. if newmode is not None and stat.S_ISDIR(newmode):
  136. # entry became a dir
  137. yield ((oldchildpath, None), (oldmode, None), (oldhexsha, None))
  138. todo.add((None, newhexsha, newchildpath))
  139. else:
  140. yield ((oldchildpath, newchildpath), (oldmode, newmode), (oldhexsha, newhexsha))
  141. for name, newmode, newhexsha in ttree.iteritems():
  142. if path == "":
  143. childpath = name
  144. else:
  145. childpath = "%s/%s" % (path, name)
  146. if not name in stree:
  147. if not stat.S_ISDIR(newmode):
  148. yield ((None, childpath), (None, newmode), (None, newhexsha))
  149. else:
  150. todo.add((None, newhexsha, childpath))
  151. def iter_tree_contents(self, tree):
  152. """Yield (path, mode, hexsha) tuples for all non-Tree objects in a tree.
  153. :param tree: SHA1 of the root of the tree
  154. """
  155. todo = set([(tree, "")])
  156. while todo:
  157. (tid, tpath) = todo.pop()
  158. tree = self[tid]
  159. for name, mode, hexsha in tree.iteritems():
  160. if tpath == "":
  161. path = name
  162. else:
  163. path = "%s/%s" % (tpath, name)
  164. if stat.S_ISDIR(mode):
  165. todo.add((hexsha, path))
  166. else:
  167. yield path, mode, hexsha
  168. def find_missing_objects(self, haves, wants, progress=None):
  169. """Find the missing objects required for a set of revisions.
  170. :param haves: Iterable over SHAs already in common.
  171. :param wants: Iterable over SHAs of objects to fetch.
  172. :param progress: Simple progress function that will be called with
  173. updated progress strings.
  174. :return: Iterator over (sha, path) pairs.
  175. """
  176. return iter(MissingObjectFinder(self, haves, wants, progress).next, None)
  177. def find_common_revisions(self, graphwalker):
  178. """Find which revisions this store has in common using graphwalker.
  179. :param graphwalker: A graphwalker object.
  180. :return: List of SHAs that are in common
  181. """
  182. haves = []
  183. sha = graphwalker.next()
  184. while sha:
  185. if sha in self:
  186. haves.append(sha)
  187. graphwalker.ack(sha)
  188. sha = graphwalker.next()
  189. return haves
  190. def get_graph_walker(self, heads):
  191. """Obtain a graph walker for this object store.
  192. :param heads: Local heads to start search with
  193. :return: GraphWalker object
  194. """
  195. return ObjectStoreGraphWalker(heads, lambda sha: self[sha].parents)
  196. def generate_pack_contents(self, have, want):
  197. """Iterate over the contents of a pack file.
  198. :param have: List of SHA1s of objects that should not be sent
  199. :param want: List of SHA1s of objects that should be sent
  200. """
  201. return self.iter_shas(self.find_missing_objects(have, want))
  202. class PackBasedObjectStore(BaseObjectStore):
  203. def __init__(self):
  204. self._pack_cache = None
  205. def contains_packed(self, sha):
  206. """Check if a particular object is present by SHA1 and is packed."""
  207. for pack in self.packs:
  208. if sha in pack:
  209. return True
  210. return False
  211. def _load_packs(self):
  212. raise NotImplementedError(self._load_packs)
  213. def _pack_cache_stale(self):
  214. """Check whether the pack cache is stale."""
  215. raise NotImplementedError(self._pack_cache_stale)
  216. def _add_known_pack(self, pack):
  217. """Add a newly appeared pack to the cache by path.
  218. """
  219. if self._pack_cache is not None:
  220. self._pack_cache.append(pack)
  221. @property
  222. def packs(self):
  223. """List with pack objects."""
  224. if self._pack_cache is None or self._pack_cache_stale():
  225. self._pack_cache = self._load_packs()
  226. return self._pack_cache
  227. def _iter_loose_objects(self):
  228. raise NotImplementedError(self._iter_loose_objects)
  229. def _get_loose_object(self, sha):
  230. raise NotImplementedError(self._get_loose_object)
  231. def __iter__(self):
  232. """Iterate over the SHAs that are present in this store."""
  233. iterables = self.packs + [self._iter_loose_objects()]
  234. return itertools.chain(*iterables)
  235. def contains_loose(self, sha):
  236. """Check if a particular object is present by SHA1 and is loose."""
  237. return self._get_loose_object(sha) is not None
  238. def get_raw(self, name):
  239. """Obtain the raw text for an object.
  240. :param name: sha for the object.
  241. :return: tuple with object type and object contents.
  242. """
  243. if len(name) == 40:
  244. sha = hex_to_sha(name)
  245. hexsha = name
  246. elif len(name) == 20:
  247. sha = name
  248. hexsha = None
  249. else:
  250. raise AssertionError
  251. for pack in self.packs:
  252. try:
  253. return pack.get_raw(sha)
  254. except KeyError:
  255. pass
  256. if hexsha is None:
  257. hexsha = sha_to_hex(name)
  258. ret = self._get_loose_object(hexsha)
  259. if ret is not None:
  260. return ret.type, ret.as_raw_string()
  261. raise KeyError(hexsha)
  262. def add_objects(self, objects):
  263. """Add a set of objects to this object store.
  264. :param objects: Iterable over objects, should support __len__.
  265. """
  266. if len(objects) == 0:
  267. # Don't bother writing an empty pack file
  268. return
  269. f, commit = self.add_pack()
  270. write_pack_data(f, objects, len(objects))
  271. commit()
  272. class DiskObjectStore(PackBasedObjectStore):
  273. """Git-style object store that exists on disk."""
  274. def __init__(self, path):
  275. """Open an object store.
  276. :param path: Path of the object store.
  277. """
  278. super(DiskObjectStore, self).__init__()
  279. self.path = path
  280. self.pack_dir = os.path.join(self.path, PACKDIR)
  281. self._pack_cache_time = 0
  282. def _load_packs(self):
  283. pack_files = []
  284. try:
  285. self._pack_cache_time = os.stat(self.pack_dir).st_mtime
  286. pack_dir_contents = os.listdir(self.pack_dir)
  287. for name in pack_dir_contents:
  288. # TODO: verify that idx exists first
  289. if name.startswith("pack-") and name.endswith(".pack"):
  290. filename = os.path.join(self.pack_dir, name)
  291. pack_files.append((os.stat(filename).st_mtime, filename))
  292. except OSError, e:
  293. if e.errno == errno.ENOENT:
  294. return []
  295. raise
  296. pack_files.sort(reverse=True)
  297. suffix_len = len(".pack")
  298. return [Pack(f[:-suffix_len]) for _, f in pack_files]
  299. def _pack_cache_stale(self):
  300. try:
  301. return os.stat(self.pack_dir).st_mtime > self._pack_cache_time
  302. except OSError, e:
  303. if e.errno == errno.ENOENT:
  304. return True
  305. raise
  306. def _get_shafile_path(self, sha):
  307. dir = sha[:2]
  308. file = sha[2:]
  309. # Check from object dir
  310. return os.path.join(self.path, dir, file)
  311. def _iter_loose_objects(self):
  312. for base in os.listdir(self.path):
  313. if len(base) != 2:
  314. continue
  315. for rest in os.listdir(os.path.join(self.path, base)):
  316. yield base+rest
  317. def _get_loose_object(self, sha):
  318. path = self._get_shafile_path(sha)
  319. try:
  320. return ShaFile.from_file(path)
  321. except OSError, e:
  322. if e.errno == errno.ENOENT:
  323. return None
  324. raise
  325. def move_in_thin_pack(self, path):
  326. """Move a specific file containing a pack into the pack directory.
  327. :note: The file should be on the same file system as the
  328. packs directory.
  329. :param path: Path to the pack file.
  330. """
  331. data = PackData(path)
  332. # Write index for the thin pack (do we really need this?)
  333. temppath = os.path.join(self.pack_dir,
  334. sha_to_hex(urllib2.randombytes(20))+".tempidx")
  335. data.create_index_v2(temppath, self.get_raw)
  336. p = Pack.from_objects(data, load_pack_index(temppath))
  337. # Write a full pack version
  338. temppath = os.path.join(self.pack_dir,
  339. sha_to_hex(urllib2.randombytes(20))+".temppack")
  340. write_pack(temppath, ((o, None) for o in p.iterobjects(self.get_raw)),
  341. len(p))
  342. pack_sha = load_pack_index(temppath+".idx").objects_sha1()
  343. newbasename = os.path.join(self.pack_dir, "pack-%s" % pack_sha)
  344. os.rename(temppath+".pack", newbasename+".pack")
  345. os.rename(temppath+".idx", newbasename+".idx")
  346. self._add_known_pack(Pack(newbasename))
  347. def move_in_pack(self, path):
  348. """Move a specific file containing a pack into the pack directory.
  349. :note: The file should be on the same file system as the
  350. packs directory.
  351. :param path: Path to the pack file.
  352. """
  353. p = PackData(path)
  354. entries = p.sorted_entries()
  355. basename = os.path.join(self.pack_dir,
  356. "pack-%s" % iter_sha1(entry[0] for entry in entries))
  357. write_pack_index_v2(basename+".idx", entries, p.get_stored_checksum())
  358. p.close()
  359. os.rename(path, basename + ".pack")
  360. self._add_known_pack(Pack(basename))
  361. def add_thin_pack(self):
  362. """Add a new thin pack to this object store.
  363. Thin packs are packs that contain deltas with parents that exist
  364. in a different pack.
  365. """
  366. fd, path = tempfile.mkstemp(dir=self.pack_dir, suffix=".pack")
  367. f = os.fdopen(fd, 'wb')
  368. def commit():
  369. os.fsync(fd)
  370. f.close()
  371. if os.path.getsize(path) > 0:
  372. self.move_in_thin_pack(path)
  373. return f, commit
  374. def add_pack(self):
  375. """Add a new pack to this object store.
  376. :return: Fileobject to write to and a commit function to
  377. call when the pack is finished.
  378. """
  379. fd, path = tempfile.mkstemp(dir=self.pack_dir, suffix=".pack")
  380. f = os.fdopen(fd, 'wb')
  381. def commit():
  382. os.fsync(fd)
  383. f.close()
  384. if os.path.getsize(path) > 0:
  385. self.move_in_pack(path)
  386. return f, commit
  387. def add_object(self, obj):
  388. """Add a single object to this object store.
  389. :param obj: Object to add
  390. """
  391. dir = os.path.join(self.path, obj.id[:2])
  392. if not os.path.isdir(dir):
  393. os.mkdir(dir)
  394. path = os.path.join(dir, obj.id[2:])
  395. if os.path.exists(path):
  396. return # Already there, no need to write again
  397. f = GitFile(path, 'wb')
  398. try:
  399. f.write(obj.as_legacy_object())
  400. finally:
  401. f.close()
  402. class MemoryObjectStore(BaseObjectStore):
  403. """Object store that keeps all objects in memory."""
  404. def __init__(self):
  405. super(MemoryObjectStore, self).__init__()
  406. self._data = {}
  407. def contains_loose(self, sha):
  408. """Check if a particular object is present by SHA1 and is loose."""
  409. return sha in self._data
  410. def contains_packed(self, sha):
  411. """Check if a particular object is present by SHA1 and is packed."""
  412. return False
  413. def __iter__(self):
  414. """Iterate over the SHAs that are present in this store."""
  415. return self._data.iterkeys()
  416. @property
  417. def packs(self):
  418. """List with pack objects."""
  419. return []
  420. def get_raw(self, name):
  421. """Obtain the raw text for an object.
  422. :param name: sha for the object.
  423. :return: tuple with object type and object contents.
  424. """
  425. return self[name].as_raw_string()
  426. def __getitem__(self, name):
  427. return self._data[name]
  428. def add_object(self, obj):
  429. """Add a single object to this object store.
  430. """
  431. self._data[obj.id] = obj
  432. def add_objects(self, objects):
  433. """Add a set of objects to this object store.
  434. :param objects: Iterable over a list of objects.
  435. """
  436. for obj, path in objects:
  437. self._data[obj.id] = obj
  438. class ObjectImporter(object):
  439. """Interface for importing objects."""
  440. def __init__(self, count):
  441. """Create a new ObjectImporter.
  442. :param count: Number of objects that's going to be imported.
  443. """
  444. self.count = count
  445. def add_object(self, object):
  446. """Add an object."""
  447. raise NotImplementedError(self.add_object)
  448. def finish(self, object):
  449. """Finish the imoprt and write objects to disk."""
  450. raise NotImplementedError(self.finish)
  451. class ObjectIterator(object):
  452. """Interface for iterating over objects."""
  453. def iterobjects(self):
  454. raise NotImplementedError(self.iterobjects)
  455. class ObjectStoreIterator(ObjectIterator):
  456. """ObjectIterator that works on top of an ObjectStore."""
  457. def __init__(self, store, sha_iter):
  458. """Create a new ObjectIterator.
  459. :param store: Object store to retrieve from
  460. :param sha_iter: Iterator over (sha, path) tuples
  461. """
  462. self.store = store
  463. self.sha_iter = sha_iter
  464. self._shas = []
  465. def __iter__(self):
  466. """Yield tuple with next object and path."""
  467. for sha, path in self.itershas():
  468. yield self.store[sha], path
  469. def iterobjects(self):
  470. """Iterate over just the objects."""
  471. for o, path in self:
  472. yield o
  473. def itershas(self):
  474. """Iterate over the SHAs."""
  475. for sha in self._shas:
  476. yield sha
  477. for sha in self.sha_iter:
  478. self._shas.append(sha)
  479. yield sha
  480. def __contains__(self, needle):
  481. """Check if an object is present.
  482. :note: This checks if the object is present in
  483. the underlying object store, not if it would
  484. be yielded by the iterator.
  485. :param needle: SHA1 of the object to check for
  486. """
  487. return needle in self.store
  488. def __getitem__(self, key):
  489. """Find an object by SHA1.
  490. :note: This retrieves the object from the underlying
  491. object store. It will also succeed if the object would
  492. not be returned by the iterator.
  493. """
  494. return self.store[key]
  495. def __len__(self):
  496. """Return the number of objects."""
  497. return len(list(self.itershas()))
  498. def tree_lookup_path(lookup_obj, root_sha, path):
  499. """Lookup an object in a Git tree.
  500. :param lookup_obj: Callback for retrieving object by SHA1
  501. :param root_sha: SHA1 of the root tree
  502. :param path: Path to lookup
  503. """
  504. parts = path.split("/")
  505. sha = root_sha
  506. for p in parts:
  507. obj = lookup_obj(sha)
  508. if type(obj) is not Tree:
  509. raise NotTreeError(sha)
  510. if p == '':
  511. continue
  512. mode, sha = obj[p]
  513. return mode, sha
  514. class MissingObjectFinder(object):
  515. """Find the objects missing from another object store.
  516. :param object_store: Object store containing at least all objects to be
  517. sent
  518. :param haves: SHA1s of commits not to send (already present in target)
  519. :param wants: SHA1s of commits to send
  520. :param progress: Optional function to report progress to.
  521. """
  522. def __init__(self, object_store, haves, wants, progress=None):
  523. self.sha_done = set(haves)
  524. self.objects_to_send = set([(w, None, False) for w in wants if w not in haves])
  525. self.object_store = object_store
  526. if progress is None:
  527. self.progress = lambda x: None
  528. else:
  529. self.progress = progress
  530. def add_todo(self, entries):
  531. self.objects_to_send.update([e for e in entries if not e[0] in self.sha_done])
  532. def parse_tree(self, tree):
  533. self.add_todo([(sha, name, not stat.S_ISDIR(mode)) for (mode, name, sha) in tree.entries() if not S_ISGITLINK(mode)])
  534. def parse_commit(self, commit):
  535. self.add_todo([(commit.tree, "", False)])
  536. self.add_todo([(p, None, False) for p in commit.parents])
  537. def parse_tag(self, tag):
  538. self.add_todo([(tag.object[1], None, False)])
  539. def next(self):
  540. if not self.objects_to_send:
  541. return None
  542. (sha, name, leaf) = self.objects_to_send.pop()
  543. if not leaf:
  544. o = self.object_store[sha]
  545. if isinstance(o, Commit):
  546. self.parse_commit(o)
  547. elif isinstance(o, Tree):
  548. self.parse_tree(o)
  549. elif isinstance(o, Tag):
  550. self.parse_tag(o)
  551. self.sha_done.add(sha)
  552. self.progress("counting objects: %d\r" % len(self.sha_done))
  553. return (sha, name)
  554. class ObjectStoreGraphWalker(object):
  555. """Graph walker that finds out what commits are missing from an object store."""
  556. def __init__(self, local_heads, get_parents):
  557. """Create a new instance.
  558. :param local_heads: Heads to start search with
  559. :param get_parents: Function for finding the parents of a SHA1.
  560. """
  561. self.heads = set(local_heads)
  562. self.get_parents = get_parents
  563. self.parents = {}
  564. def ack(self, sha):
  565. """Ack that a particular revision and its ancestors are present in the source."""
  566. if sha in self.heads:
  567. self.heads.remove(sha)
  568. if sha in self.parents:
  569. for p in self.parents[sha]:
  570. self.ack(p)
  571. def next(self):
  572. """Iterate over ancestors of heads in the target."""
  573. if self.heads:
  574. ret = self.heads.pop()
  575. ps = self.get_parents(ret)
  576. self.parents[ret] = ps
  577. self.heads.update(ps)
  578. return ret
  579. return None