object_store.py 22 KB

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