Debian Codegraph @

test/tools/merge_coveralls.py

raw
1 #!/usr/bin/env python3
2
3 from __future__ import print_function
4
5 import argparse
6 import json
7 import os
8 import sys
9 import codecs
10
11 import requests
12
13 # Python 2/3 compatibility
14 if sys.version_info.major > 2:
15 xrange = range
16
17 # install path to repository mapping
18 # if path mapped to None, it means that the file should be ignored (i.e. test file/helper)
19 # first matched path counts.
20 # terminating slash should be added for directories
21 path_mapping = [
22 ("${install-dir}/share/rspamd/lib/fun.lua", None),
23 ("${install-dir}/share/rspamd/lib/", "lualib/"),
24 ("${install-dir}/share/rspamd/rules/" , "rules/"),
25 ("${install-dir}/share/rspamd/lib/torch/" , None),
26 ("${build-dir}/CMakeFiles/", None),
27 ("${build-dir}/contrib/", None),
28 ("${build-dir}/test", None),
29 ("${project-root}/test/lua/", None),
30 ("${project-root}/test/", None),
31 ("${project-root}/clang-plugin/", None),
32 ("${project-root}/CMakeFiles/", None),
33 ("${project-root}/contrib/", None),
34 ("${project-root}/", ""),
35 ("contrib/", None),
36 ("CMakeFiles/", None),
37 ]
38
39 parser = argparse.ArgumentParser(description='')
40 parser.add_argument('--input', nargs='+', help='input files')
41 parser.add_argument('--output', help='output file)')
42 parser.add_argument('--root', default="/rspamd/src/github.com/rspamd/rspamd", help='repository root)')
43 parser.add_argument('--install-dir', default="/rspamd/install", help='install root)')
44 parser.add_argument('--build-dir', default="/rspamd/build", help='build root)')
45 parser.add_argument('--token', help='If present, the file will be uploaded to coveralls)')
46 parser.add_argument('--parallel', action='store_true', help='If present, this is a parallel build)')
47 parser.add_argument('--parallel-close', action='store_true', help='If present, close parallel build and exit)')
48
49
50 def merge_coverage_vectors(c1, c2):
51 assert(len(c1) == len(c2))
52
53 for i in range(0, len(c1)):
54 if c1[i] is None and c2[i] is None:
55 pass
56 elif type(c1[i]) is int and c2[i] is None:
57 pass
58 elif c1[i] is None and type(c2[i]) is int:
59 c1[i] = c2[i]
60 elif type(c1[i]) is int and type(c2[i]) is int:
61 c1[i] += c2[i]
62 else:
63 raise RuntimeError("bad element types at %d: %s, %s", i, type(c1[i]), type(c1[i]))
64
65 return c1
66
67
68 def normalize_name(name):
69 name = os.path.normpath(name)
70 if not os.path.isabs(name):
71 name = os.path.abspath(repository_root + "/" + name)
72 for k in path_mapping:
73 if name.startswith(k[0]):
74 if k[1] is None:
75 return None
76 else:
77 name = k[1] + name[len(k[0]):]
78 break
79 return name
80
81 def merge(files, j1):
82 for sf in j1['source_files']:
83 name = normalize_name(sf['name'])
84 if name is None:
85 continue
86 if name in files:
87 files[name]['coverage'] = merge_coverage_vectors(files[name]['coverage'], sf['coverage'])
88 else:
89 sf['name'] = name
90 files[name] = sf
91
92 return files
93
94 def prepare_path_mapping():
95 for i in range(0, len(path_mapping)):
96 new_key = path_mapping[i][0].replace("${install-dir}", install_dir)
97 new_key = new_key.replace("${project-root}", repository_root)
98 new_key = new_key.replace("${build-dir}", build_dir)
99
100 path_mapping[i] = (new_key, path_mapping[i][1])
101
102 def close_parallel_build():
103 j = {'payload':{'status': 'done'}}
104 j['payload']['build_num'] = os.getenv('DRONE_BUILD_NUMBER')
105 query_str = {'repo_token': args.token}
106 try:
107 r = requests.post('https://coveralls.io/webhook', params=query_str, json=j)
108 r.raise_for_status()
109 except requests.exceptions.RequestException as e:
110 print("Failed to send data to coveralls: %s" % e)
111 sys.exit()
112
113 try:
114 response = r.json()
115 if 'url' in response:
116 print("[coveralls] URL %s" % response['url'])
117 if 'error' in response:
118 print("[coveralls] ERROR: %s" % response['error'])
119 except json.decoder.JSONDecodeError:
120 print("Bad response: '%s'" % r.text)
121
122 if __name__ == '__main__':
123 args = parser.parse_args()
124
125 if args.parallel_close:
126 close_parallel_build()
127 sys.exit(0)
128
129 if not args.input:
130 print("error: the following arguments are required: --input")
131 sys.exit(1)
132
133 repository_root = os.path.abspath(os.path.expanduser(args.root))
134 install_dir = os.path.normpath(os.path.expanduser(args.install_dir))
135 build_dir = os.path.normpath(os.path.expanduser(args.build_dir))
136
137 prepare_path_mapping()
138
139 with codecs.open(args.input[0], 'r', encoding='utf-8') as fh:
140 j1 = json.load(fh)
141
142 files = merge({}, j1)
143 for i in range(1, len(args.input)):
144 with codecs.open(args.input[i], 'r', encoding='utf-8') as fh:
145 j2 = json.load(fh)
146
147 files = merge(files, j2)
148
149 if 'git' not in j1 and 'git' in j2:
150 j1['git'] = j2['git']
151 if 'service_name' not in j1 and 'service_name' in j2:
152 j1['service_name'] = j2['service_name']
153 if 'service_job_id' not in j1 and 'service_job_id' in j2:
154 j1['service_job_id'] = j2['service_job_id']
155
156 if args.parallel:
157 j1['parallel'] = True
158
159 if os.getenv('CIRCLECI'):
160 j1['service_name'] = 'circleci'
161 j1['service_job_id'] = os.getenv('CIRCLE_BUILD_NUM')
162 elif os.getenv('DRONE') == 'true':
163 j1['service_name'] = 'drone'
164 j1['service_branch'] = os.getenv('DRONE_COMMIT_BRANCH')
165 j1['service_build_url'] = os.getenv('DRONE_BUILD_LINK')
166 j1['service_number'] = os.getenv('DRONE_BUILD_NUMBER')
167 j1['commit_sha'] = os.getenv('DRONE_COMMIT_SHA')
168 if os.getenv('DRONE_BUILD_EVENT') == 'pull_request':
169 j1['service_pull_request'] = os.getenv('DRONE_PULL_REQUEST')
170 # git data can be filled by cpp-coveralls, but in our layout it can't find repo
171 # so we can override git info witout merging
172 j1['git'] = {
173 'head': {
174 'id': j1['commit_sha'],
175 'author_email': os.getenv('DRONE_COMMIT_AUTHOR_EMAIL'),
176 'message': os.getenv('DRONE_COMMIT_MESSAGE')
177 },
178 'branch': j1['service_branch'],
179 'remotes': [{
180 'name': 'origin',
181 'url': os.getenv('DRONE_GIT_HTTP_URL')
182 }]
183 }
184
185
186 j1['source_files'] = list(files.values())
187
188 if args.output:
189 with open(args.output, 'w') as f:
190 f.write(json.dumps(j1))
191
192 if args.token:
193 j1['repo_token'] = args.token
194 try:
195 r = requests.post('https://coveralls.io/api/v1/jobs', files={"json_file": json.dumps(j1)})
196 r.raise_for_status()
197 except requests.exceptions.RequestException as e:
198 print("Failed to send data to coveralls: %s" % e)
199 sys.exit()
200
201 try:
202 response = r.json()
203 print("[coveralls] %s" % response['message'])
204 if 'url' in response:
205 print("[coveralls] Uploaded to %s" % response['url'])
206 except json.decoder.JSONDecodeError:
207 print("Bad response: '%s'" % r.text)