repo.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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. ObjectStore,
  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 object_dir(self):
  133. """Return path of the object directory."""
  134. return os.path.join(self.controldir(), OBJECTDIR)
  135. @property
  136. def object_store(self):
  137. if self._object_store is None:
  138. self._object_store = ObjectStore(self.object_dir())
  139. return self._object_store
  140. def pack_dir(self):
  141. return os.path.join(self.object_dir(), PACKDIR)
  142. def _get_ref(self, file):
  143. f = open(file, 'rb')
  144. try:
  145. contents = f.read()
  146. if contents.startswith(SYMREF):
  147. ref = contents[len(SYMREF):]
  148. if ref[-1] == '\n':
  149. ref = ref[:-1]
  150. return self.ref(ref)
  151. assert len(contents) == 41, 'Invalid ref in %s' % file
  152. return contents[:-1]
  153. finally:
  154. f.close()
  155. def ref(self, name):
  156. """Return the SHA1 a ref is pointing to."""
  157. for dir in self.ref_locs:
  158. file = os.path.join(self.controldir(), dir, name)
  159. if os.path.exists(file):
  160. return self._get_ref(file)
  161. packed_refs = self.get_packed_refs()
  162. if name in packed_refs:
  163. return packed_refs[name]
  164. def get_refs(self):
  165. """Get dictionary with all refs."""
  166. ret = {}
  167. if self.head():
  168. ret['HEAD'] = self.head()
  169. for dir in ["refs/heads", "refs/tags"]:
  170. for name in os.listdir(os.path.join(self.controldir(), dir)):
  171. path = os.path.join(self.controldir(), dir, name)
  172. if os.path.isfile(path):
  173. ret["/".join([dir, name])] = self._get_ref(path)
  174. ret.update(self.get_packed_refs())
  175. return ret
  176. def get_packed_refs(self):
  177. """Get contents of the packed-refs file.
  178. :return: Dictionary mapping ref names to SHA1s
  179. :note: Will return an empty dictionary when no packed-refs file is
  180. present.
  181. """
  182. path = os.path.join(self.controldir(), 'packed-refs')
  183. if not os.path.exists(path):
  184. return {}
  185. ret = {}
  186. f = open(path, 'r')
  187. try:
  188. for entry in read_packed_refs(f):
  189. ret[entry[1]] = entry[0]
  190. return ret
  191. finally:
  192. f.close()
  193. def set_ref(self, name, value):
  194. """Set a new ref.
  195. :param name: Name of the ref
  196. :param value: SHA1 to point at
  197. """
  198. file = os.path.join(self.controldir(), name)
  199. dirpath = os.path.dirname(file)
  200. if not os.path.exists(dirpath):
  201. os.makedirs(dirpath)
  202. f = open(file, 'w')
  203. try:
  204. f.write(value+"\n")
  205. finally:
  206. f.close()
  207. def remove_ref(self, name):
  208. """Remove a ref.
  209. :param name: Name of the ref
  210. """
  211. file = os.path.join(self.controldir(), name)
  212. if os.path.exists(file):
  213. os.remove(file)
  214. def tagdir(self):
  215. """Tag directory."""
  216. return os.path.join(self.controldir(), REFSDIR, 'tags')
  217. def get_tags(self):
  218. ret = {}
  219. for root, dirs, files in os.walk(self.tagdir()):
  220. for name in files:
  221. ret[name] = self._get_ref(os.path.join(root, name))
  222. return ret
  223. def heads(self):
  224. """Return dictionary with heads."""
  225. ret = {}
  226. for root, dirs, files in os.walk(os.path.join(self.controldir(), REFSDIR, 'heads')):
  227. for name in files:
  228. ret[name] = self._get_ref(os.path.join(root, name))
  229. return ret
  230. def head(self):
  231. """Return the SHA1 pointed at by HEAD."""
  232. return self.ref('HEAD')
  233. def _get_object(self, sha, cls):
  234. assert len(sha) in (20, 40)
  235. ret = self.get_object(sha)
  236. if ret._type != cls._type:
  237. if cls is Commit:
  238. raise NotCommitError(ret)
  239. elif cls is Blob:
  240. raise NotBlobError(ret)
  241. elif cls is Tree:
  242. raise NotTreeError(ret)
  243. else:
  244. raise Exception("Type invalid: %r != %r" % (ret._type, cls._type))
  245. return ret
  246. def get_object(self, sha):
  247. return self.object_store[sha]
  248. def get_parents(self, sha):
  249. return self.commit(sha).parents
  250. def commit(self, sha):
  251. return self._get_object(sha, Commit)
  252. def tree(self, sha):
  253. return self._get_object(sha, Tree)
  254. def tag(self, sha):
  255. return self._get_object(sha, Tag)
  256. def get_blob(self, sha):
  257. return self._get_object(sha, Blob)
  258. def revision_history(self, head):
  259. """Returns a list of the commits reachable from head.
  260. Returns a list of commit objects. the first of which will be the commit
  261. of head, then following theat will be the parents.
  262. Raises NotCommitError if any no commits are referenced, including if the
  263. head parameter isn't the sha of a commit.
  264. XXX: work out how to handle merges.
  265. """
  266. # We build the list backwards, as parents are more likely to be older
  267. # than children
  268. pending_commits = [head]
  269. history = []
  270. while pending_commits != []:
  271. head = pending_commits.pop(0)
  272. try:
  273. commit = self.commit(head)
  274. except KeyError:
  275. raise MissingCommitError(head)
  276. if commit in history:
  277. continue
  278. i = 0
  279. for known_commit in history:
  280. if known_commit.commit_time > commit.commit_time:
  281. break
  282. i += 1
  283. history.insert(i, commit)
  284. parents = commit.parents
  285. pending_commits += parents
  286. history.reverse()
  287. return history
  288. def __repr__(self):
  289. return "<Repo at %r>" % self.path
  290. @classmethod
  291. def init(cls, path, mkdir=True):
  292. controldir = os.path.join(path, ".git")
  293. os.mkdir(controldir)
  294. cls.init_bare(controldir)
  295. @classmethod
  296. def init_bare(cls, path, mkdir=True):
  297. for d in [[OBJECTDIR],
  298. [OBJECTDIR, "info"],
  299. [OBJECTDIR, "pack"],
  300. ["branches"],
  301. [REFSDIR],
  302. ["refs", "tags"],
  303. ["refs", "heads"],
  304. ["hooks"],
  305. ["info"]]:
  306. os.mkdir(os.path.join(path, *d))
  307. open(os.path.join(path, 'HEAD'), 'w').write("ref: refs/heads/master\n")
  308. open(os.path.join(path, 'description'), 'w').write("Unnamed repository")
  309. open(os.path.join(path, 'info', 'excludes'), 'w').write("")
  310. create = init_bare