forked from buildbot/buildbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
github.py
222 lines (187 loc) · 8.35 KB
/
github.py
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
# This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
import re
from twisted.internet import defer
from twisted.python import log
from buildbot.process.properties import Interpolate
from buildbot.process.properties import Properties
from buildbot.process.results import CANCELLED
from buildbot.process.results import EXCEPTION
from buildbot.process.results import FAILURE
from buildbot.process.results import RETRY
from buildbot.process.results import SKIPPED
from buildbot.process.results import SUCCESS
from buildbot.process.results import WARNINGS
from buildbot.reporters import http
from buildbot.util import httpclientservice
from buildbot.util.giturlparse import giturlparse
HOSTED_BASE_URL = 'https://api.github.com'
class GitHubStatusPush(http.HttpStatusPushBase):
name = "GitHubStatusPush"
neededDetails = dict(wantProperties=True)
@defer.inlineCallbacks
def reconfigService(self, token,
startDescription=None, endDescription=None,
context=None, baseURL=None, verbose=False, **kwargs):
token = yield self.renderSecrets(token)
yield super().reconfigService(**kwargs)
self.setDefaults(context, startDescription, endDescription)
if baseURL is None:
baseURL = HOSTED_BASE_URL
if baseURL.endswith('/'):
baseURL = baseURL[:-1]
self._http = yield httpclientservice.HTTPClientService.getService(
self.master, baseURL, headers={
'Authorization': 'token ' + token,
'User-Agent': 'Buildbot'
},
debug=self.debug, verify=self.verify)
self.verbose = verbose
def setDefaults(self, context, startDescription, endDescription):
self.context = context or Interpolate('buildbot/%(prop:buildername)s')
self.startDescription = startDescription or 'Build started.'
self.endDescription = endDescription or 'Build done.'
def createStatus(self,
repo_user, repo_name, sha, state, target_url=None,
context=None, issue=None, description=None):
"""
:param repo_user: GitHub user or organization
:param repo_name: Name of the repository
:param sha: Full sha to create the status for.
:param state: one of the following 'pending', 'success', 'error'
or 'failure'.
:param target_url: Target url to associate with this status.
:param description: Short description of the status.
:param context: Build context
:return: A deferred with the result from GitHub.
This code comes from txgithub by @tomprince.
txgithub is based on twisted's webclient agent, which is much less reliable and featureful
as txrequest (support for proxy, connection pool, keep alive, retry, etc)
"""
payload = {'state': state}
if description is not None:
payload['description'] = description
if target_url is not None:
payload['target_url'] = target_url
if context is not None:
payload['context'] = context
return self._http.post(
'/'.join(['/repos', repo_user, repo_name, 'statuses', sha]),
json=payload)
@defer.inlineCallbacks
def send(self, build):
props = Properties.fromDict(build['properties'])
props.master = self.master
if build['complete']:
state = {
SUCCESS: 'success',
WARNINGS: 'success',
FAILURE: 'failure',
SKIPPED: 'success',
EXCEPTION: 'error',
RETRY: 'pending',
CANCELLED: 'error'
}.get(build['results'], 'error')
description = yield props.render(self.endDescription)
elif self.startDescription:
state = 'pending'
description = yield props.render(self.startDescription)
else:
return
context = yield props.render(self.context)
sourcestamps = build['buildset'].get('sourcestamps')
if not sourcestamps or not sourcestamps[0]:
return
project = sourcestamps[0]['project']
branch = props['branch']
m = re.search(r"refs/pull/([0-9]*)/merge", branch)
if m:
issue = m.group(1)
else:
issue = None
if "/" in project:
repoOwner, repoName = project.split('/')
else:
giturl = giturlparse(sourcestamps[0]['repository'])
repoOwner = giturl.owner
repoName = giturl.repo
if self.verbose:
log.msg("Updating github status: repoOwner={repoOwner}, repoName={repoName}".format(
repoOwner=repoOwner, repoName=repoName))
for sourcestamp in sourcestamps:
sha = sourcestamp['revision']
response = None
try:
repo_user = repoOwner
repo_name = repoName
target_url = build['url']
response = yield self.createStatus(
repo_user=repo_user,
repo_name=repo_name,
sha=sha,
state=state,
target_url=target_url,
context=context,
issue=issue,
description=description
)
if not self.isStatus2XX(response.code):
raise Exception()
if self.verbose:
log.msg(
'Updated status with "{state}" for {repoOwner}/{repoName} '
'at {sha}, context "{context}", issue {issue}.'.format(
state=state, repoOwner=repoOwner, repoName=repoName,
sha=sha, issue=issue, context=context))
except Exception as e:
if response:
content = yield response.content()
code = response.code
else:
content = code = "n/a"
log.err(
e,
'Failed to update "{state}" for {repoOwner}/{repoName} '
'at {sha}, context "{context}", issue {issue}. '
'http {code}, {content}'.format(
state=state, repoOwner=repoOwner, repoName=repoName,
sha=sha, issue=issue, context=context,
code=code, content=content))
class GitHubCommentPush(GitHubStatusPush):
name = "GitHubCommentPush"
neededDetails = dict(wantProperties=True)
def setDefaults(self, context, startDescription, endDescription):
self.context = ''
self.startDescription = startDescription
self.endDescription = endDescription or 'Build done.'
def createStatus(self,
repo_user, repo_name, sha, state, target_url=None,
context=None, issue=None, description=None):
"""
:param repo_user: GitHub user or organization
:param repo_name: Name of the repository
:param issue: Pull request number
:param state: one of the following 'pending', 'success', 'error'
or 'failure'.
:param description: Short description of the status.
:return: A deferred with the result from GitHub.
This code comes from txgithub by @tomprince.
txgithub is based on twisted's webclient agent, which is much less reliable and featureful
as txrequest (support for proxy, connection pool, keep alive, retry, etc)
"""
payload = {'body': description}
return self._http.post(
'/'.join(['/repos', repo_user, repo_name, 'issues', issue, 'comments']),
json=payload)