2
0

repo.py 9.3 KB

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