appveyor-irc-notify.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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. # This program is free software; you can redistribute it and/or modify it under the
  29. # terms of the GNU General Public License as published by the Free Software Foundation;
  30. # either version 2 of the License, or (at your option) any later version.
  31. #
  32. # This program is distributed in the hope that it will be useful, but WITHOUT ANY
  33. # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
  34. # PARTICULAR PURPOSE. See the GNU General Public License for more details.
  35. #
  36. # You should have received a copy of the GNU General Public License along with this
  37. # program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street,
  38. # Fifth Floor, Boston, MA 02110-1301 USA.
  39. """Simple AppVeyor IRC notification script.
  40. The first argument is an IRC server and port; the second is the channel. Other
  41. arguments passed to the script will be sent as notice messages content and any
  42. {var}-formatted environment variables will be expanded automatically, replaced
  43. with a corresponding Appveyor environment variable value. Use commas to
  44. delineate multiple messages.
  45. Example:
  46. export APPVEYOR_URL=https://ci.appveyor.com
  47. export APPVEYOR_PROJECT_NAME=tor
  48. export APPVEYOR_REPO_COMMIT_AUTHOR=isislovecruft
  49. export APPVEYOR_REPO_COMMIT_TIMESTAMP=2018-04-23
  50. export APPVEYOR_REPO_PROVIDER=gihub
  51. export APPVEYOR_REPO_BRANCH=repo_branch
  52. export APPVEYOR_PULL_REQUEST_TITLE=pull_request_title
  53. export APPVEYOR_BUILD_VERSION=1
  54. export APPVEYOR_REPO_COMMIT=22c95b72e29248dc4de9b85e590ee18f6f587de8
  55. export APPVEYOR_REPO_COMMIT_MESSAGE="some IRC test"
  56. export APPVEYOR_ACCOUNT_NAME=isislovecruft
  57. export APPVEYOR_PULL_REQUEST_NUMBER=pull_request_number
  58. export APPVEYOR_REPO_NAME=isislovecruft/tor
  59. 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}
  60. See also https://github.com/gridsync/gridsync/blob/master/appveyor.yml for examples
  61. in Appveyor's YAML:
  62. on_success:
  63. - "python scripts/test/appveyor-irc-notify.py irc.oftc.net:6697 tor-ci success
  64. on_failure:
  65. - "python scripts/test/appveyor-irc-notify.py irc.oftc.net:6697 tor-ci failure
  66. """
  67. from __future__ import print_function
  68. from __future__ import absolute_import
  69. import os
  70. import random
  71. import socket
  72. import ssl
  73. import sys
  74. import time
  75. def appveyor_vars():
  76. """
  77. Return a dict of key value carfted from appveyor environment variables.
  78. """
  79. vars = dict([
  80. (
  81. v.replace('APPVEYOR_', '').lower(),
  82. os.getenv(v, '').decode('utf-8')
  83. ) for v in [
  84. 'APPVEYOR_URL',
  85. 'APPVEYOR_REPO_COMMIT_MESSAGE_EXTENDED',
  86. 'APPVEYOR_REPO_BRANCH',
  87. 'APPVEYOR_REPO_COMMIT_AUTHOR',
  88. 'APPVEYOR_REPO_COMMIT_AUTHOR_EMAIL',
  89. 'APPVEYOR_REPO_COMMIT_TIMESTAMP',
  90. 'APPVEYOR_REPO_PROVIDER',
  91. 'APPVEYOR_PROJECT_NAME',
  92. 'APPVEYOR_PULL_REQUEST_TITLE',
  93. 'APPVEYOR_BUILD_VERSION',
  94. 'APPVEYOR_REPO_COMMIT',
  95. 'APPVEYOR_REPO_COMMIT_MESSAGE',
  96. 'APPVEYOR_ACCOUNT_NAME',
  97. 'APPVEYOR_PULL_REQUEST_NUMBER',
  98. 'APPVEYOR_REPO_NAME'
  99. ]
  100. ])
  101. BUILD_FMT = u'{url}/project/{account_name}/{project_name}/build/{build_version}'
  102. if vars["repo_provider"].lower().startswith('github'):
  103. COMMIT_FMT = u'https://{repo_provider}.com/{repo_name}/commit/{repo_commit}'
  104. vars.update(commit_url=COMMIT_FMT.format(**vars))
  105. vars.update(
  106. build_url=BUILD_FMT.format(**vars),
  107. short_commit=vars["repo_commit"][:7],
  108. )
  109. return vars
  110. def notify():
  111. """
  112. Send IRC notification
  113. """
  114. apvy_vars = appveyor_vars()
  115. server, port = sys.argv[1].rsplit(":", 1)
  116. channel = sys.argv[2]
  117. success = sys.argv[3] == "success"
  118. failure = sys.argv[3] == "failure"
  119. if success or failure:
  120. messages = []
  121. messages.append(u"{repo_name} {repo_branch} {short_commit} - {repo_commit_author}: {repo_commit_message}")
  122. if success:
  123. m = u"Build #{build_version} passed. Details: {build_url}"
  124. if failure:
  125. m = u"Build #{build_version} failed. Details: {build_url}"
  126. if "commit_url" in apvy_vars:
  127. m += " Commit: {commit_url}"
  128. messages.append(m)
  129. else:
  130. messages = sys.argv[3:]
  131. messages = ' '.join(messages)
  132. messages = messages.decode("utf-8").split(',')
  133. print(repr(apvy_vars))
  134. messages = [msg.format(**apvy_vars).strip() for msg in messages]
  135. irc_username = 'appveyor-ci'
  136. irc_nick = irc_username
  137. # establish connection
  138. irc_sock = ssl.wrap_socket(socket.socket(socket.AF_INET, socket.SOCK_STREAM))
  139. irc_sock.connect((socket.gethostbyname(server), int(port)))
  140. irc_sock.send('NICK {0}\r\nUSER {0} * 0 :{0}\r\n'.format(irc_username).encode())
  141. irc_sock.send('JOIN #{0}\r\n'.format(channel).encode())
  142. irc_file = irc_sock.makefile()
  143. while irc_file:
  144. line = irc_file.readline()
  145. print(line.rstrip())
  146. response = line.split()
  147. if response[0] == 'PING':
  148. irc_file.send('PONG {}\r\n'.format(response[1]).encode())
  149. elif response[1] == '433':
  150. irc_sock.send('NICK {}\r\n'.format(irc_nick).encode())
  151. elif response[1] == '001':
  152. time.sleep(5)
  153. # send notification
  154. for msg in messages:
  155. print(u'PRIVMSG #{} :{}'.format(channel, msg).encode("utf-8"))
  156. irc_sock.send(u'PRIVMSG #{} :{}\r\n'.format(channel, msg).encode("utf-8"))
  157. time.sleep(5)
  158. return
  159. if __name__ == '__main__':
  160. try:
  161. notify()
  162. except:
  163. import traceback
  164. print('ERROR: Failed to send notification: \n' + traceback.format_exc())