forked from psklenar/tools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub_comments.py
More file actions
executable file
·231 lines (195 loc) · 8.06 KB
/
github_comments.py
File metadata and controls
executable file
·231 lines (195 loc) · 8.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
#!/usr/bin/env python
# Author Petr Sklenar psklenar@gmail.com
# script adds comment to github pull request
# EXAMPLE:
#
# 1, store comment:
#./github_comments.py -t YOURGITHUBTOKEN -o psklenar -r tools -p 2 -a store -s 0 -c "abc" -R "Moje CI" -u https://example.org
#
# 2, store as pull request status:
# for status you have to use proper status codes `0` is success, `1` is failure, `2` is error, `3` is pending
#
#./github_comments.py -t YOURGITHUBTOKEN -o psklenar -r tools -p 2 -a store -s 0 -c "abc" -R "Moje CI" -u https://example.org -w status
#
# SEND EMAIL:
#EMAIL_FROM=user@example.com
#EMAIL_SERVER=mail.example.com
#EMAIL=user@example.com
#./github_comments.py -t YOURGITHUBTOKEN -o psklenar -r tools -p 2 -a store -s 0 -c "abc" -R "Moje CI" -u https://example.org -w email
import requests
import json
import os
import smtplib
from email.mime.text import MIMEText
import socket
import traceback
import sys
from optparse import OptionParser
state_translation = ["success", "failure", "error", "pending"] + ['failure' for x in range (255)]
def get_options():
parser = OptionParser(usage="usage: %prog [options]",
version="%prog 1.0")
parser.add_option("-p", "--pullrequest",
dest="pullRequest",
help="pull request where to write comments")
parser.add_option("-t", "--token",
action="store",
dest="token",
help="your secret token")
parser.add_option("-o", "--githubOrgName",
dest="githubOrgName",
help="name of the organization / username , for ex:\n"
"https://github.com/'STRING_NEED'.git where STRING_NEED='org_user/reponame'")
parser.add_option("-r", "--githubRepoName",
dest="githubRepoName",
help="name of the repo, for ex:\n"
"https://github.com/'STRING_NEED'.git where STRING_NEED='org_user/reponame'")
parser.add_option("-a", "--action",
dest="action",
choices=["list", "store"],
default="list",
help="show all stuff for selected pull request")
parser.add_option("-c", "--comment",
dest="comment",
default="",
help="comment it")
parser.add_option("-s", "--status",
action="store", # optional because action defaults to "store"
dest="status",
help="which state to store")
parser.add_option("-w", "--what",
dest="what",
action="append",
choices=["comment", "status", "email"],
default=[],
help="how to store result")
parser.add_option("-R", "--resulttype",
dest="type",
default="CI",
help="context of CI to change")
parser.add_option("-u", "--url",
action="store", # optional because action defaults to "store"
dest="url",
default="",
help="Result URL with reslts")
(options, args) = parser.parse_args()
if not options.token:
parser.error("Token not given")
if not options.pullRequest:
parser.error("Pull request not given")
if not options.githubOrgName:
parser.error("Org Name not given")
if not options.githubRepoName:
parser.error("Repo Name not given")
return options
# "error", "failure", "pending", "success"
class GhComment(object):
def __init__(self, token, orgname, pr, repo):
self.orgname = orgname
self.pr = pr
self.repo = repo
self.get_url = "https://api.github.com/repos/{0}/{1}/pulls/{2}".format(orgname, repo, pr)
self.auth_header = {
'Content-Type': 'application/json',
'Authorization': 'token {0}'.format(token),
}
self.post_url_type = "comments_url"
def report_url(self):
return self.get()[self.post_url_type]
def get(self):
## requests.get()
r = requests.get(self.get_url, headers=self.auth_header)
#print r.json()
return r.json()
def post(self):
#print self.report_url()
#print self.auth_header
#print json.dumps(self.data)
r = requests.post(self.report_url(), headers=self.auth_header, data=json.dumps(self.data))
#print r.request
#print r.reason
#print r.raw
if r.status_code == 201:
return True
else:
try:
raise Exception('http return code is bad', r.status_code)
except:
traceback.print_exc()
sys.exit(3)
def set_content(self, status, comment, url, type):
body = """## {context} comment
* Status: {textstatus}, return code = __{status}__
* Result url: __[{url}]({url})__
* Comment: __{comment}__
""".format(textstatus=state_translation[status], status=status, context=type, url=url, comment=comment)
data = {
'body': '{body}'.format(body=body)
}
self.data = data
class GhStatus(GhComment):
def __init__(self, *args, **kwargs):
super(GhStatus,self).__init__(*args, **kwargs)
self.post_url_type = "statuses_url"
def set_content(self, status, comment, url, type):
data = {
"state": state_translation[status],
"target_url": url,
"description": comment,
"context": type
}
self.data = data
class Email(GhComment):
def __init__(self, *args, **kwargs):
super(Email,self).__init__(*args, **kwargs)
def set_content(self, status, comment, url, type):
self.email_to = os.environ.get("EMAIL")
self.email_from = os.environ.get("EMAIL_FROM") or "root@localhost"
self.email_server = os.environ.get("EMAIL_SERVER") or "localhost"
self.subject = "Automation: {type} for {repo} - {pr}".format(type=type, repo=self.repo, pr=self.pr)
data = """
Hello,
I'm your CI.
----------------
Status: {textstatus}, return code = {status}
Result url: {url}
Comment: {comment}
See: https://github.com/{orgname}/{repo}/pull/{pr}
Enjoy!
""".format(textstatus=state_translation[status], status=status, type=type, url=url, comment=comment, orgname=self.orgname, repo=self.repo, pr=self.pr)
self.data = data
def post(self):
msg = MIMEText(self.data)
msg['Subject'] = self.subject
msg['From'] = self.email_from
msg['To'] = self.email_to
try:
server = smtplib.SMTP(self.email_server)
server.sendmail(self.email_from, [self.email_to], msg.as_string())
server.quit()
except socket.error as e:
print("{0}\n Did you specify mails variables? like EMAIL_FROM=user@example.com EMAIL_SERVER=mail.example.com EMAIL=user@example.com".format(e))
exit(1)
def main():
options=get_options()
resobj = None
for what in options.what:
if what == "comment":
print "Store to GitHub Comment"
resobj = GhComment(token=options.token, orgname=options.githubOrgName, pr=options.pullRequest,
repo=options.githubRepoName)
elif what == "status":
resobj = GhStatus(token=options.token, orgname=options.githubOrgName, pr=options.pullRequest,
repo=options.githubRepoName)
print "Store to GitHub PR Status"
elif what == "email":
resobj = Email(token=options.token, orgname=options.githubOrgName, pr=options.pullRequest,
repo=options.githubRepoName)
print "Send email"
if options.action == "list":
print "Items in PR"
else:
resobj.set_content(status=int(options.status), comment=options.comment, url=options.url, type=options.type)
resobj.post()
if __name__ == '__main__':
main()