Merge pull request #285 from nico/winninjatest
[platform/upstream/ninja.git] / configure.py
1 #!/usr/bin/env python
2 #
3 # Copyright 2001 Google Inc. All Rights Reserved.
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 #     http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 """Script that generates the build.ninja for ninja itself.
18
19 Projects that use ninja themselves should either write a similar script
20 or use a meta-build system that supports Ninja output."""
21
22 from optparse import OptionParser
23 import os
24 import sys
25 sys.path.insert(0, 'misc')
26
27 import ninja_syntax
28
29 parser = OptionParser()
30 platforms = ['linux', 'freebsd', 'mingw', 'windows']
31 profilers = ['gmon', 'pprof']
32 parser.add_option('--platform',
33                   help='target platform (' + '/'.join(platforms) + ')',
34                   choices=platforms)
35 parser.add_option('--host',
36                   help='host platform (' + '/'.join(platforms) + ')',
37                   choices=platforms)
38 parser.add_option('--debug', action='store_true',
39                   help='enable debugging flags',)
40 parser.add_option('--profile', metavar='TYPE',
41                   choices=profilers,
42                   help='enable profiling (' + '/'.join(profilers) + ')',)
43 parser.add_option('--with-gtest', metavar='PATH',
44                   help='use gtest unpacked in directory PATH')
45 parser.add_option('--with-python', metavar='EXE',
46                   help='use EXE as the Python interpreter',
47                   default=os.path.basename(sys.executable))
48 (options, args) = parser.parse_args()
49 if args:
50     print 'ERROR: extra unparsed command-line arguments:', args
51     sys.exit(1)
52
53 platform = options.platform
54 if platform is None:
55     platform = sys.platform
56     if platform.startswith('linux'):
57         platform = 'linux'
58     elif platform.startswith('freebsd'):
59         platform = 'freebsd'
60     elif platform.startswith('mingw'):
61         platform = 'mingw'
62     elif platform.startswith('win'):
63         platform = 'windows'
64 host = options.host or platform
65
66 BUILD_FILENAME = 'build.ninja'
67 buildfile = open(BUILD_FILENAME, 'w')
68 n = ninja_syntax.Writer(buildfile)
69 n.comment('This file is used to build ninja itself.')
70 n.comment('It is generated by ' + os.path.basename(__file__) + '.')
71 n.newline()
72
73 n.comment('The arguments passed to configure.py, for rerunning it.')
74 n.variable('configure_args', ' '.join(sys.argv[1:]))
75 n.newline()
76
77 objext = '.o'
78 if platform == 'windows':
79     objext = '.obj'
80
81 def src(filename):
82     return os.path.join('src', filename)
83 def built(filename):
84     return os.path.join('$builddir', filename)
85 def doc(filename):
86     return os.path.join('doc', filename)
87 def cc(name, **kwargs):
88     return n.build(built(name + objext), 'cxx', src(name + '.c'), **kwargs)
89 def cxx(name, **kwargs):
90     return n.build(built(name + objext), 'cxx', src(name + '.cc'), **kwargs)
91 def binary(name):
92     if platform in ('mingw', 'windows'):
93         return name + '.exe'
94     return name
95
96 n.variable('builddir', 'build')
97 if platform == 'windows':
98     n.variable('cxx', 'cl')
99     n.variable('ar', 'link')
100 else:
101     n.variable('cxx', os.environ.get('CXX', 'g++'))
102     n.variable('ar', os.environ.get('AR', 'ar'))
103
104 if platform == 'windows':
105     cflags = ['/nologo', '/Zi', '/W4', '/WX', '/wd4530', '/wd4100', '/wd4706',
106               '/wd4512', '/wd4800', '/wd4702', '/wd4819', '/GR-',
107               '/DNOMINMAX', '/D_CRT_SECURE_NO_WARNINGS',
108               "/DNINJA_PYTHON=\"%s\"" % (options.with_python,)]
109     ldflags = ['/DEBUG', '/libpath:$builddir']
110     if not options.debug:
111         cflags += ['/Ox', '/DNDEBUG', '/GL']
112         ldflags += ['/LTCG', '/OPT:REF', '/OPT:ICF']
113 else:
114     cflags = ['-g', '-Wall', '-Wextra',
115               '-Wno-deprecated',
116               '-Wno-unused-parameter',
117               '-fno-rtti',
118               '-fno-exceptions',
119               '-fvisibility=hidden', '-pipe',
120               "'-DNINJA_PYTHON=\"%s\"'" % (options.with_python,)]
121     if options.debug:
122         cflags += ['-D_GLIBCXX_DEBUG', '-D_GLIBCXX_DEBUG_PEDANTIC']
123     else:
124         cflags += ['-O2', '-DNDEBUG']
125     ldflags = ['-L$builddir']
126 libs = []
127
128 if platform == 'mingw':
129     cflags.remove('-fvisibility=hidden');
130     ldflags.append('-static')
131 elif platform == 'sunos5':
132     cflags.remove('-fvisibility=hidden')
133 elif platform == 'windows':
134     pass
135 else:
136     if options.profile == 'gmon':
137         cflags.append('-pg')
138         ldflags.append('-pg')
139     elif options.profile == 'pprof':
140         libs.append('-lprofiler')
141
142 if 'CFLAGS' in os.environ:
143     cflags.append(os.environ['CFLAGS'])
144 n.variable('cflags', ' '.join(cflags))
145 if 'LDFLAGS' in os.environ:
146     ldflags.append(os.environ['LDFLAGS'])
147 n.variable('ldflags', ' '.join(ldflags))
148 n.newline()
149
150 if platform == 'windows':
151     n.rule('cxx',
152         command='$cxx $cflags -c $in /Fo$out',
153         depfile='$out.d',
154         description='CXX $out')
155 else:
156     n.rule('cxx',
157         command='$cxx -MMD -MT $out -MF $out.d $cflags -c $in -o $out',
158         depfile='$out.d',
159         description='CXX $out')
160 n.newline()
161
162 if host == 'windows':
163     n.rule('ar',
164            command='lib /nologo /ltcg /out:$out $in',
165            description='LIB $out')
166 elif host == 'mingw':
167     n.rule('ar',
168            command='cmd /c $ar cqs $out.tmp $in && move /Y $out.tmp $out',
169            description='AR $out')
170 else:
171     n.rule('ar',
172            command='rm -f $out && $ar crs $out $in',
173            description='AR $out')
174 n.newline()
175
176 if platform == 'windows':
177     n.rule('link',
178         command='$cxx $in $libs /nologo /link $ldflags /out:$out',
179         description='LINK $out')
180 else:
181     n.rule('link',
182         command='$cxx $ldflags -o $out $in $libs',
183         description='LINK $out')
184 n.newline()
185
186 objs = []
187
188 if platform not in ('mingw', 'windows'):
189     n.comment('browse_py.h is used to inline browse.py.')
190     n.rule('inline',
191            command='src/inline.sh $varname < $in > $out',
192            description='INLINE $out')
193     n.build(built('browse_py.h'), 'inline', src('browse.py'),
194             implicit='src/inline.sh',
195             variables=[('varname', 'kBrowsePy')])
196     n.newline()
197
198     objs += cxx('browse', order_only=built('browse_py.h'))
199     n.newline()
200
201 n.comment('the depfile parser and ninja lexers are generated using re2c.')
202 n.rule('re2c',
203        command='re2c -b -i --no-generation-date -o $out $in',
204        description='RE2C $out')
205 # Generate the .cc files in the source directory so we can check them in.
206 n.build(src('depfile_parser.cc'), 're2c', src('depfile_parser.in.cc'))
207 n.build(src('lexer.cc'), 're2c', src('lexer.in.cc'))
208 n.newline()
209
210 n.comment('Core source files all build into ninja library.')
211 for name in ['build',
212              'build_log',
213              'clean',
214              'depfile_parser',
215              'disk_interface',
216              'edit_distance',
217              'eval_env',
218              'explain',
219              'graph',
220              'graphviz',
221              'lexer',
222              'metrics',
223              'parsers',
224              'state',
225              'util']:
226     objs += cxx(name)
227 if platform == 'mingw' or platform == 'windows':
228     objs += cxx('subprocess-win32')
229     objs += cc('getopt')
230 else:
231     objs += cxx('subprocess')
232 if platform == 'windows':
233     ninja_lib = n.build(built('ninja.lib'), 'ar', objs)
234 else:
235     ninja_lib = n.build(built('libninja.a'), 'ar', objs)
236 n.newline()
237
238 if platform == 'windows':
239     libs.append('ninja.lib')
240 else:
241     libs.append('-lninja')
242
243 all_targets = []
244
245 n.comment('Main executable is library plus main() function.')
246 objs = cxx('ninja')
247 ninja = n.build(binary('ninja'), 'link', objs, implicit=ninja_lib,
248                 variables=[('libs', libs)])
249 if ninja != 'ninja':
250   n.build('ninja', 'phony', ninja)
251 n.newline()
252 all_targets += ninja
253
254 n.comment('Tests all build into ninja_test executable.')
255
256 variables = []
257 test_cflags = None
258 test_ldflags = None
259 test_libs = libs
260 objs = []
261 if options.with_gtest:
262     path = options.with_gtest
263
264     gtest_all_incs = '-I%s -I%s' % (path, os.path.join(path, 'include'))
265     if platform == 'windows':
266         gtest_cflags = '/nologo /EHsc ' + gtest_all_incs
267     else:
268         gtest_cflags = '-fvisibility=hidden ' + gtest_all_incs
269     objs += n.build(built('gtest-all' + objext), 'cxx',
270                     os.path.join(path, 'src/gtest-all.cc'),
271                     variables=[('cflags', gtest_cflags)])
272     objs += n.build(built('gtest_main' + objext), 'cxx',
273                     os.path.join(path, 'src/gtest_main.cc'),
274                     variables=[('cflags', gtest_cflags)])
275
276     test_cflags = cflags + ['-DGTEST_HAS_RTTI=0',
277                             '-I%s' % os.path.join(path, 'include')]
278 elif platform == 'windows':
279     test_libs.extend(['gtest_main.lib', 'gtest.lib'])
280 else:
281     test_libs.extend(['-lgtest_main', '-lgtest'])
282
283 for name in ['build_log_test',
284              'build_test',
285              'clean_test',
286              'depfile_parser_test',
287              'disk_interface_test',
288              'edit_distance_test',
289              'graph_test',
290              'lexer_test',
291              'parsers_test',
292              'state_test',
293              'subprocess_test',
294              'test',
295              'util_test']:
296     objs += cxx(name, variables=[('cflags', test_cflags)])
297
298 if platform != 'mingw' and platform != 'windows':
299     test_libs.append('-lpthread')
300 ninja_test = n.build(binary('ninja_test'), 'link', objs, implicit=ninja_lib,
301                      variables=[('ldflags', test_ldflags),
302                                 ('libs', test_libs)])
303 if ninja_test != 'ninja_test':
304   n.build('ninja_test', 'phony', ninja_test)
305 n.newline()
306 all_targets += ninja_test
307
308
309 n.comment('Perftest executable.')
310 objs = cxx('parser_perftest')
311 parser_perftest = n.build(binary('parser_perftest'), 'link', objs,
312                           implicit=ninja_lib,
313                           variables=[('libs', '-L$builddir -lninja')])
314 n.newline()
315 all_targets += parser_perftest
316
317 n.comment('Generate a graph using the "graph" tool.')
318 n.rule('gendot',
319        command='./ninja -t graph > $out')
320 n.rule('gengraph',
321        command='dot -Tpng $in > $out')
322 dot = n.build(built('graph.dot'), 'gendot', ['ninja', 'build.ninja'])
323 n.build('graph.png', 'gengraph', dot)
324 n.newline()
325
326 n.comment('Generate the manual using asciidoc.')
327 n.rule('asciidoc',
328        command='asciidoc -a toc -a max-width=45em -o $out $in',
329        description='ASCIIDOC $in')
330 manual = n.build(doc('manual.html'), 'asciidoc', doc('manual.asciidoc'))
331 n.build('manual', 'phony',
332         order_only=manual)
333 n.newline()
334
335 n.comment('Generate Doxygen.')
336 n.rule('doxygen',
337        command='doxygen $in',
338        description='DOXYGEN $in')
339 n.variable('doxygen_mainpage_generator',
340            src('gen_doxygen_mainpage.sh'))
341 n.rule('doxygen_mainpage',
342        command='$doxygen_mainpage_generator $in > $out',
343        description='DOXYGEN_MAINPAGE $out')
344 mainpage = n.build(built('doxygen_mainpage'), 'doxygen_mainpage',
345                    ['README', 'HACKING', 'COPYING'],
346                    implicit=['$doxygen_mainpage_generator'])
347 n.build('doxygen', 'doxygen', doc('doxygen.config'),
348         implicit=mainpage)
349 n.newline()
350
351 if host != 'mingw':
352     n.comment('Regenerate build files if build script changes.')
353     n.rule('configure',
354            command=options.with_python + ' configure.py $configure_args',
355            generator=True)
356     n.build('build.ninja', 'configure',
357             implicit=['configure.py', 'misc/ninja_syntax.py'])
358     n.newline()
359
360 n.comment('Build only the main binary by default.')
361 n.default(ninja)
362 n.newline()
363
364 n.build('all', 'phony', all_targets)
365
366 print 'wrote %s.' % BUILD_FILENAME