appveyor-irc-notify.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. # coding=utf8
  2. # Copyright (C) 2015-2016 Christopher R. Wood
  3. # Copyright (c) 2018 The Tor Project
  4. # Copyright (c) 2018 isis agora lovecruft
  5. #
  6. # From: https://raw.githubusercontent.com/gridsync/gridsync/def54f8166089b733d166665fdabcad4cdc526d8/misc/irc-notify.py
  7. # and: https://github.com/gridsync/gridsync
  8. #
  9. # Modified by nexB on October 2016:
  10. # - rework the handling of environment variables.
  11. # - made the script use functions
  12. # - support only Appveyor loading its environment variable to craft IRC notices.
  13. #
  14. # Modified by isis agora lovecruft <isis@torproject.org> in 2018:
  15. # - Make IRC server configurable.
  16. # - Make bot IRC nick deterministic.
  17. # - Make bot join the channel rather than sending NOTICE messages externally.
  18. # - Fix a bug which always caused sys.exit() to be logged as a traceback.
  19. # - Actually reset the IRC colour codes after printing.
  20. #
  21. # Modified by Marcin Cieślak in 2018:
  22. # - Accept UTF-8
  23. # - only guess github URLs
  24. # - stop using ANSI colors
  25. #
  26. # Modified by teor in 2018:
  27. # - fix github provider detection ('gitHub' or 'gitHubEnterprise', apparently)
  28. # - make short commits 10 hexdigits long (that's what git does for tor)
  29. # - generate correct branches and URLs for pull requests and tags
  30. # - switch to one URL per line
  31. # This program is free software; you can redistribute it and/or modify it under the
  32. # terms of the GNU General Public License as published by the Free Software Foundation;
  33. # either version 2 of the License, or (at your option) any later version.
  34. #
  35. # This program is distributed in the hope that it will be useful, but WITHOUT ANY
  36. # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
  37. # PARTICULAR PURPOSE. See the GNU General Public License for more details.
  38. #
  39. # You should have received a copy of the GNU General Public License along with this
  40. # program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street,
  41. # Fifth Floor, Boston, MA 02110-1301 USA.
  42. """Simple AppVeyor IRC notification script.
  43. The first argument is an IRC server and port; the second is the channel. Other
  44. arguments passed to the script will be sent as notice messages content and any
  45. {var}-formatted environment variables will be expanded automatically, replaced
  46. with a corresponding Appveyor environment variable value. Use commas to
  47. delineate multiple messages.
  48. Example:
  49. export APPVEYOR_ACCOUNT_NAME=isislovecruft
  50. export APPVEYOR_BUILD_VERSION=1
  51. export APPVEYOR_PROJECT_NAME=tor
  52. export APPVEYOR_PULL_REQUEST_NUMBER=pull_request_number
  53. export APPVEYOR_PULL_REQUEST_TITLE=pull_request_title
  54. export APPVEYOR_REPO_BRANCH=repo_branch
  55. export APPVEYOR_REPO_COMMIT=22c95b72e29248dc4de9b85e590ee18f6f587de8
  56. export APPVEYOR_REPO_COMMIT_AUTHOR=isislovecruft
  57. export APPVEYOR_REPO_COMMIT_MESSAGE="some IRC test"
  58. export APPVEYOR_REPO_COMMIT_TIMESTAMP=2018-04-23
  59. export APPVEYOR_REPO_NAME=isislovecruft/tor
  60. export APPVEYOR_REPO_PROVIDER=github
  61. export APPVEYOR_URL=https://ci.appveyor.com
  62. python ./appveyor-irc-notify.py irc.oftc.net:6697 tor-ci '{repo_name} {repo_branch} {short_commit} - {repo_commit_author}: {repo_commit_message}','Build #{build_version} passed. Details: {build_url} | Commit: {commit_url}
  63. See also https://github.com/gridsync/gridsync/blob/master/appveyor.yml for examples
  64. in Appveyor's YAML:
  65. on_success:
  66. - "python scripts/test/appveyor-irc-notify.py irc.oftc.net:6697 tor-ci success
  67. on_failure:
  68. - "python scripts/test/appveyor-irc-notify.py irc.oftc.net:6697 tor-ci failure
  69. """
  70. # Future imports for Python 2.7, mandatory in 3.0
  71. from __future__ import division
  72. from __future__ import print_function
  73. from __future__ import unicode_literals
  74. import os
  75. import random
  76. import socket
  77. import ssl
  78. import sys
  79. import time
  80. def appveyor_vars():
  81. """
  82. Return a dict of key value crafted from appveyor environment variables.
  83. """
  84. vars = dict([
  85. (
  86. v.replace('APPVEYOR_', '').lower(),
  87. os.getenv(v, '').decode('utf-8')
  88. ) for v in [
  89. 'APPVEYOR_ACCOUNT_NAME',
  90. 'APPVEYOR_BUILD_VERSION',
  91. 'APPVEYOR_PROJECT_NAME',
  92. 'APPVEYOR_PULL_REQUEST_HEAD_COMMIT',
  93. 'APPVEYOR_PULL_REQUEST_HEAD_REPO_BRANCH',
  94. 'APPVEYOR_PULL_REQUEST_HEAD_REPO_NAME',
  95. 'APPVEYOR_PULL_REQUEST_NUMBER',
  96. 'APPVEYOR_PULL_REQUEST_TITLE',
  97. 'APPVEYOR_REPO_BRANCH',
  98. 'APPVEYOR_REPO_COMMIT',
  99. 'APPVEYOR_REPO_COMMIT_AUTHOR',
  100. 'APPVEYOR_REPO_COMMIT_AUTHOR_EMAIL',
  101. 'APPVEYOR_REPO_COMMIT_MESSAGE',
  102. 'APPVEYOR_REPO_COMMIT_MESSAGE_EXTENDED',
  103. 'APPVEYOR_REPO_COMMIT_TIMESTAMP',
  104. 'APPVEYOR_REPO_NAME',
  105. 'APPVEYOR_REPO_PROVIDER',
  106. 'APPVEYOR_REPO_TAG_NAME',
  107. 'APPVEYOR_URL',
  108. ]
  109. ])
  110. BUILD_FMT = u'{url}/project/{account_name}/{project_name}/build/{build_version}'
  111. if vars["repo_tag_name"]:
  112. BRANCH_FMT = u'{repo_name} {repo_tag_name} {short_commit}'
  113. else:
  114. BRANCH_FMT = u'{repo_name} {repo_branch} {short_commit}'
  115. vars.update(head_commit=vars["repo_commit"])
  116. if vars["repo_provider"].lower().startswith('github'):
  117. COMMIT_FMT = u'https://github.com/{repo_name}/commit/{repo_commit}'
  118. if vars["pull_request_number"]:
  119. vars.update(head_commit=vars["pull_request_head_commit"])
  120. BRANCH_FMT = u'{repo_name} {repo_branch} pull {pull_request_head_repo_name} {pull_request_head_repo_branch} {short_commit}'
  121. COMMIT_FMT = u'https://github.com/{pull_request_head_repo_name}/commit/{pull_request_head_commit}'
  122. PULL_FMT = u'https://github.com/{repo_name}/pull/{pull_request_number}'
  123. vars.update(pull_url=PULL_FMT.format(**vars))
  124. vars.update(commit_url=COMMIT_FMT.format(**vars))
  125. vars.update(short_commit=vars["head_commit"][:10])
  126. vars.update(
  127. build_url=BUILD_FMT.format(**vars),
  128. branch_detail=BRANCH_FMT.format(**vars),
  129. )
  130. return vars
  131. def notify():
  132. """
  133. Send IRC notification
  134. """
  135. apvy_vars = appveyor_vars()
  136. server, port = sys.argv[1].rsplit(":", 1)
  137. channel = sys.argv[2]
  138. success = sys.argv[3] == "success"
  139. failure = sys.argv[3] == "failure"
  140. if success or failure:
  141. messages = []
  142. messages.append(u"{branch_detail} - {repo_commit_author}: {repo_commit_message}")
  143. if success:
  144. messages.append(u"Build #{build_version} passed. Details: {build_url}")
  145. if failure:
  146. messages.append(u"Build #{build_version} failed. Details: {build_url}")
  147. if "commit_url" in apvy_vars:
  148. messages.append(u"Commit: {commit_url}")
  149. if "pull_url" in apvy_vars:
  150. messages.append(u"Pull: {pull_url}")
  151. else:
  152. messages = sys.argv[3:]
  153. messages = ' '.join(messages)
  154. messages = messages.decode("utf-8").split(',')
  155. print(repr(apvy_vars))
  156. messages = [msg.format(**apvy_vars).strip() for msg in messages]
  157. irc_username = 'appveyor-ci'
  158. irc_nick = irc_username
  159. # establish connection
  160. irc_sock = ssl.wrap_socket(socket.socket(socket.AF_INET, socket.SOCK_STREAM))
  161. irc_sock.connect((socket.gethostbyname(server), int(port)))
  162. irc_sock.send('NICK {0}\r\nUSER {0} * 0 :{0}\r\n'.format(irc_username).encode())
  163. irc_sock.send('JOIN #{0}\r\n'.format(channel).encode())
  164. irc_file = irc_sock.makefile()
  165. while irc_file:
  166. line = irc_file.readline()
  167. print(line.rstrip())
  168. response = line.split()
  169. if response[0] == 'PING':
  170. irc_file.send('PONG {}\r\n'.format(response[1]).encode())
  171. elif response[1] == '433':
  172. irc_sock.send('NICK {}\r\n'.format(irc_nick).encode())
  173. elif response[1] == '001':
  174. time.sleep(5)
  175. # send notification
  176. for msg in messages:
  177. print(u'PRIVMSG #{} :{}'.format(channel, msg).encode("utf-8"))
  178. irc_sock.send(u'PRIVMSG #{} :{}\r\n'.format(channel, msg).encode("utf-8"))
  179. time.sleep(5)
  180. return
  181. if __name__ == '__main__':
  182. try:
  183. notify()
  184. except:
  185. import traceback
  186. print('ERROR: Failed to send notification: \n' + traceback.format_exc())