Make sync-commits.py robust against missing Subversion authors and missing parent...
[WebKit-https.git] / Websites / perf.webkit.org / tools / util.py
1 import json
2 import sys
3 import urllib2
4
5
6 def submit_commits(commits, dashboard_url, slave_name, slave_password, status_to_accept=['OK']):
7     try:
8         payload = json.dumps({
9             'slaveName': slave_name,
10             'slavePassword': slave_password,
11             'commits': commits,
12         })
13         request = urllib2.Request(dashboard_url + '/api/report-commits')
14         request.add_header('Content-Type', 'application/json')
15         request.add_header('Content-Length', len(payload))
16
17         output = urllib2.urlopen(request, payload).read()
18         try:
19             result = json.loads(output)
20         except Exception, error:
21             raise Exception(error, output)
22
23         if result.get('status') not in status_to_accept:
24             raise Exception(result)
25         return result
26     except Exception as error:
27         sys.exit('Failed to submit commits: %s' % str(error))
28
29
30 def text_content(element):
31     text = ''
32     for child in element.childNodes:
33         if child.nodeType == child.TEXT_NODE:
34             text += child.data
35         else:
36             text += text_content(child)
37     return text
38
39
40 HTTP_AUTH_HANDLERS = {
41     'basic': urllib2.HTTPBasicAuthHandler,
42     'digest': urllib2.HTTPDigestAuthHandler,
43 }
44
45
46 def setup_auth(server):
47     auth = server.get('auth')
48     if not auth:
49         return
50
51     password_manager = urllib2.HTTPPasswordMgr()
52     password_manager.add_password(realm=auth['realm'], uri=server['url'], user=auth['username'], passwd=auth['password'])
53     auth_handler = HTTP_AUTH_HANDLERS[auth['type']](password_manager)
54     urllib2.install_opener(urllib2.build_opener(auth_handler))
55
56
57 def load_server_config(json_path):
58     with open(json_path) as server_config_json:
59         server_config = json.load(server_config_json)
60         server = server_config['server']
61         server['url'] = server['scheme'] + '://' + server['host'] + ':' + str(server['port'])
62         setup_auth(server)
63         return server_config