object_store.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  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 _add_known_pack(self, pack):
  214. """Add a newly appeared pack to the cache by path.
  215. """
  216. if self._pack_cache is not None:
  217. self._pack_cache.append(pack)
  218. @property
  219. def packs(self):
  220. """List with pack objects."""
  221. if self._pack_cache is None:
  222. self._pack_cache = self._load_packs()
  223. return self._pack_cache
  224. def _iter_loose_objects(self):
  225. raise NotImplementedError(self._iter_loose_objects)
  226. def _get_loose_object(self, sha):
  227. raise NotImplementedError(self._get_loose_object)
  228. def __iter__(self):
  229. """Iterate over the SHAs that are present in this store."""
  230. iterables = self.packs + [self._iter_loose_objects()]
  231. return itertools.chain(*iterables)
  232. def contains_loose(self, sha):
  233. """Check if a particular object is present by SHA1 and is loose."""
  234. return self._get_loose_object(sha) is not None
  235. def get_raw(self, name):
  236. """Obtain the raw text for an object.
  237. :param name: sha for the object.
  238. :return: tuple with object type and object contents.
  239. """
  240. if len(name) == 40:
  241. sha = hex_to_sha(name)
  242. hexsha = name
  243. elif len(name) == 20:
  244. sha = name
  245. hexsha = None
  246. else:
  247. raise AssertionError
  248. for pack in self.packs:
  249. try:
  250. return pack.get_raw(sha)
  251. except KeyError:
  252. pass
  253. if hexsha is None:
  254. hexsha = sha_to_hex(name)
  255. ret = self._get_loose_object(hexsha)
  256. if ret is not None:
  257. return ret.type, ret.as_raw_string()
  258. raise KeyError(hexsha)
  259. def add_objects(self, objects):
  260. """Add a set of objects to this object store.
  261. :param objects: Iterable over objects, should support __len__.
  262. """
  263. if len(objects) == 0:
  264. # Don't bother writing an empty pack file
  265. return
  266. f, commit = self.add_pack()
  267. write_pack_data(f, objects, len(objects))
  268. commit()
  269. class DiskObjectStore(PackBasedObjectStore):
  270. """Git-style object store that exists on disk."""
  271. def __init__(self, path):
  272. """Open an object store.
  273. :param path: Path of the object store.
  274. """
  275. super(DiskObjectStore, self).__init__()
  276. self.path = path
  277. self.pack_dir = os.path.join(self.path, PACKDIR)
  278. def _load_packs(self):
  279. pack_files = []
  280. try:
  281. for name in os.listdir(self.pack_dir):
  282. # TODO: verify that idx exists first
  283. if name.startswith("pack-") and name.endswith(".pack"):
  284. filename = os.path.join(self.pack_dir, name)
  285. pack_files.append((os.stat(filename).st_mtime, filename))
  286. except OSError, e:
  287. if e.errno == errno.ENOENT:
  288. return []
  289. raise
  290. pack_files.sort(reverse=True)
  291. suffix_len = len(".pack")
  292. return [Pack(f[:-suffix_len]) for _, f in pack_files]
  293. def _get_shafile_path(self, sha):
  294. dir = sha[:2]
  295. file = sha[2:]
  296. # Check from object dir
  297. return os.path.join(self.path, dir, file)
  298. def _iter_loose_objects(self):
  299. for base in os.listdir(self.path):
  300. if len(base) != 2:
  301. continue
  302. for rest in os.listdir(os.path.join(self.path, base)):
  303. yield base+rest
  304. def _get_loose_object(self, sha):
  305. path = self._get_shafile_path(sha)
  306. try:
  307. return ShaFile.from_file(path)
  308. except OSError, e:
  309. if e.errno == errno.ENOENT:
  310. return None
  311. raise
  312. def move_in_thin_pack(self, path):
  313. """Move a specific file containing a pack into the pack directory.
  314. :note: The file should be on the same file system as the
  315. packs directory.
  316. :param path: Path to the pack file.
  317. """
  318. data = PackData(path)
  319. # Write index for the thin pack (do we really need this?)
  320. temppath = os.path.join(self.pack_dir,
  321. sha_to_hex(urllib2.randombytes(20))+".tempidx")
  322. data.create_index_v2(temppath, self.get_raw)
  323. p = Pack.from_objects(data, load_pack_index(temppath))
  324. # Write a full pack version
  325. temppath = os.path.join(self.pack_dir,
  326. sha_to_hex(urllib2.randombytes(20))+".temppack")
  327. write_pack(temppath, ((o, None) for o in p.iterobjects(self.get_raw)),
  328. len(p))
  329. pack_sha = load_pack_index(temppath+".idx").objects_sha1()
  330. newbasename = os.path.join(self.pack_dir, "pack-%s" % pack_sha)
  331. os.rename(temppath+".pack", newbasename+".pack")
  332. os.rename(temppath+".idx", newbasename+".idx")
  333. self._add_known_pack(Pack(newbasename))
  334. def move_in_pack(self, path):
  335. """Move a specific file containing a pack into the pack directory.
  336. :note: The file should be on the same file system as the
  337. packs directory.
  338. :param path: Path to the pack file.
  339. """
  340. p = PackData(path)
  341. entries = p.sorted_entries()
  342. basename = os.path.join(self.pack_dir,
  343. "pack-%s" % iter_sha1(entry[0] for entry in entries))
  344. write_pack_index_v2(basename+".idx", entries, p.get_stored_checksum())
  345. p.close()
  346. os.rename(path, basename + ".pack")
  347. self._add_known_pack(Pack(basename))
  348. def add_thin_pack(self):
  349. """Add a new thin pack to this object store.
  350. Thin packs are packs that contain deltas with parents that exist
  351. in a different pack.
  352. """
  353. fd, path = tempfile.mkstemp(dir=self.pack_dir, suffix=".pack")
  354. f = os.fdopen(fd, 'wb')
  355. def commit():
  356. os.fsync(fd)
  357. f.close()
  358. if os.path.getsize(path) > 0:
  359. self.move_in_thin_pack(path)
  360. return f, commit
  361. def add_pack(self):
  362. """Add a new pack to this object store.
  363. :return: Fileobject to write to and a commit function to
  364. call when the pack is finished.
  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_pack(path)
  373. return f, commit
  374. def add_object(self, obj):
  375. """Add a single object to this object store.
  376. :param obj: Object to add
  377. """
  378. dir = os.path.join(self.path, obj.id[:2])
  379. if not os.path.isdir(dir):
  380. os.mkdir(dir)
  381. path = os.path.join(dir, obj.id[2:])
  382. if os.path.exists(path):
  383. return # Already there, no need to write again
  384. f = GitFile(path, 'wb')
  385. try:
  386. f.write(obj.as_legacy_object())
  387. finally:
  388. f.close()
  389. class MemoryObjectStore(BaseObjectStore):
  390. """Object store that keeps all objects in memory."""
  391. def __init__(self):
  392. super(MemoryObjectStore, self).__init__()
  393. self._data = {}
  394. def contains_loose(self, sha):
  395. """Check if a particular object is present by SHA1 and is loose."""
  396. return sha in self._data
  397. def contains_packed(self, sha):
  398. """Check if a particular object is present by SHA1 and is packed."""
  399. return False
  400. def __iter__(self):
  401. """Iterate over the SHAs that are present in this store."""
  402. return self._data.iterkeys()
  403. @property
  404. def packs(self):
  405. """List with pack objects."""
  406. return []
  407. def get_raw(self, name):
  408. """Obtain the raw text for an object.
  409. :param name: sha for the object.
  410. :return: tuple with object type and object contents.
  411. """
  412. return self[name].as_raw_string()
  413. def __getitem__(self, name):
  414. return self._data[name]
  415. def add_object(self, obj):
  416. """Add a single object to this object store.
  417. """
  418. self._data[obj.id] = obj
  419. def add_objects(self, objects):
  420. """Add a set of objects to this object store.
  421. :param objects: Iterable over a list of objects.
  422. """
  423. for obj, path in objects:
  424. self._data[obj.id] = obj
  425. class ObjectImporter(object):
  426. """Interface for importing objects."""
  427. def __init__(self, count):
  428. """Create a new ObjectImporter.
  429. :param count: Number of objects that's going to be imported.
  430. """
  431. self.count = count
  432. def add_object(self, object):
  433. """Add an object."""
  434. raise NotImplementedError(self.add_object)
  435. def finish(self, object):
  436. """Finish the imoprt and write objects to disk."""
  437. raise NotImplementedError(self.finish)
  438. class ObjectIterator(object):
  439. """Interface for iterating over objects."""
  440. def iterobjects(self):
  441. raise NotImplementedError(self.iterobjects)
  442. class ObjectStoreIterator(ObjectIterator):
  443. """ObjectIterator that works on top of an ObjectStore."""
  444. def __init__(self, store, sha_iter):
  445. """Create a new ObjectIterator.
  446. :param store: Object store to retrieve from
  447. :param sha_iter: Iterator over (sha, path) tuples
  448. """
  449. self.store = store
  450. self.sha_iter = sha_iter
  451. self._shas = []
  452. def __iter__(self):
  453. """Yield tuple with next object and path."""
  454. for sha, path in self.itershas():
  455. yield self.store[sha], path
  456. def iterobjects(self):
  457. """Iterate over just the objects."""
  458. for o, path in self:
  459. yield o
  460. def itershas(self):
  461. """Iterate over the SHAs."""
  462. for sha in self._shas:
  463. yield sha
  464. for sha in self.sha_iter:
  465. self._shas.append(sha)
  466. yield sha
  467. def __contains__(self, needle):
  468. """Check if an object is present.
  469. :note: This checks if the object is present in
  470. the underlying object store, not if it would
  471. be yielded by the iterator.
  472. :param needle: SHA1 of the object to check for
  473. """
  474. return needle in self.store
  475. def __getitem__(self, key):
  476. """Find an object by SHA1.
  477. :note: This retrieves the object from the underlying
  478. object store. It will also succeed if the object would
  479. not be returned by the iterator.
  480. """
  481. return self.store[key]
  482. def __len__(self):
  483. """Return the number of objects."""
  484. return len(list(self.itershas()))
  485. def tree_lookup_path(lookup_obj, root_sha, path):
  486. """Lookup an object in a Git tree.
  487. :param lookup_obj: Callback for retrieving object by SHA1
  488. :param root_sha: SHA1 of the root tree
  489. :param path: Path to lookup
  490. """
  491. parts = path.split("/")
  492. sha = root_sha
  493. for p in parts:
  494. obj = lookup_obj(sha)
  495. if type(obj) is not Tree:
  496. raise NotTreeError(sha)
  497. if p == '':
  498. continue
  499. mode, sha = obj[p]
  500. return mode, sha
  501. class MissingObjectFinder(object):
  502. """Find the objects missing from another object store.
  503. :param object_store: Object store containing at least all objects to be
  504. sent
  505. :param haves: SHA1s of commits not to send (already present in target)
  506. :param wants: SHA1s of commits to send
  507. :param progress: Optional function to report progress to.
  508. """
  509. def __init__(self, object_store, haves, wants, progress=None):
  510. self.sha_done = set(haves)
  511. self.objects_to_send = set([(w, None, False) for w in wants if w not in haves])
  512. self.object_store = object_store
  513. if progress is None:
  514. self.progress = lambda x: None
  515. else:
  516. self.progress = progress
  517. def add_todo(self, entries):
  518. self.objects_to_send.update([e for e in entries if not e[0] in self.sha_done])
  519. def parse_tree(self, tree):
  520. self.add_todo([(sha, name, not stat.S_ISDIR(mode)) for (mode, name, sha) in tree.entries() if not S_ISGITLINK(mode)])
  521. def parse_commit(self, commit):
  522. self.add_todo([(commit.tree, "", False)])
  523. self.add_todo([(p, None, False) for p in commit.parents])
  524. def parse_tag(self, tag):
  525. self.add_todo([(tag.object[1], None, False)])
  526. def next(self):
  527. if not self.objects_to_send:
  528. return None
  529. (sha, name, leaf) = self.objects_to_send.pop()
  530. if not leaf:
  531. o = self.object_store[sha]
  532. if isinstance(o, Commit):
  533. self.parse_commit(o)
  534. elif isinstance(o, Tree):
  535. self.parse_tree(o)
  536. elif isinstance(o, Tag):
  537. self.parse_tag(o)
  538. self.sha_done.add(sha)
  539. self.progress("counting objects: %d\r" % len(self.sha_done))
  540. return (sha, name)
  541. class ObjectStoreGraphWalker(object):
  542. """Graph walker that finds out what commits are missing from an object store."""
  543. def __init__(self, local_heads, get_parents):
  544. """Create a new instance.
  545. :param local_heads: Heads to start search with
  546. :param get_parents: Function for finding the parents of a SHA1.
  547. """
  548. self.heads = set(local_heads)
  549. self.get_parents = get_parents
  550. self.parents = {}
  551. def ack(self, sha):
  552. """Ack that a particular revision and its ancestors are present in the source."""
  553. if sha in self.heads:
  554. self.heads.remove(sha)
  555. if sha in self.parents:
  556. for p in self.parents[sha]:
  557. self.ack(p)
  558. def next(self):
  559. """Iterate over ancestors of heads in the target."""
  560. if self.heads:
  561. ret = self.heads.pop()
  562. ps = self.get_parents(ret)
  563. self.parents[ret] = ps
  564. self.heads.update(ps)
  565. return ret
  566. return None