repo.py 12 KB

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