repo.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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(self, target, determine_wants=None, progress=None):
  201. """Fetch objects into another repository.
  202. :param target: The target repository
  203. :param determine_wants: Optional function to determine what refs to
  204. fetch.
  205. :param progress: Optional progress function
  206. """
  207. if determine_wants is None:
  208. determine_wants = lambda heads: heads.values()
  209. target.object_store.add_objects(
  210. self.fetch_objects(determine_wants, target.get_graph_walker(),
  211. progress))
  212. return self.get_refs()
  213. def fetch_objects(self, determine_wants, graph_walker, progress):
  214. """Fetch the missing objects required for a set of revisions.
  215. :param determine_wants: Function that takes a dictionary with heads
  216. and returns the list of heads to fetch.
  217. :param graph_walker: Object that can iterate over the list of revisions
  218. to fetch and has an "ack" method that will be called to acknowledge
  219. that a revision is present.
  220. :param progress: Simple progress function that will be called with
  221. updated progress strings.
  222. :return: iterator over objects, with __len__ implemented
  223. """
  224. wants = determine_wants(self.get_refs())
  225. haves = self.object_store.find_common_revisions(graph_walker)
  226. return self.object_store.iter_shas(
  227. self.object_store.find_missing_objects(haves, wants, progress))
  228. def get_graph_walker(self, heads=None):
  229. if heads is None:
  230. heads = self.refs.as_dict('refs/heads').values()
  231. return self.object_store.get_graph_walker(heads)
  232. def ref(self, name):
  233. """Return the SHA1 a ref is pointing to."""
  234. try:
  235. return self.refs.follow(name)
  236. except KeyError:
  237. return self.get_packed_refs()[name]
  238. def get_refs(self):
  239. """Get dictionary with all refs."""
  240. ret = {}
  241. try:
  242. if self.head():
  243. ret['HEAD'] = self.head()
  244. except KeyError:
  245. pass
  246. ret.update(self.refs.as_dict())
  247. ret.update(self.get_packed_refs())
  248. return ret
  249. def get_packed_refs(self):
  250. """Get contents of the packed-refs file.
  251. :return: Dictionary mapping ref names to SHA1s
  252. :note: Will return an empty dictionary when no packed-refs file is
  253. present.
  254. """
  255. path = os.path.join(self.controldir(), 'packed-refs')
  256. if not os.path.exists(path):
  257. return {}
  258. ret = {}
  259. f = open(path, 'rb')
  260. try:
  261. for entry in read_packed_refs(f):
  262. ret[entry[1]] = entry[0]
  263. return ret
  264. finally:
  265. f.close()
  266. def head(self):
  267. """Return the SHA1 pointed at by HEAD."""
  268. return self.refs.follow('HEAD')
  269. def _get_object(self, sha, cls):
  270. assert len(sha) in (20, 40)
  271. ret = self.get_object(sha)
  272. if ret._type != cls._type:
  273. if cls is Commit:
  274. raise NotCommitError(ret)
  275. elif cls is Blob:
  276. raise NotBlobError(ret)
  277. elif cls is Tree:
  278. raise NotTreeError(ret)
  279. else:
  280. raise Exception("Type invalid: %r != %r" % (ret._type, cls._type))
  281. return ret
  282. def get_object(self, sha):
  283. return self.object_store[sha]
  284. def get_parents(self, sha):
  285. return self.commit(sha).parents
  286. def get_config(self):
  287. from configobj import ConfigObj
  288. return ConfigObj(os.path.join(self._controldir, 'config'))
  289. def commit(self, sha):
  290. return self._get_object(sha, Commit)
  291. def tree(self, sha):
  292. return self._get_object(sha, Tree)
  293. def tag(self, sha):
  294. return self._get_object(sha, Tag)
  295. def get_blob(self, sha):
  296. return self._get_object(sha, Blob)
  297. def revision_history(self, head):
  298. """Returns a list of the commits reachable from head.
  299. Returns a list of commit objects. the first of which will be the commit
  300. of head, then following theat will be the parents.
  301. Raises NotCommitError if any no commits are referenced, including if the
  302. head parameter isn't the sha of a commit.
  303. XXX: work out how to handle merges.
  304. """
  305. # We build the list backwards, as parents are more likely to be older
  306. # than children
  307. pending_commits = [head]
  308. history = []
  309. while pending_commits != []:
  310. head = pending_commits.pop(0)
  311. try:
  312. commit = self.commit(head)
  313. except KeyError:
  314. raise MissingCommitError(head)
  315. if commit in history:
  316. continue
  317. i = 0
  318. for known_commit in history:
  319. if known_commit.commit_time > commit.commit_time:
  320. break
  321. i += 1
  322. history.insert(i, commit)
  323. parents = commit.parents
  324. pending_commits += parents
  325. history.reverse()
  326. return history
  327. def __repr__(self):
  328. return "<Repo at %r>" % self.path
  329. def __getitem__(self, name):
  330. if len(name) in (20, 40):
  331. return self.object_store[name]
  332. return self.object_store[self.refs[name]]
  333. def __setitem__(self, name, value):
  334. if name.startswith("refs/") or name == "HEAD":
  335. if isinstance(value, ShaFile):
  336. self.refs[name] = value.id
  337. elif isinstance(value, str):
  338. self.refs[name] = value
  339. else:
  340. raise TypeError(value)
  341. raise ValueError(name)
  342. def __delitem__(self, name):
  343. if name.startswith("refs") or name == "HEAD":
  344. del self.refs[name]
  345. raise ValueError(name)
  346. def do_commit(self, committer, message,
  347. author=None, commit_timestamp=None,
  348. commit_timezone=None, author_timestamp=None,
  349. author_timezone=None, tree=None):
  350. """Create a new commit.
  351. :param committer: Committer fullname
  352. :param message: Commit message
  353. :param author: Author fullname (defaults to committer)
  354. :param commit_timestamp: Commit timestamp (defaults to now)
  355. :param commit_timezone: Commit timestamp timezone (defaults to GMT)
  356. :param author_timestamp: Author timestamp (defaults to commit timestamp)
  357. :param author_timezone: Author timestamp timezone
  358. (defaults to commit timestamp timezone)
  359. :param tree: SHA1 of the tree root to use (if not specified the current index will be committed).
  360. :return: New commit SHA1
  361. """
  362. from dulwich.index import commit_index
  363. import time
  364. index = self.open_index()
  365. c = Commit()
  366. if tree is None:
  367. c.tree = commit_index(self.object_store, index)
  368. else:
  369. c.tree = tree
  370. c.committer = committer
  371. if commit_timestamp is None:
  372. commit_timestamp = time.time()
  373. c.commit_time = int(commit_timestamp)
  374. if commit_timezone is None:
  375. commit_timezone = 0
  376. c.commit_timezone = commit_timezone
  377. if author is None:
  378. author = committer
  379. c.author = author
  380. if author_timestamp is None:
  381. author_timestamp = commit_timestamp
  382. c.author_time = int(author_timestamp)
  383. if author_timezone is None:
  384. author_timezone = commit_timezone
  385. c.author_timezone = author_timezone
  386. c.message = message
  387. self.object_store.add_object(c)
  388. self.refs["HEAD"] = c.id
  389. return c.id
  390. @classmethod
  391. def init(cls, path, mkdir=True):
  392. controldir = os.path.join(path, ".git")
  393. os.mkdir(controldir)
  394. cls.init_bare(controldir)
  395. return cls(path)
  396. @classmethod
  397. def init_bare(cls, path, mkdir=True):
  398. for d in [[OBJECTDIR],
  399. [OBJECTDIR, "info"],
  400. [OBJECTDIR, "pack"],
  401. ["branches"],
  402. [REFSDIR],
  403. [REFSDIR, REFSDIR_TAGS],
  404. [REFSDIR, REFSDIR_HEADS],
  405. ["hooks"],
  406. ["info"]]:
  407. os.mkdir(os.path.join(path, *d))
  408. ret = cls(path)
  409. ret.refs.set_ref("HEAD", "refs/heads/master")
  410. open(os.path.join(path, 'description'), 'wb').write("Unnamed repository")
  411. open(os.path.join(path, 'info', 'excludes'), 'wb').write("")
  412. open(os.path.join(path, 'config'), 'wb').write("""[core]
  413. repositoryformatversion = 0
  414. filemode = true
  415. bare = false
  416. logallrefupdates = true
  417. """)
  418. return ret
  419. create = init_bare