A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

218 linhas
8.2 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. def do_delete(self):
  143. """Delete a branch, while making sure that we are not already on it."""
  144. try:
  145. target = self.data.args[2]
  146. except IndexError: # No branch name provided
  147. self.reply(self.data, "delete which branch?")
  148. return
  149. current_branch = self.repo.active_branch.name
  150. if current_branch == target:
  151. msg = "you're currently on this branch; please checkout to a different branch before deleting."
  152. self.reply(self.data, msg)
  153. return
  154. try:
  155. ref = getattr(self.repo.branches, target)
  156. except AttributeError:
  157. msg = "branch \x0302{0}\x0301 doesn't exist!".format(target)
  158. self.reply(self.data, msg)
  159. else:
  160. self.repo.git.branch("-d", ref)
  161. msg = "branch \x0302{0}\x0301 has been deleted locally."
  162. self.reply(self.data, msg.format(target))
  163. def do_pull(self):
  164. """Pull from our remote repository."""
  165. branch = current_branch = self.repo.active_branch.name
  166. msg = "pulling from remote (currently on \x0302{0}\x0301)..."
  167. self.reply(self.data, msg.format(branch))
  168. remote = self.get_remote()
  169. if not remote:
  170. return
  171. result = remote.pull()
  172. updated = [info for info in result if info.flags != info.HEAD_UPTODATE]
  173. if updated:
  174. branches = ", ".join([info.ref.remote_head for info in updated])
  175. msg = "done; updates to \x0302{0}\x0301 (from {1})."
  176. self.reply(self.data, msg.format(branches, remote.url))
  177. else:
  178. self.reply(self.data, "done; no new changes.")
  179. def do_status(self):
  180. """Check if we have anything to pull."""
  181. remote = self.get_remote()
  182. if not remote:
  183. return
  184. since = self.get_time_since(self.repo.head.object.committed_date)
  185. result = remote.fetch(dry_run=True)
  186. updated = [info for info in result if info.flags != info.HEAD_UPTODATE]
  187. if updated:
  188. branches = ", ".join([info.ref.remote_head for info in updated])
  189. msg = "last local commit was \x02{0}\x0F ago; updates to \x0302{1}\x0301."
  190. self.reply(self.data, msg.format(since, branches))
  191. else:
  192. msg = "last commit was \x02{0}\x0F ago. Local copy is up-to-date with remote."
  193. self.reply(self.data, msg.format(since))