2
0

repo.py 13 KB

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