repo.py 12 KB

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