repo.py 9.3 KB

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