2
0

repo.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. # repo.py -- For dealing wih git repositories.
  2. # Copyright (C) 2007 James Westby <jw+debian@jameswestby.net>
  3. # Copyright (C) 2008 Jelmer Vernooij <jelmer@samba.org>
  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; version 2
  8. # of the License or (at your option) any later version of
  9. # the License.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program; if not, write to the Free Software
  18. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  19. # MA 02110-1301, USA.
  20. import os, stat
  21. from commit import Commit
  22. from errors import (
  23. MissingCommitError,
  24. NotBlobError,
  25. NotCommitError,
  26. NotGitRepository,
  27. NotTreeError,
  28. )
  29. from object_store import ObjectStore
  30. from objects import (
  31. ShaFile,
  32. Commit,
  33. Tree,
  34. Blob,
  35. )
  36. OBJECTDIR = 'objects'
  37. SYMREF = 'ref: '
  38. class Tags(object):
  39. def __init__(self, tagdir, tags):
  40. self.tagdir = tagdir
  41. self.tags = tags
  42. def __getitem__(self, name):
  43. return self.tags[name]
  44. def __setitem__(self, name, ref):
  45. self.tags[name] = ref
  46. f = open(os.path.join(self.tagdir, name), 'wb')
  47. try:
  48. f.write("%s\n" % ref)
  49. finally:
  50. f.close()
  51. def __len__(self):
  52. return len(self.tags)
  53. def iteritems(self):
  54. for k in self.tags:
  55. yield k, self[k]
  56. class Repo(object):
  57. ref_locs = ['', 'refs', 'refs/tags', 'refs/heads', 'refs/remotes']
  58. def __init__(self, root):
  59. if os.path.isdir(os.path.join(root, ".git", "objects")):
  60. self.bare = False
  61. self._controldir = os.path.join(root, ".git")
  62. elif os.path.isdir(os.path.join(root, "objects")):
  63. self.bare = True
  64. self._controldir = root
  65. else:
  66. raise NotGitRepository(root)
  67. self.path = root
  68. self.tags = Tags(self.tagdir(), self.get_tags())
  69. self._object_store = None
  70. def controldir(self):
  71. return self._controldir
  72. def find_missing_objects(self, determine_wants, graph_walker, progress):
  73. """Fetch the missing objects required for a set of revisions.
  74. :param determine_wants: Function that takes a dictionary with heads
  75. and returns the list of heads to fetch.
  76. :param graph_walker: Object that can iterate over the list of revisions
  77. to fetch and has an "ack" method that will be called to acknowledge
  78. that a revision is present.
  79. :param progress: Simple progress function that will be called with
  80. updated progress strings.
  81. """
  82. wants = determine_wants(self.get_refs())
  83. commits_to_send = set(wants)
  84. sha_done = set()
  85. ref = graph_walker.next()
  86. while ref:
  87. if ref in self.object_store:
  88. graph_walker.ack(ref)
  89. ref = graph_walker.next()
  90. while commits_to_send:
  91. sha = (commits_to_send.pop(), None)
  92. if sha in sha_done:
  93. continue
  94. c = self.commit(sha)
  95. assert isinstance(c, Commit)
  96. sha_done.add((sha, None))
  97. commits_to_send.update([p for p in c.parents if not p in sha_done])
  98. def parse_tree(tree, sha_done):
  99. for mode, name, sha in tree.entries():
  100. if (sha, name) in sha_done:
  101. continue
  102. if mode & stat.S_IFDIR:
  103. parse_tree(self.tree(sha), sha_done)
  104. sha_done.add((sha, name))
  105. treesha = c.tree
  106. if c.tree not in sha_done:
  107. parse_tree(self.tree(c.tree), sha_done)
  108. sha_done.add((c.tree, None))
  109. progress("counting objects: %d\r" % len(sha_done))
  110. return sha_done
  111. def fetch_objects(self, determine_wants, graph_walker, progress):
  112. """Fetch the missing objects required for a set of revisions.
  113. :param determine_wants: Function that takes a dictionary with heads
  114. and returns the list of heads to fetch.
  115. :param graph_walker: Object that can iterate over the list of revisions
  116. to fetch and has an "ack" method that will be called to acknowledge
  117. that a revision is present.
  118. :param progress: Simple progress function that will be called with
  119. updated progress strings.
  120. :return: tuple with number of objects, iterator over objects
  121. """
  122. shas = self.find_missing_objects(determine_wants, graph_walker, progress)
  123. return (len(shas), ((self.get_object(sha), path) for sha, path in shas))
  124. def object_dir(self):
  125. return os.path.join(self.controldir(), OBJECTDIR)
  126. @property
  127. def object_store(self):
  128. if self._object_store is None:
  129. self._object_store = ObjectStore(self.object_dir())
  130. return self._object_store
  131. def pack_dir(self):
  132. return os.path.join(self.object_dir(), PACKDIR)
  133. def _get_ref(self, file):
  134. f = open(file, 'rb')
  135. try:
  136. contents = f.read()
  137. if contents.startswith(SYMREF):
  138. ref = contents[len(SYMREF):]
  139. if ref[-1] == '\n':
  140. ref = ref[:-1]
  141. return self.ref(ref)
  142. assert len(contents) == 41, 'Invalid ref in %s' % file
  143. return contents[:-1]
  144. finally:
  145. f.close()
  146. def ref(self, name):
  147. for dir in self.ref_locs:
  148. file = os.path.join(self.controldir(), dir, name)
  149. if os.path.exists(file):
  150. return self._get_ref(file)
  151. def get_refs(self):
  152. ret = {}
  153. if self.head():
  154. ret['HEAD'] = self.head()
  155. for dir in ["refs/heads", "refs/tags"]:
  156. for name in os.listdir(os.path.join(self.controldir(), dir)):
  157. path = os.path.join(self.controldir(), dir, name)
  158. if os.path.isfile(path):
  159. ret["/".join([dir, name])] = self._get_ref(path)
  160. return ret
  161. def set_ref(self, name, value):
  162. file = os.path.join(self.controldir(), name)
  163. open(file, 'w').write(value+"\n")
  164. def remove_ref(self, name):
  165. file = os.path.join(self.controldir(), name)
  166. if os.path.exists(file):
  167. os.remove(file)
  168. return
  169. def tagdir(self):
  170. return os.path.join(self.controldir(), 'refs', 'tags')
  171. def get_tags(self):
  172. ret = {}
  173. for root, dirs, files in os.walk(self.tagdir()):
  174. for name in files:
  175. ret[name] = self._get_ref(os.path.join(root, name))
  176. return ret
  177. def heads(self):
  178. ret = {}
  179. for root, dirs, files in os.walk(os.path.join(self.controldir(), 'refs', 'heads')):
  180. for name in files:
  181. ret[name] = self._get_ref(os.path.join(root, name))
  182. return ret
  183. def head(self):
  184. return self.ref('HEAD')
  185. def _get_object(self, sha, cls):
  186. assert len(sha) in (20, 40)
  187. ret = self.get_object(sha)
  188. if ret._type != cls._type:
  189. if cls is Commit:
  190. raise NotCommitError(ret)
  191. elif cls is Blob:
  192. raise NotBlobError(ret)
  193. elif cls is Tree:
  194. raise NotTreeError(ret)
  195. else:
  196. raise Exception("Type invalid: %r != %r" % (ret._type, cls._type))
  197. return ret
  198. def get_object(self, sha):
  199. return self.object_store[sha]
  200. def get_parents(self, sha):
  201. return self.commit(sha).parents
  202. def commit(self, sha):
  203. return self._get_object(sha, Commit)
  204. def tree(self, sha):
  205. return self._get_object(sha, Tree)
  206. def get_blob(self, sha):
  207. return self._get_object(sha, Blob)
  208. def revision_history(self, head):
  209. """Returns a list of the commits reachable from head.
  210. Returns a list of commit objects. the first of which will be the commit
  211. of head, then following theat will be the parents.
  212. Raises NotCommitError if any no commits are referenced, including if the
  213. head parameter isn't the sha of a commit.
  214. XXX: work out how to handle merges.
  215. """
  216. # We build the list backwards, as parents are more likely to be older
  217. # than children
  218. pending_commits = [head]
  219. history = []
  220. while pending_commits != []:
  221. head = pending_commits.pop(0)
  222. try:
  223. commit = self.commit(head)
  224. except KeyError:
  225. raise MissingCommitError(head)
  226. if commit in history:
  227. continue
  228. i = 0
  229. for known_commit in history:
  230. if known_commit.commit_time > commit.commit_time:
  231. break
  232. i += 1
  233. history.insert(i, commit)
  234. parents = commit.parents
  235. pending_commits += parents
  236. history.reverse()
  237. return history
  238. def __repr__(self):
  239. return "<Repo at %r>" % self.path
  240. @classmethod
  241. def init(cls, path, mkdir=True):
  242. controldir = os.path.join(path, ".git")
  243. os.mkdir(controldir)
  244. cls.init_bare(controldir)
  245. @classmethod
  246. def init_bare(cls, path, mkdir=True):
  247. for d in [["objects"],
  248. ["objects", "info"],
  249. ["objects", "pack"],
  250. ["branches"],
  251. ["refs"],
  252. ["refs", "tags"],
  253. ["refs", "heads"],
  254. ["hooks"],
  255. ["info"]]:
  256. os.mkdir(os.path.join(path, *d))
  257. open(os.path.join(path, 'HEAD'), 'w').write("ref: refs/heads/master\n")
  258. open(os.path.join(path, 'description'), 'w').write("Unnamed repository")
  259. open(os.path.join(path, 'info', 'excludes'), 'w').write("")
  260. create = init_bare