repo.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. # repo.py -- For dealing wih git repositories.
  2. # Copyright (C) 2007 James Westby <jw+debian@jameswestby.net>
  3. # Copyright (C) 2008-2009 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
  21. import stat
  22. from dulwich.errors import (
  23. MissingCommitError,
  24. NotBlobError,
  25. NotCommitError,
  26. NotGitRepository,
  27. NotTreeError,
  28. )
  29. from dulwich.object_store import ObjectStore
  30. from dulwich.objects import (
  31. Blob,
  32. Commit,
  33. ShaFile,
  34. Tag,
  35. Tree,
  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. def read_packed_refs(f):
  58. l = f.readline()
  59. for l in f.readlines():
  60. if l[0] == "#":
  61. # Comment
  62. continue
  63. if l[0] == "^":
  64. # FIXME: Return somehow
  65. continue
  66. yield tuple(l.rstrip("\n").split(" ", 2))
  67. class MissingObjectFinder(object):
  68. def __init__(self, object_store, wants, graph_walker, progress=None):
  69. self.sha_done = set()
  70. self.objects_to_send = set([(w, None) for w in wants])
  71. self.object_store = object_store
  72. if progress is None:
  73. self.progress = lambda x: None
  74. else:
  75. self.progress = progress
  76. ref = graph_walker.next()
  77. while ref:
  78. if ref in self.object_store:
  79. graph_walker.ack(ref)
  80. ref = graph_walker.next()
  81. def add_todo(self, entries):
  82. self.objects_to_send.update([e for e in entries if not e in self.sha_done])
  83. def parse_tree(self, tree):
  84. self.add_todo([(sha, name) for (mode, name, sha) in tree.entries()])
  85. def parse_commit(self, commit):
  86. self.add_todo([(commit.tree, "")])
  87. self.add_todo([(p, None) for p in commit.parents])
  88. def parse_tag(self, tag):
  89. self.add_todo([(tag.object[1], None)])
  90. def next(self):
  91. if not self.objects_to_send:
  92. return None
  93. (sha, name) = self.objects_to_send.pop()
  94. o = self.object_store[sha]
  95. if isinstance(o, Commit):
  96. self.parse_commit(o)
  97. elif isinstance(o, Tree):
  98. self.parse_tree(o)
  99. elif isinstance(o, Tag):
  100. self.parse_tag(o)
  101. self.sha_done.add((sha, name))
  102. self.progress("counting objects: %d\r" % len(self.sha_done))
  103. return (sha, name)
  104. class Repo(object):
  105. ref_locs = ['', 'refs', 'refs/tags', 'refs/heads', 'refs/remotes']
  106. def __init__(self, root):
  107. if os.path.isdir(os.path.join(root, ".git", "objects")):
  108. self.bare = False
  109. self._controldir = os.path.join(root, ".git")
  110. elif os.path.isdir(os.path.join(root, "objects")):
  111. self.bare = True
  112. self._controldir = root
  113. else:
  114. raise NotGitRepository(root)
  115. self.path = root
  116. self.tags = Tags(self.tagdir(), self.get_tags())
  117. self._object_store = None
  118. def controldir(self):
  119. return self._controldir
  120. def index_path(self):
  121. return os.path.join(self.controldir(), "index")
  122. def open_index(self):
  123. from dulwich.index import Index
  124. return Index(self.index_path())
  125. def has_index(self):
  126. return os.path.exists(self.index_path())
  127. def find_missing_objects(self, determine_wants, graph_walker, progress):
  128. """Find the missing objects required for a set of revisions.
  129. :param determine_wants: Function that takes a dictionary with heads
  130. and returns the list of heads to fetch.
  131. :param graph_walker: Object that can iterate over the list of revisions
  132. to fetch and has an "ack" method that will be called to acknowledge
  133. that a revision is present.
  134. :param progress: Simple progress function that will be called with
  135. updated progress strings.
  136. """
  137. wants = determine_wants(self.get_refs())
  138. return iter(MissingObjectFinder(self.object_store, wants, graph_walker,
  139. progress).next, None)
  140. def fetch_objects(self, determine_wants, graph_walker, progress):
  141. """Fetch the missing objects required for a set of revisions.
  142. :param determine_wants: Function that takes a dictionary with heads
  143. and returns the list of heads to fetch.
  144. :param graph_walker: Object that can iterate over the list of revisions
  145. to fetch and has an "ack" method that will be called to acknowledge
  146. that a revision is present.
  147. :param progress: Simple progress function that will be called with
  148. updated progress strings.
  149. :return: tuple with number of objects, iterator over objects
  150. """
  151. return self.object_store.iter_shas(
  152. self.find_missing_objects(determine_wants, graph_walker, progress))
  153. def object_dir(self):
  154. return os.path.join(self.controldir(), OBJECTDIR)
  155. @property
  156. def object_store(self):
  157. if self._object_store is None:
  158. self._object_store = ObjectStore(self.object_dir())
  159. return self._object_store
  160. def pack_dir(self):
  161. return os.path.join(self.object_dir(), PACKDIR)
  162. def _get_ref(self, file):
  163. f = open(file, 'rb')
  164. try:
  165. contents = f.read()
  166. if contents.startswith(SYMREF):
  167. ref = contents[len(SYMREF):]
  168. if ref[-1] == '\n':
  169. ref = ref[:-1]
  170. return self.ref(ref)
  171. assert len(contents) == 41, 'Invalid ref in %s' % file
  172. return contents[:-1]
  173. finally:
  174. f.close()
  175. def ref(self, name):
  176. for dir in self.ref_locs:
  177. file = os.path.join(self.controldir(), dir, name)
  178. if os.path.exists(file):
  179. return self._get_ref(file)
  180. packed_refs = self.get_packed_refs()
  181. if name in packed_refs:
  182. return packed_refs[name]
  183. def get_refs(self):
  184. ret = {}
  185. if self.head():
  186. ret['HEAD'] = self.head()
  187. for dir in ["refs/heads", "refs/tags"]:
  188. for name in os.listdir(os.path.join(self.controldir(), dir)):
  189. path = os.path.join(self.controldir(), dir, name)
  190. if os.path.isfile(path):
  191. ret["/".join([dir, name])] = self._get_ref(path)
  192. ret.update(self.get_packed_refs())
  193. return ret
  194. def get_packed_refs(self):
  195. path = os.path.join(self.controldir(), 'packed-refs')
  196. if not os.path.exists(path):
  197. return {}
  198. ret = {}
  199. f = open(path, 'r')
  200. try:
  201. for entry in read_packed_refs(f):
  202. ret[entry[1]] = entry[0]
  203. return ret
  204. finally:
  205. f.close()
  206. def set_ref(self, name, value):
  207. file = os.path.join(self.controldir(), name)
  208. dirpath = os.path.dirname(file)
  209. if not os.path.exists(dirpath):
  210. os.makedirs(dirpath)
  211. f = open(file, 'w')
  212. try:
  213. f.write(value+"\n")
  214. finally:
  215. f.close()
  216. def remove_ref(self, name):
  217. file = os.path.join(self.controldir(), name)
  218. if os.path.exists(file):
  219. os.remove(file)
  220. def tagdir(self):
  221. return os.path.join(self.controldir(), 'refs', 'tags')
  222. def get_tags(self):
  223. ret = {}
  224. for root, dirs, files in os.walk(self.tagdir()):
  225. for name in files:
  226. ret[name] = self._get_ref(os.path.join(root, name))
  227. return ret
  228. def heads(self):
  229. ret = {}
  230. for root, dirs, files in os.walk(os.path.join(self.controldir(), 'refs', 'heads')):
  231. for name in files:
  232. ret[name] = self._get_ref(os.path.join(root, name))
  233. return ret
  234. def head(self):
  235. return self.ref('HEAD')
  236. def _get_object(self, sha, cls):
  237. assert len(sha) in (20, 40)
  238. ret = self.get_object(sha)
  239. if ret._type != cls._type:
  240. if cls is Commit:
  241. raise NotCommitError(ret)
  242. elif cls is Blob:
  243. raise NotBlobError(ret)
  244. elif cls is Tree:
  245. raise NotTreeError(ret)
  246. else:
  247. raise Exception("Type invalid: %r != %r" % (ret._type, cls._type))
  248. return ret
  249. def get_object(self, sha):
  250. return self.object_store[sha]
  251. def get_parents(self, sha):
  252. return self.commit(sha).parents
  253. def commit(self, sha):
  254. return self._get_object(sha, Commit)
  255. def tree(self, sha):
  256. return self._get_object(sha, Tree)
  257. def tag(self, sha):
  258. return self._get_object(sha, Tag)
  259. def get_blob(self, sha):
  260. return self._get_object(sha, Blob)
  261. def revision_history(self, head):
  262. """Returns a list of the commits reachable from head.
  263. Returns a list of commit objects. the first of which will be the commit
  264. of head, then following theat will be the parents.
  265. Raises NotCommitError if any no commits are referenced, including if the
  266. head parameter isn't the sha of a commit.
  267. XXX: work out how to handle merges.
  268. """
  269. # We build the list backwards, as parents are more likely to be older
  270. # than children
  271. pending_commits = [head]
  272. history = []
  273. while pending_commits != []:
  274. head = pending_commits.pop(0)
  275. try:
  276. commit = self.commit(head)
  277. except KeyError:
  278. raise MissingCommitError(head)
  279. if commit in history:
  280. continue
  281. i = 0
  282. for known_commit in history:
  283. if known_commit.commit_time > commit.commit_time:
  284. break
  285. i += 1
  286. history.insert(i, commit)
  287. parents = commit.parents
  288. pending_commits += parents
  289. history.reverse()
  290. return history
  291. def __repr__(self):
  292. return "<Repo at %r>" % self.path
  293. @classmethod
  294. def init(cls, path, mkdir=True):
  295. controldir = os.path.join(path, ".git")
  296. os.mkdir(controldir)
  297. cls.init_bare(controldir)
  298. @classmethod
  299. def init_bare(cls, path, mkdir=True):
  300. for d in [["objects"],
  301. ["objects", "info"],
  302. ["objects", "pack"],
  303. ["branches"],
  304. ["refs"],
  305. ["refs", "tags"],
  306. ["refs", "heads"],
  307. ["hooks"],
  308. ["info"]]:
  309. os.mkdir(os.path.join(path, *d))
  310. open(os.path.join(path, 'HEAD'), 'w').write("ref: refs/heads/master\n")
  311. open(os.path.join(path, 'description'), 'w').write("Unnamed repository")
  312. open(os.path.join(path, 'info', 'excludes'), 'w').write("")
  313. create = init_bare