repo.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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. """Repository access."""
  21. import os
  22. import stat
  23. from dulwich.errors import (
  24. MissingCommitError,
  25. NotBlobError,
  26. NotCommitError,
  27. NotGitRepository,
  28. NotTreeError,
  29. )
  30. from dulwich.object_store import (
  31. DiskObjectStore,
  32. )
  33. from dulwich.objects import (
  34. Blob,
  35. Commit,
  36. ShaFile,
  37. Tag,
  38. Tree,
  39. )
  40. OBJECTDIR = 'objects'
  41. SYMREF = 'ref: '
  42. REFSDIR = 'refs'
  43. REFSDIR_TAGS = 'tags'
  44. REFSDIR_HEADS = 'heads'
  45. INDEX_FILENAME = "index"
  46. class RefsContainer(object):
  47. def __init__(self, path):
  48. self.path = path
  49. def __repr__(self):
  50. return "%s(%r)" % (self.__class__.__name__, self.path)
  51. def refpath(self, name):
  52. return os.path.join(self.path, name)
  53. def __setitem__(self, name, ref):
  54. f = open(self.refpath(name), 'wb')
  55. try:
  56. f.write("%s\n" % ref)
  57. finally:
  58. f.close()
  59. class Tags(RefsContainer):
  60. """Tags container."""
  61. def __init__(self, tagdir, tags):
  62. super(Tags, self).__init__(tagdir)
  63. self.tags = tags
  64. def __setitem__(self, name, value):
  65. super(Tags, self)[name] = value
  66. self.tags[name] = value
  67. def __getitem__(self, name):
  68. return self.tags[name]
  69. def __len__(self):
  70. return len(self.tags)
  71. def iteritems(self):
  72. for k in self.tags:
  73. yield k, self[k]
  74. def read_packed_refs(f):
  75. """Read a packed refs file.
  76. Yields tuples with ref names and SHA1s.
  77. :param f: file-like object to read from
  78. """
  79. l = f.readline()
  80. for l in f.readlines():
  81. if l[0] == "#":
  82. # Comment
  83. continue
  84. if l[0] == "^":
  85. # FIXME: Return somehow
  86. continue
  87. yield tuple(l.rstrip("\n").split(" ", 2))
  88. class Repo(object):
  89. """A local git repository."""
  90. ref_locs = ['', REFSDIR, 'refs/tags', 'refs/heads', 'refs/remotes']
  91. def __init__(self, root):
  92. if os.path.isdir(os.path.join(root, ".git", OBJECTDIR)):
  93. self.bare = False
  94. self._controldir = os.path.join(root, ".git")
  95. elif os.path.isdir(os.path.join(root, OBJECTDIR)):
  96. self.bare = True
  97. self._controldir = root
  98. else:
  99. raise NotGitRepository(root)
  100. self.path = root
  101. self.tags = Tags(self.tagdir(), self.get_tags())
  102. self.object_store = DiskObjectStore(
  103. os.path.join(self.controldir(), OBJECTDIR))
  104. def controldir(self):
  105. """Return the path of the control directory."""
  106. return self._controldir
  107. def index_path(self):
  108. """Return path to the index file."""
  109. return os.path.join(self.controldir(), INDEX_FILENAME)
  110. def open_index(self):
  111. """Open the index for this repository."""
  112. from dulwich.index import Index
  113. return Index(self.index_path())
  114. def has_index(self):
  115. """Check if an index is present."""
  116. return os.path.exists(self.index_path())
  117. def fetch_objects(self, determine_wants, graph_walker, progress):
  118. """Fetch the missing objects required for a set of revisions.
  119. :param determine_wants: Function that takes a dictionary with heads
  120. and returns the list of heads to fetch.
  121. :param graph_walker: Object that can iterate over the list of revisions
  122. to fetch and has an "ack" method that will be called to acknowledge
  123. that a revision is present.
  124. :param progress: Simple progress function that will be called with
  125. updated progress strings.
  126. :return: tuple with number of objects, iterator over objects
  127. """
  128. wants = determine_wants(self.get_refs())
  129. haves = self.object_store.find_missing_revisions(graphwalker)
  130. return self.object_store.iter_shas(
  131. self.object_store.find_missing_objects(haves, wants, progress))
  132. def get_graph_walker(self, heads=None):
  133. if heads is None:
  134. heads = self.heads().values()
  135. return self.object_store.get_graph_walker(heads)
  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. """Return the SHA1 a ref is pointing to."""
  151. for dir in self.ref_locs:
  152. file = os.path.join(self.controldir(), dir, name)
  153. if os.path.exists(file):
  154. return self._get_ref(file)
  155. packed_refs = self.get_packed_refs()
  156. if name in packed_refs:
  157. return packed_refs[name]
  158. def get_refs(self):
  159. """Get dictionary with all refs."""
  160. ret = {}
  161. if self.head():
  162. ret['HEAD'] = self.head()
  163. for dir in ["refs/heads", "refs/tags"]:
  164. for name in os.listdir(os.path.join(self.controldir(), dir)):
  165. path = os.path.join(self.controldir(), dir, name)
  166. if os.path.isfile(path):
  167. ret["/".join([dir, name])] = self._get_ref(path)
  168. ret.update(self.get_packed_refs())
  169. return ret
  170. def get_packed_refs(self):
  171. """Get contents of the packed-refs file.
  172. :return: Dictionary mapping ref names to SHA1s
  173. :note: Will return an empty dictionary when no packed-refs file is
  174. present.
  175. """
  176. path = os.path.join(self.controldir(), 'packed-refs')
  177. if not os.path.exists(path):
  178. return {}
  179. ret = {}
  180. f = open(path, 'r')
  181. try:
  182. for entry in read_packed_refs(f):
  183. ret[entry[1]] = entry[0]
  184. return ret
  185. finally:
  186. f.close()
  187. def set_ref(self, name, value):
  188. """Set a new ref.
  189. :param name: Name of the ref
  190. :param value: SHA1 to point at
  191. """
  192. file = os.path.join(self.controldir(), name)
  193. dirpath = os.path.dirname(file)
  194. if not os.path.exists(dirpath):
  195. os.makedirs(dirpath)
  196. f = open(file, 'w')
  197. try:
  198. f.write(value+"\n")
  199. finally:
  200. f.close()
  201. def remove_ref(self, name):
  202. """Remove a ref.
  203. :param name: Name of the ref
  204. """
  205. file = os.path.join(self.controldir(), name)
  206. if os.path.exists(file):
  207. os.remove(file)
  208. def tagdir(self):
  209. """Tag directory."""
  210. return os.path.join(self.controldir(), REFSDIR, REFSDIR_TAGS)
  211. def get_tags(self):
  212. ret = {}
  213. for root, dirs, files in os.walk(self.tagdir()):
  214. for name in files:
  215. ret[name] = self._get_ref(os.path.join(root, name))
  216. return ret
  217. def heads(self):
  218. """Return dictionary with heads."""
  219. ret = {}
  220. for root, dirs, files in os.walk(os.path.join(self.controldir(), REFSDIR, REFSDIR_HEADS)):
  221. for name in files:
  222. ret[name] = self._get_ref(os.path.join(root, name))
  223. return ret
  224. def head(self):
  225. """Return the SHA1 pointed at by HEAD."""
  226. return self.ref('HEAD')
  227. def _get_object(self, sha, cls):
  228. assert len(sha) in (20, 40)
  229. ret = self.get_object(sha)
  230. if ret._type != cls._type:
  231. if cls is Commit:
  232. raise NotCommitError(ret)
  233. elif cls is Blob:
  234. raise NotBlobError(ret)
  235. elif cls is Tree:
  236. raise NotTreeError(ret)
  237. else:
  238. raise Exception("Type invalid: %r != %r" % (ret._type, cls._type))
  239. return ret
  240. def get_object(self, sha):
  241. return self.object_store[sha]
  242. def get_parents(self, sha):
  243. return self.object_store.get_commit_parents(sha)
  244. def commit(self, sha):
  245. return self._get_object(sha, Commit)
  246. def tree(self, sha):
  247. return self._get_object(sha, Tree)
  248. def tag(self, sha):
  249. return self._get_object(sha, Tag)
  250. def get_blob(self, sha):
  251. return self._get_object(sha, Blob)
  252. def revision_history(self, head):
  253. """Returns a list of the commits reachable from head.
  254. Returns a list of commit objects. the first of which will be the commit
  255. of head, then following theat will be the parents.
  256. Raises NotCommitError if any no commits are referenced, including if the
  257. head parameter isn't the sha of a commit.
  258. XXX: work out how to handle merges.
  259. """
  260. # We build the list backwards, as parents are more likely to be older
  261. # than children
  262. pending_commits = [head]
  263. history = []
  264. while pending_commits != []:
  265. head = pending_commits.pop(0)
  266. try:
  267. commit = self.commit(head)
  268. except KeyError:
  269. raise MissingCommitError(head)
  270. if commit in history:
  271. continue
  272. i = 0
  273. for known_commit in history:
  274. if known_commit.commit_time > commit.commit_time:
  275. break
  276. i += 1
  277. history.insert(i, commit)
  278. parents = commit.parents
  279. pending_commits += parents
  280. history.reverse()
  281. return history
  282. def __repr__(self):
  283. return "<Repo at %r>" % self.path
  284. @classmethod
  285. def init(cls, path, mkdir=True):
  286. controldir = os.path.join(path, ".git")
  287. os.mkdir(controldir)
  288. cls.init_bare(controldir)
  289. return cls(path)
  290. @classmethod
  291. def init_bare(cls, path, mkdir=True):
  292. for d in [[OBJECTDIR],
  293. [OBJECTDIR, "info"],
  294. [OBJECTDIR, "pack"],
  295. ["branches"],
  296. [REFSDIR],
  297. [REFSDIR, REFSDIR_TAGS],
  298. [REFSDIR, REFSDIR_HEADS],
  299. ["hooks"],
  300. ["info"]]:
  301. os.mkdir(os.path.join(path, *d))
  302. open(os.path.join(path, 'HEAD'), 'w').write("ref: refs/heads/master\n")
  303. open(os.path.join(path, 'description'), 'w').write("Unnamed repository")
  304. open(os.path.join(path, 'info', 'excludes'), 'w').write("")
  305. return cls(path)
  306. create = init_bare