Merge pull request #296 from nico/confenv
[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 extras',)
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 env_keys = set(['CXX', 'AR', 'CFLAGS', 'LDFLAGS'])
76 configure_env = dict((k, os.environ[k]) for k in os.environ if k in env_keys)
77 n.variable('configure_env',
78            ' '.join([k + '=' + configure_env[k] for k in configure_env]))
79 n.newline()
80
81 objext = '.o'
82 if platform == 'windows':
83     objext = '.obj'
84
85 def src(filename):
86     return os.path.join('src', filename)
87 def built(filename):
88     return os.path.join('$builddir', filename)
89 def doc(filename):
90     return os.path.join('doc', filename)
91 def cc(name, **kwargs):
92     return n.build(built(name + objext), 'cxx', src(name + '.c'), **kwargs)
93 def cxx(name, **kwargs):
94     return n.build(built(name + objext), 'cxx', src(name + '.cc'), **kwargs)
95 def binary(name):
96     if platform in ('mingw', 'windows'):
97         return name + '.exe'
98     return name
99
100 n.variable('builddir', 'build')
101 if platform == 'windows':
102     n.variable('cxx', 'cl')
103     n.variable('ar', 'link')
104 else:
105     n.variable('cxx', configure_env.get('CXX', 'g++'))
106     n.variable('ar', configure_env.get('AR', 'ar'))
107
108 if platform == 'windows':
109     cflags = ['/nologo', '/Zi', '/W4', '/WX', '/wd4530', '/wd4100', '/wd4706',
110               '/wd4512', '/wd4800', '/wd4702', '/wd4819', '/GR-',
111               '/DNOMINMAX', '/D_CRT_SECURE_NO_WARNINGS',
112               "/DNINJA_PYTHON=\"%s\"" % (options.with_python,)]
113     ldflags = ['/DEBUG', '/libpath:$builddir']
114     if not options.debug:
115         cflags += ['/Ox', '/DNDEBUG', '/GL']
116         ldflags += ['/LTCG', '/OPT:REF', '/OPT:ICF']
117 else:
118     cflags = ['-g', '-Wall', '-Wextra',
119               '-Wno-deprecated',
120               '-Wno-unused-parameter',
121               '-fno-rtti',
122               '-fno-exceptions',
123               '-fvisibility=hidden', '-pipe',
124               "'-DNINJA_PYTHON=\"%s\"'" % (options.with_python,)]
125     if options.debug:
126         cflags += ['-D_GLIBCXX_DEBUG', '-D_GLIBCXX_DEBUG_PEDANTIC']
127     else:
128         cflags += ['-O2', '-DNDEBUG']
129     ldflags = ['-L$builddir']
130 libs = []
131
132 if platform == 'mingw':
133     cflags.remove('-fvisibility=hidden');
134     ldflags.append('-static')
135 elif platform == 'sunos5':
136     cflags.remove('-fvisibility=hidden')
137 elif platform == 'windows':
138     pass
139 else:
140     if options.profile == 'gmon':
141         cflags.append('-pg')
142         ldflags.append('-pg')
143     elif options.profile == 'pprof':
144         libs.append('-lprofiler')
145
146 if 'CFLAGS' in configure_env:
147     cflags.append(configure_env['CFLAGS'])
148 n.variable('cflags', ' '.join(cflags))
149 if 'LDFLAGS' in configure_env:
150     ldflags.append(configure_env['LDFLAGS'])
151 n.variable('ldflags', ' '.join(ldflags))
152 n.newline()
153
154 if platform == 'windows':
155     n.rule('cxx',
156         command='$cxx $cflags -c $in /Fo$out',
157         depfile='$out.d',
158         description='CXX $out')
159 else:
160     n.rule('cxx',
161         command='$cxx -MMD -MT $out -MF $out.d $cflags -c $in -o $out',
162         depfile='$out.d',
163         description='CXX $out')
164 n.newline()
165
166 if host == 'windows':
167     n.rule('ar',
168            command='lib /nologo /ltcg /out:$out $in',
169            description='LIB $out')
170 elif host == 'mingw':
171     n.rule('ar',
172            command='cmd /c $ar cqs $out.tmp $in && move /Y $out.tmp $out',
173            description='AR $out')
174 else:
175     n.rule('ar',
176            command='rm -f $out && $ar crs $out $in',
177            description='AR $out')
178 n.newline()
179
180 if platform == 'windows':
181     n.rule('link',
182         command='$cxx $in $libs /nologo /link $ldflags /out:$out',
183         description='LINK $out')
184 else:
185     n.rule('link',
186         command='$cxx $ldflags -o $out $in $libs',
187         description='LINK $out')
188 n.newline()
189
190 objs = []
191
192 if platform not in ('mingw', 'windows'):
193     n.comment('browse_py.h is used to inline browse.py.')
194     n.rule('inline',
195            command='src/inline.sh $varname < $in > $out',
196            description='INLINE $out')
197     n.build(built('browse_py.h'), 'inline', src('browse.py'),
198             implicit='src/inline.sh',
199             variables=[('varname', 'kBrowsePy')])
200     n.newline()
201
202     objs += cxx('browse', order_only=built('browse_py.h'))
203     n.newline()
204
205 n.comment('the depfile parser and ninja lexers are generated using re2c.')
206 n.rule('re2c',
207        command='re2c -b -i --no-generation-date -o $out $in',
208        description='RE2C $out')
209 # Generate the .cc files in the source directory so we can check them in.
210 n.build(src('depfile_parser.cc'), 're2c', src('depfile_parser.in.cc'))
211 n.build(src('lexer.cc'), 're2c', src('lexer.in.cc'))
212 n.newline()
213
214 n.comment('Core source files all build into ninja library.')
215 for name in ['build',
216              'build_log',
217              'clean',
218              'depfile_parser',
219              'disk_interface',
220              'edit_distance',
221              'eval_env',
222              'explain',
223              'graph',
224              'graphviz',
225              'lexer',
226              'metrics',
227              'parsers',
228              'state',
229              'util']:
230     objs += cxx(name)
231 if platform == 'mingw' or platform == 'windows':
232     objs += cxx('subprocess-win32')
233     objs += cc('getopt')
234 else:
235     objs += cxx('subprocess')
236 if platform == 'windows':
237     ninja_lib = n.build(built('ninja.lib'), 'ar', objs)
238 else:
239     ninja_lib = n.build(built('libninja.a'), 'ar', objs)
240 n.newline()
241
242 if platform == 'windows':
243     libs.append('ninja.lib')
244 else:
245     libs.append('-lninja')
246
247 all_targets = []
248
249 n.comment('Main executable is library plus main() function.')
250 objs = cxx('ninja')
251 ninja = n.build(binary('ninja'), 'link', objs, implicit=ninja_lib,
252                 variables=[('libs', libs)])
253 if 'ninja' not in ninja:
254   n.build('ninja', 'phony', ninja)
255 n.newline()
256 all_targets += ninja
257
258 n.comment('Tests all build into ninja_test executable.')
259
260 variables = []
261 test_cflags = None
262 test_ldflags = None
263 test_libs = libs
264 objs = []
265 if options.with_gtest:
266     path = options.with_gtest
267
268     gtest_all_incs = '-I%s -I%s' % (path, os.path.join(path, 'include'))
269     if platform == 'windows':
270         gtest_cflags = '/nologo /EHsc ' + gtest_all_incs
271     else:
272         gtest_cflags = '-fvisibility=hidden ' + gtest_all_incs
273     objs += n.build(built('gtest-all' + objext), 'cxx',
274                     os.path.join(path, 'src/gtest-all.cc'),
275                     variables=[('cflags', gtest_cflags)])
276     objs += n.build(built('gtest_main' + objext), 'cxx',
277                     os.path.join(path, 'src/gtest_main.cc'),
278                     variables=[('cflags', gtest_cflags)])
279
280     test_cflags = cflags + ['-DGTEST_HAS_RTTI=0',
281                             '-I%s' % os.path.join(path, 'include')]
282 elif platform == 'windows':
283     test_libs.extend(['gtest_main.lib', 'gtest.lib'])
284 else:
285     test_libs.extend(['-lgtest_main', '-lgtest'])
286
287 for name in ['build_log_test',
288              'build_test',
289              'clean_test',
290              'depfile_parser_test',
291              'disk_interface_test',
292              'edit_distance_test',
293              'graph_test',
294              'lexer_test',
295              'parsers_test',
296              'state_test',
297              'subprocess_test',
298              'test',
299              'util_test']:
300     objs += cxx(name, variables=[('cflags', test_cflags)])
301
302 if platform != 'mingw' and platform != 'windows':
303     test_libs.append('-lpthread')
304 ninja_test = n.build(binary('ninja_test'), 'link', objs, implicit=ninja_lib,
305                      variables=[('ldflags', test_ldflags),
306                                 ('libs', test_libs)])
307 if 'ninja_test' not in ninja_test:
308   n.build('ninja_test', 'phony', ninja_test)
309 n.newline()
310 all_targets += ninja_test
311
312
313 n.comment('Perftest executable.')
314 objs = cxx('parser_perftest')
315 parser_perftest = n.build(binary('parser_perftest'), 'link', objs,
316                           implicit=ninja_lib,
317                           variables=[('libs', '-L$builddir -lninja')])
318 n.newline()
319 all_targets += parser_perftest
320
321 n.comment('Generate a graph using the "graph" tool.')
322 n.rule('gendot',
323        command='./ninja -t graph > $out')
324 n.rule('gengraph',
325        command='dot -Tpng $in > $out')
326 dot = n.build(built('graph.dot'), 'gendot', ['ninja', 'build.ninja'])
327 n.build('graph.png', 'gengraph', dot)
328 n.newline()
329
330 n.comment('Generate the manual using asciidoc.')
331 n.rule('asciidoc',
332        command='asciidoc -a toc -a max-width=45em -o $out $in',
333        description='ASCIIDOC $in')
334 manual = n.build(doc('manual.html'), 'asciidoc', doc('manual.asciidoc'))
335 n.build('manual', 'phony',
336         order_only=manual)
337 n.newline()
338
339 n.comment('Generate Doxygen.')
340 n.rule('doxygen',
341        command='doxygen $in',
342        description='DOXYGEN $in')
343 n.variable('doxygen_mainpage_generator',
344            src('gen_doxygen_mainpage.sh'))
345 n.rule('doxygen_mainpage',
346        command='$doxygen_mainpage_generator $in > $out',
347        description='DOXYGEN_MAINPAGE $out')
348 mainpage = n.build(built('doxygen_mainpage'), 'doxygen_mainpage',
349                    ['README', 'HACKING', 'COPYING'],
350                    implicit=['$doxygen_mainpage_generator'])
351 n.build('doxygen', 'doxygen', doc('doxygen.config'),
352         implicit=mainpage)
353 n.newline()
354
355 if host != 'mingw':
356     n.comment('Regenerate build files if build script changes.')
357     n.rule('configure',
358            command='$configure_env %s configure.py $configure_args' %
359                options.with_python,
360            generator=True)
361     n.build('build.ninja', 'configure',
362             implicit=['configure.py', 'misc/ninja_syntax.py'])
363     n.newline()
364
365 n.comment('Build only the main binary by default.')
366 n.default(ninja)
367 n.newline()
368
369 n.build('all', 'phony', all_targets)
370
371 print 'wrote %s.' % BUILD_FILENAME