A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.

236 righe
9.3 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2009-2012 by Ben Kurtovic <ben.kurtovic@verizon.net>
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a copy
  6. # of this software and associated documentation files (the "Software"), to deal
  7. # in the Software without restriction, including without limitation the rights
  8. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. # copies of the Software, and to permit persons to whom the Software is
  10. # furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. # SOFTWARE.
  22. import time
  23. import git
  24. from earwigbot.commands import BaseCommand
  25. class Command(BaseCommand):
  26. """Commands to interface with the bot's git repository; use '!git' for a
  27. sub-command list."""
  28. name = "git"
  29. repos = {
  30. "core": "/home/earwig/git/earwigbot",
  31. "plugins": "/home/earwig/git/earwigbot-plugins",
  32. }
  33. def process(self, data):
  34. self.data = data
  35. if data.host not in self.config.irc["permissions"]["owners"]:
  36. msg = "you must be a bot owner to use this command."
  37. self.reply(data, msg)
  38. return
  39. if not data.args or data.args[0] == "help":
  40. self.do_help()
  41. return
  42. command = data.args[0]
  43. try:
  44. repo_name = data.args[1]
  45. except IndexError:
  46. repos = self.get_repos()
  47. msg = "which repo do you want to work with (options are {0})?"
  48. self.reply(data, msg.format(repos))
  49. return
  50. if repo_name not in self.repos:
  51. repos = self.get_repos()
  52. msg = "repository must be one of the following: {0}"
  53. self.reply(data, msg.format(repos))
  54. return
  55. self.repo = git.Repo(self.repos[repo_name])
  56. if command == "branch":
  57. self.do_branch()
  58. elif command == "branches":
  59. self.do_branches()
  60. elif command == "checkout":
  61. self.do_checkout()
  62. elif command == "delete":
  63. self.do_delete()
  64. elif command == "pull":
  65. self.do_pull()
  66. elif command == "status":
  67. self.do_status()
  68. else: # They asked us to do something we don't know
  69. msg = "unknown argument: \x0303{0}\x0301.".format(data.args[0])
  70. self.reply(data, msg)
  71. def get_repos(self):
  72. data = self.repos.iteritems()
  73. repos = ["\x0302{0}\x0301 ({1})".format(k, v) for k, v in data]
  74. return ", ".join(repos)
  75. def get_remote(self):
  76. try:
  77. remote_name = self.data.args[2]
  78. except IndexError:
  79. remote_name = "origin"
  80. try:
  81. return getattr(self.repo.remotes, remote_name)
  82. except AttributeError:
  83. msg = "unknown remote: \x0302{0}\x0301".format(remote_name)
  84. self.reply(self.data, msg)
  85. def get_time_since(self, date):
  86. diff = time.mktime(time.gmtime()) - date
  87. if diff < 60:
  88. return "{0} seconds".format(int(diff))
  89. if diff < 60 * 60:
  90. return "{0} minutes".format(int(diff / 60))
  91. if diff < 60 * 60 * 24:
  92. return "{0} hours".format(int(diff / 60 / 60))
  93. return "{0} days".format(int(diff / 60 / 60 / 24))
  94. def do_help(self):
  95. """Display all commands."""
  96. help = {
  97. "branch": "get current branch",
  98. "branches": "get all branches",
  99. "checkout": "switch branches",
  100. "delete": "delete an old branch",
  101. "pull": "update everything from the remote server",
  102. "status": "check if we are up-to-date",
  103. }
  104. subcommands = ""
  105. for key in sorted(help.keys()):
  106. subcommands += "\x0303{0}\x0301 ({1}), ".format(key, help[key])
  107. subcommands = subcommands[:-2] # Trim last comma and space
  108. msg = "sub-commands are: {0}; repos are: {1}. Syntax: !git \x0303subcommand\x0301 \x0302repo\x0301."
  109. self.reply(self.data, msg.format(subcommands, self.get_repos()))
  110. def do_branch(self):
  111. """Get our current branch."""
  112. branch = self.repo.active_branch.name
  113. msg = "currently on branch \x0302{0}\x0301.".format(branch)
  114. self.reply(self.data, msg)
  115. def do_branches(self):
  116. """Get a list of branches."""
  117. branches = [branch.name for branch in self.repo.branches]
  118. msg = "branches: \x0302{0}\x0301.".format(", ".join(branches))
  119. self.reply(self.data, msg)
  120. def do_checkout(self):
  121. """Switch branches."""
  122. try:
  123. target = self.data.args[2]
  124. except IndexError: # No branch name provided
  125. self.reply(self.data, "switch to which branch?")
  126. return
  127. current_branch = self.repo.active_branch.name
  128. if target == current_branch:
  129. msg = "already on \x0302{0}\x0301!".format(target)
  130. self.reply(self.data, msg)
  131. return
  132. try:
  133. ref = getattr(self.repo.branches, target)
  134. except AttributeError:
  135. msg = "branch \x0302{0}\x0301 doesn't exist!".format(target)
  136. self.reply(self.data, msg)
  137. else:
  138. ref.checkout()
  139. ms = "switched from branch \x0302{1}\x0301 to \x0302{1}\x0301."
  140. msg = ms.format(current_branch, target)
  141. self.reply(self.data, msg)
  142. log = "{0} checked out branch {1} of {2}"
  143. logmsg = log.format(self.data.nick, target, self.repo.working_dir)
  144. self.logger.info(logmsg)
  145. def do_delete(self):
  146. """Delete a branch, while making sure that we are not already on it."""
  147. try:
  148. target = self.data.args[2]
  149. except IndexError: # No branch name provided
  150. self.reply(self.data, "delete which branch?")
  151. return
  152. current_branch = self.repo.active_branch.name
  153. if current_branch == target:
  154. msg = "you're currently on this branch; please checkout to a different branch before deleting."
  155. self.reply(self.data, msg)
  156. return
  157. try:
  158. ref = getattr(self.repo.branches, target)
  159. except AttributeError:
  160. msg = "branch \x0302{0}\x0301 doesn't exist!".format(target)
  161. self.reply(self.data, msg)
  162. else:
  163. self.repo.git.branch("-d", ref)
  164. msg = "branch \x0302{0}\x0301 has been deleted locally."
  165. self.reply(self.data, msg.format(target))
  166. log = "{0} deleted branch {1} of {2}"
  167. logmsg = log.format(self.data.nick, target, self.repo.working_dir)
  168. self.logger.info(logmsg)
  169. def do_pull(self):
  170. """Pull from our remote repository."""
  171. branch = self.repo.active_branch.name
  172. msg = "pulling from remote (currently on \x0302{0}\x0301)..."
  173. self.reply(self.data, msg.format(branch))
  174. remote = self.get_remote()
  175. if not remote:
  176. return
  177. result = remote.pull()
  178. updated = [info for info in result if info.flags != info.HEAD_UPTODATE]
  179. if updated:
  180. branches = ", ".join([info.ref.remote_head for info in updated])
  181. msg = "done; updates to \x0302{0}\x0301 (from {1})."
  182. self.reply(self.data, msg.format(branches, remote.url))
  183. log = "{0} pulled {1} of {2} (updates to {3})"
  184. self.logger.info(log.format(self.data.nick, remote.name,
  185. self.repo.working_dir, branches))
  186. else:
  187. self.reply(self.data, "done; no new changes.")
  188. log = "{0} pulled {1} of {2} (no updates)"
  189. self.logger.info(log.format(self.data.nick, remote.name,
  190. self.repo.working_dir))
  191. def do_status(self):
  192. """Check if we have anything to pull."""
  193. remote = self.get_remote()
  194. if not remote:
  195. return
  196. since = self.get_time_since(self.repo.head.object.committed_date)
  197. result = remote.fetch(dry_run=True)
  198. updated = [info for info in result if info.flags != info.HEAD_UPTODATE]
  199. if updated:
  200. branches = ", ".join([info.ref.remote_head for info in updated])
  201. msg = "last local commit was \x02{0}\x0F ago; updates to \x0302{1}\x0301."
  202. self.reply(self.data, msg.format(since, branches))
  203. log = "{0} got status of {1} of {2} (updates to {3})"
  204. self.logger.info(log.format(self.data.nick, remote.name,
  205. self.repo.working_dir, branches))
  206. else:
  207. msg = "last commit was \x02{0}\x0F ago. Local copy is up-to-date with remote."
  208. self.reply(self.data, msg.format(since))
  209. log = "{0} pulled {1} of {2} (no updates)"
  210. self.logger.info(log.format(self.data.nick, remote.name,
  211. self.repo.working_dir))