-
Notifications
You must be signed in to change notification settings - Fork 1
/
slack_notifier.py
84 lines (69 loc) · 2.13 KB
/
slack_notifier.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
import httplib, json
import getopt, sys, os
import subprocess
def get_connection(organization):
return httplib.HTTPSConnection('%s.slack.com' % organization)
def get_url(token):
return '/services/hooks/incoming-webhook?token=%s' % token
def get_data_from_git(format_string, commit):
return subprocess.check_output(['git', 'log', '-1', '--format=format:%s' % format_string, commit])
def get_author(commit):
return get_data_from_git('%an <%ae>', commit)
def get_date(commit):
return get_data_from_git('%aD', commit)
def get_title(commit):
return get_data_from_git('%s', commit)
def get_full_message(commit):
return get_data_from_git('%b', commit)
def post_message(connection, url, success, project):
headers = {'Content-Type': 'application/json'}
build_url = os.environ['BUILD_URL']
build_number = os.environ['BUILD_NUMBER']
branch = os.environ['BRANCH']
commit = os.environ['COMMIT']
status_text = 'succeeded' if success else 'failed'
color = 'good' if success else 'danger'
text = '<%s|Build #%s> %s for project %s on branch %s' % (build_url, build_number, status_text, project, branch)
message = {
'username': 'Shippable',
'fallback': text,
'pretext': text,
'color': color,
'fields': [
{
'title': get_author(commit),
'value': get_date(commit)
},
{
'title': get_title(commit),
'value': get_full_message(commit)
}
]
}
connection.request('POST', url, json.dumps(message), headers)
response = connection.getresponse()
print response.read().decode()
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], ':sf', ['project=', 'org=', 'token='])
except getopt.GetoptError as err:
print str(err)
sys.exit(2)
success = False
project = None
organization = None
token = None
for o, arg in opts:
if o == '-s':
success = True
elif o == '--project':
project = arg
elif o == '--org':
organization = arg
elif o == '--token':
token = arg
connection = get_connection(organization)
url = get_url(token)
post_message(connection, url, success, project)
if __name__ == '__main__':
main()