repo.py 11 KB

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