batchbuild.py 11.2 KB
Newer Older
Christopher Dunn's avatar
simple    
Christopher Dunn committed
1
from __future__ import print_function
Christopher Dunn's avatar
ws    
Christopher Dunn committed
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import collections
import itertools
import json
import os
import os.path
import re
import shutil
import string
import subprocess
import sys
import cgi

class BuildDesc:
    def __init__(self, prepend_envs=None, variables=None, build_type=None, generator=None):
        self.prepend_envs = prepend_envs or [] # [ { "var": "value" } ]
        self.variables = variables or []
        self.build_type = build_type
        self.generator = generator

21
    def merged_with(self, build_desc):
Christopher Dunn's avatar
ws    
Christopher Dunn committed
22
23
24
        """Returns a new BuildDesc by merging field content.
           Prefer build_desc fields to self fields for single valued field.
        """
25
        return BuildDesc(self.prepend_envs + build_desc.prepend_envs,
Christopher Dunn's avatar
ws    
Christopher Dunn committed
26
27
                          self.variables + build_desc.variables,
                          build_desc.build_type or self.build_type,
28
                          build_desc.generator or self.generator)
Christopher Dunn's avatar
ws    
Christopher Dunn committed
29

30
    def env(self):
Christopher Dunn's avatar
ws    
Christopher Dunn committed
31
32
        environ = os.environ.copy()
        for values_by_name in self.prepend_envs:
Christopher Dunn's avatar
simple    
Christopher Dunn committed
33
            for var, value in list(values_by_name.items()):
Christopher Dunn's avatar
ws    
Christopher Dunn committed
34
35
                var = var.upper()
                if type(value) is unicode:
36
                    value = value.encode(sys.getdefaultencoding())
Christopher Dunn's avatar
ws    
Christopher Dunn committed
37
38
39
40
41
42
                if var in environ:
                    environ[var] = value + os.pathsep + environ[var]
                else:
                    environ[var] = value
        return environ

43
    def cmake_args(self):
Christopher Dunn's avatar
ws    
Christopher Dunn committed
44
45
46
        args = ["-D%s" % var for var in self.variables]
        # skip build type for Visual Studio solution as it cause warning
        if self.build_type and 'Visual' not in self.generator:
47
            args.append("-DCMAKE_BUILD_TYPE=%s" % self.build_type)
Christopher Dunn's avatar
ws    
Christopher Dunn committed
48
        if self.generator:
49
            args.extend(['-G', self.generator])
Christopher Dunn's avatar
ws    
Christopher Dunn committed
50
51
        return args

52
53
    def __repr__(self):
        return "BuildDesc(%s, build_type=%s)" %  (" ".join(self.cmake_args()), self.build_type)
Christopher Dunn's avatar
ws    
Christopher Dunn committed
54
55

class BuildData:
56
    def __init__(self, desc, work_dir, source_dir):
Christopher Dunn's avatar
ws    
Christopher Dunn committed
57
58
59
        self.desc = desc
        self.work_dir = work_dir
        self.source_dir = source_dir
60
61
        self.cmake_log_path = os.path.join(work_dir, 'batchbuild_cmake.log')
        self.build_log_path = os.path.join(work_dir, 'batchbuild_build.log')
Christopher Dunn's avatar
ws    
Christopher Dunn committed
62
63
64
65
        self.cmake_succeeded = False
        self.build_succeeded = False

    def execute_build(self):
Christopher Dunn's avatar
simple    
Christopher Dunn committed
66
        print('Build %s' % self.desc)
67
68
        self._make_new_work_dir()
        self.cmake_succeeded = self._generate_makefiles()
Christopher Dunn's avatar
ws    
Christopher Dunn committed
69
        if self.cmake_succeeded:
70
            self.build_succeeded = self._build_using_makefiles()
Christopher Dunn's avatar
ws    
Christopher Dunn committed
71
72
73
        return self.build_succeeded

    def _generate_makefiles(self):
Christopher Dunn's avatar
simple    
Christopher Dunn committed
74
        print('  Generating makefiles: ', end=' ')
75
76
        cmd = ['cmake'] + self.desc.cmake_args() + [os.path.abspath(self.source_dir)]
        succeeded = self._execute_build_subprocess(cmd, self.desc.env(), self.cmake_log_path)
Christopher Dunn's avatar
simple    
Christopher Dunn committed
77
        print('done' if succeeded else 'FAILED')
Christopher Dunn's avatar
ws    
Christopher Dunn committed
78
79
80
        return succeeded

    def _build_using_makefiles(self):
Christopher Dunn's avatar
simple    
Christopher Dunn committed
81
        print('  Building:', end=' ')
Christopher Dunn's avatar
ws    
Christopher Dunn committed
82
83
84
        cmd = ['cmake', '--build', self.work_dir]
        if self.desc.build_type:
            cmd += ['--config', self.desc.build_type]
85
        succeeded = self._execute_build_subprocess(cmd, self.desc.env(), self.build_log_path)
Christopher Dunn's avatar
simple    
Christopher Dunn committed
86
        print('done' if succeeded else 'FAILED')
Christopher Dunn's avatar
ws    
Christopher Dunn committed
87
88
89
        return succeeded

    def _execute_build_subprocess(self, cmd, env, log_path):
90
91
92
        process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=self.work_dir,
                                    env=env)
        stdout, _ = process.communicate()
Christopher Dunn's avatar
ws    
Christopher Dunn committed
93
        succeeded = (process.returncode == 0)
94
95
96
        with open(log_path, 'wb') as flog:
            log = ' '.join(cmd) + '\n' + stdout + '\nExit code: %r\n' % process.returncode
            flog.write(fix_eol(log))
Christopher Dunn's avatar
ws    
Christopher Dunn committed
97
98
99
        return succeeded

    def _make_new_work_dir(self):
100
        if os.path.isdir(self.work_dir):
Christopher Dunn's avatar
simple    
Christopher Dunn committed
101
            print('  Removing work directory', self.work_dir)
102
103
104
            shutil.rmtree(self.work_dir, ignore_errors=True)
        if not os.path.isdir(self.work_dir):
            os.makedirs(self.work_dir)
Christopher Dunn's avatar
ws    
Christopher Dunn committed
105

106
def fix_eol(stdout):
Christopher Dunn's avatar
ws    
Christopher Dunn committed
107
108
    """Fixes wrong EOL produced by cmake --build on Windows (\r\r\n instead of \r\n).
    """
109
    return re.sub('\r*\n', os.linesep, stdout)
Christopher Dunn's avatar
ws    
Christopher Dunn committed
110

111
112
113
def load_build_variants_from_config(config_path):
    with open(config_path, 'rb') as fconfig:
        data = json.load(fconfig)
Christopher Dunn's avatar
ws    
Christopher Dunn committed
114
    variants = data[ 'cmake_variants' ]
115
    build_descs_by_axis = collections.defaultdict(list)
Christopher Dunn's avatar
ws    
Christopher Dunn committed
116
117
118
119
120
121
    for axis in variants:
        axis_name = axis["name"]
        build_descs = []
        if "generators" in axis:
            for generator_data in axis["generators"]:
                for generator in generator_data["generator"]:
122
123
124
                    build_desc = BuildDesc(generator=generator,
                                            prepend_envs=generator_data.get("env_prepend"))
                    build_descs.append(build_desc)
Christopher Dunn's avatar
ws    
Christopher Dunn committed
125
126
        elif "variables" in axis:
            for variables in axis["variables"]:
127
128
                build_desc = BuildDesc(variables=variables)
                build_descs.append(build_desc)
Christopher Dunn's avatar
ws    
Christopher Dunn committed
129
130
        elif "build_types" in axis:
            for build_type in axis["build_types"]:
131
132
133
                build_desc = BuildDesc(build_type=build_type)
                build_descs.append(build_desc)
        build_descs_by_axis[axis_name].extend(build_descs)
Christopher Dunn's avatar
ws    
Christopher Dunn committed
134
135
    return build_descs_by_axis

136
def generate_build_variants(build_descs_by_axis):
Christopher Dunn's avatar
ws    
Christopher Dunn committed
137
    """Returns a list of BuildDesc generated for the partial BuildDesc for each axis."""
Christopher Dunn's avatar
simple    
Christopher Dunn committed
138
    axis_names = list(build_descs_by_axis.keys())
Christopher Dunn's avatar
ws    
Christopher Dunn committed
139
    build_descs = []
Christopher Dunn's avatar
simple    
Christopher Dunn committed
140
    for axis_name, axis_build_descs in list(build_descs_by_axis.items()):
Christopher Dunn's avatar
ws    
Christopher Dunn committed
141
142
143
        if len(build_descs):
            # for each existing build_desc and each axis build desc, create a new build_desc
            new_build_descs = []
144
145
            for prototype_build_desc, axis_build_desc in itertools.product(build_descs, axis_build_descs):
                new_build_descs.append(prototype_build_desc.merged_with(axis_build_desc))
Christopher Dunn's avatar
ws    
Christopher Dunn committed
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
            build_descs = new_build_descs
        else:
            build_descs = axis_build_descs
    return build_descs

HTML_TEMPLATE = string.Template('''<html>
<head>
    <title>$title</title>
    <style type="text/css">
    td.failed {background-color:#f08080;}
    td.ok {background-color:#c0eec0;}
    </style>
</head>
<body>
<table border="1">
<thead>
    <tr>
        <th>Variables</th>
        $th_vars
    </tr>
    <tr>
        <th>Build type</th>
        $th_build_types
    </tr>
</thead>
<tbody>
$tr_builds
</tbody>
</table>
</body></html>''')

177
178
def generate_html_report(html_report_path, builds):
    report_dir = os.path.dirname(html_report_path)
Christopher Dunn's avatar
ws    
Christopher Dunn committed
179
180
    # Vertical axis: generator
    # Horizontal: variables, then build_type
181
    builds_by_generator = collections.defaultdict(list)
Christopher Dunn's avatar
ws    
Christopher Dunn committed
182
    variables = set()
183
    build_types_by_variable = collections.defaultdict(set)
Christopher Dunn's avatar
ws    
Christopher Dunn committed
184
185
    build_by_pos_key = {} # { (generator, var_key, build_type): build }
    for build in builds:
186
        builds_by_generator[build.desc.generator].append(build)
Christopher Dunn's avatar
ws    
Christopher Dunn committed
187
        var_key = tuple(sorted(build.desc.variables))
188
189
        variables.add(var_key)
        build_types_by_variable[var_key].add(build.desc.build_type)
Christopher Dunn's avatar
ws    
Christopher Dunn committed
190
191
        pos_key = (build.desc.generator, var_key, build.desc.build_type)
        build_by_pos_key[pos_key] = build
192
    variables = sorted(variables)
Christopher Dunn's avatar
ws    
Christopher Dunn committed
193
194
195
    th_vars = []
    th_build_types = []
    for variable in variables:
196
        build_types = sorted(build_types_by_variable[variable])
Christopher Dunn's avatar
ws    
Christopher Dunn committed
197
        nb_build_type = len(build_types_by_variable[variable])
198
        th_vars.append('<th colspan="%d">%s</th>' % (nb_build_type, cgi.escape(' '.join(variable))))
Christopher Dunn's avatar
ws    
Christopher Dunn committed
199
        for build_type in build_types:
200
            th_build_types.append('<th>%s</th>' % cgi.escape(build_type))
Christopher Dunn's avatar
ws    
Christopher Dunn committed
201
    tr_builds = []
202
203
    for generator in sorted(builds_by_generator):
        tds = [ '<td>%s</td>\n' % cgi.escape(generator) ]
Christopher Dunn's avatar
ws    
Christopher Dunn committed
204
        for variable in variables:
205
            build_types = sorted(build_types_by_variable[variable])
Christopher Dunn's avatar
ws    
Christopher Dunn committed
206
207
208
209
210
211
            for build_type in build_types:
                pos_key = (generator, variable, build_type)
                build = build_by_pos_key.get(pos_key)
                if build:
                    cmake_status = 'ok' if build.cmake_succeeded else 'FAILED'
                    build_status = 'ok' if build.build_succeeded else 'FAILED'
212
213
214
                    cmake_log_url = os.path.relpath(build.cmake_log_path, report_dir)
                    build_log_url = os.path.relpath(build.build_log_path, report_dir)
                    td = '<td class="%s"><a href="%s" class="%s">CMake: %s</a>' % (                        build_status.lower(), cmake_log_url, cmake_status.lower(), cmake_status)
Christopher Dunn's avatar
ws    
Christopher Dunn committed
215
                    if build.cmake_succeeded:
216
                        td += '<br><a href="%s" class="%s">Build: %s</a>' % (                            build_log_url, build_status.lower(), build_status)
Christopher Dunn's avatar
ws    
Christopher Dunn committed
217
218
219
                    td += '</td>'
                else:
                    td = '<td></td>'
220
221
222
                tds.append(td)
        tr_builds.append('<tr>%s</tr>' % '\n'.join(tds))
    html = HTML_TEMPLATE.substitute(        title='Batch build report',
Christopher Dunn's avatar
ws    
Christopher Dunn committed
223
        th_vars=' '.join(th_vars),
224
225
226
227
        th_build_types=' '.join(th_build_types),
        tr_builds='\n'.join(tr_builds))
    with open(html_report_path, 'wt') as fhtml:
        fhtml.write(html)
Christopher Dunn's avatar
simple    
Christopher Dunn committed
228
    print('HTML report generated in:', html_report_path)
Christopher Dunn's avatar
ws    
Christopher Dunn committed
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245

def main():
    usage = r"""%prog WORK_DIR SOURCE_DIR CONFIG_JSON_PATH [CONFIG2_JSON_PATH...]
Build a given CMake based project located in SOURCE_DIR with multiple generators/options.dry_run
as described in CONFIG_JSON_PATH building in WORK_DIR.

Example of call:
python devtools\batchbuild.py e:\buildbots\jsoncpp\build . devtools\agent_vmw7.json
"""
    from optparse import OptionParser
    parser = OptionParser(usage=usage)
    parser.allow_interspersed_args = True
#    parser.add_option('-v', '--verbose', dest="verbose", action='store_true',
#        help="""Be verbose.""")
    parser.enable_interspersed_args()
    options, args = parser.parse_args()
    if len(args) < 3:
246
        parser.error("Missing one of WORK_DIR SOURCE_DIR CONFIG_JSON_PATH.")
Christopher Dunn's avatar
ws    
Christopher Dunn committed
247
248
249
250
    work_dir = args[0]
    source_dir = args[1].rstrip('/\\')
    config_paths = args[2:]
    for config_path in config_paths:
251
252
        if not os.path.isfile(config_path):
            parser.error("Can not read: %r" % config_path)
Christopher Dunn's avatar
ws    
Christopher Dunn committed
253
254
255
256

    # generate build variants
    build_descs = []
    for config_path in config_paths:
257
258
        build_descs_by_axis = load_build_variants_from_config(config_path)
        build_descs.extend(generate_build_variants(build_descs_by_axis))
Christopher Dunn's avatar
simple    
Christopher Dunn committed
259
    print('Build variants (%d):' % len(build_descs))
Christopher Dunn's avatar
ws    
Christopher Dunn committed
260
    # assign build directory for each variant
261
262
    if not os.path.isdir(work_dir):
        os.makedirs(work_dir)
Christopher Dunn's avatar
ws    
Christopher Dunn committed
263
    builds = []
264
265
266
267
268
    with open(os.path.join(work_dir, 'matrix-dir-map.txt'), 'wt') as fmatrixmap:
        for index, build_desc in enumerate(build_descs):
            build_desc_work_dir = os.path.join(work_dir, '%03d' % (index+1))
            builds.append(BuildData(build_desc, build_desc_work_dir, source_dir))
            fmatrixmap.write('%s: %s\n' % (build_desc_work_dir, build_desc))
Christopher Dunn's avatar
ws    
Christopher Dunn committed
269
270
    for build in builds:
        build.execute_build()
271
272
    html_report_path = os.path.join(work_dir, 'batchbuild-report.html')
    generate_html_report(html_report_path, builds)
Christopher Dunn's avatar
simple    
Christopher Dunn committed
273
    print('Done')
Christopher Dunn's avatar
ws    
Christopher Dunn committed
274
275
276
277
278


if __name__ == '__main__':
    main()