Merge pull request #257 from PetrWolf/53598255
[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',
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 -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              'graph',
219              'graphviz',
220              'lexer',
221              'metrics',
222              'parsers',
223              'state',
224              'util']:
225     objs += cxx(name)
226 if platform == 'mingw' or platform == 'windows':
227     objs += cxx('subprocess-win32')
228     objs += cc('getopt')
229 else:
230     objs += cxx('subprocess')
231 if platform == 'windows':
232     ninja_lib = n.build(built('ninja.lib'), 'ar', objs)
233 else:
234     ninja_lib = n.build(built('libninja.a'), 'ar', objs)
235 n.newline()
236
237 if platform == 'windows':
238     libs.append('ninja.lib')
239 else:
240     libs.append('-lninja')
241
242 all_targets = []
243
244 n.comment('Main executable is library plus main() function.')
245 objs = cxx('ninja')
246 ninja = n.build(binary('ninja'), 'link', objs, implicit=ninja_lib,
247                 variables=[('libs', libs)])
248 n.newline()
249 all_targets += ninja
250
251 n.comment('Tests all build into ninja_test executable.')
252
253 variables = []
254 test_cflags = None
255 test_ldflags = None
256 test_libs = libs
257 objs = []
258 if options.with_gtest:
259     path = options.with_gtest
260
261     gtest_all_incs = '-I%s -I%s' % (path, os.path.join(path, 'include'))
262     gtest_cflags = '-fvisibility=hidden ' + gtest_all_incs
263     objs += n.build(built('gtest-all.o'), 'cxx',
264                     os.path.join(path, 'src/gtest-all.cc'),
265                     variables=[('cflags', gtest_cflags)])
266     objs += n.build(built('gtest_main.o'), 'cxx',
267                     os.path.join(path, 'src/gtest_main.cc'),
268                     variables=[('cflags', gtest_cflags)])
269
270     test_cflags = cflags + ['-I%s' % os.path.join(path, 'include')]
271 elif platform == 'windows':
272     test_libs.extend(['gtest_main.lib', 'gtest.lib'])
273 else:
274     test_libs.extend(['-lgtest_main', '-lgtest'])
275
276 for name in ['build_log_test',
277              'build_test',
278              'clean_test',
279              'depfile_parser_test',
280              'disk_interface_test',
281              'edit_distance_test',
282              'graph_test',
283              'lexer_test',
284              'parsers_test',
285              'state_test',
286              'subprocess_test',
287              'test',
288              'util_test']:
289     objs += cxx(name, variables=[('cflags', test_cflags)])
290
291 if platform != 'mingw' and platform != 'windows':
292     test_libs.append('-lpthread')
293 ninja_test = n.build(binary('ninja_test'), 'link', objs, implicit=ninja_lib,
294                      variables=[('ldflags', test_ldflags),
295                                 ('libs', test_libs)])
296 n.newline()
297 all_targets += ninja_test
298
299 n.comment('Perftest executable.')
300 objs = cxx('parser_perftest')
301 parser_perftest = n.build(binary('parser_perftest'), 'link', objs,
302                           implicit=ninja_lib,
303                           variables=[('libs', '-L$builddir -lninja')])
304 n.newline()
305 all_targets += parser_perftest
306
307 n.comment('Generate a graph using the "graph" tool.')
308 n.rule('gendot',
309        command='./ninja -t graph > $out')
310 n.rule('gengraph',
311        command='dot -Tpng $in > $out')
312 dot = n.build(built('graph.dot'), 'gendot', ['ninja', 'build.ninja'])
313 n.build('graph.png', 'gengraph', dot)
314 n.newline()
315
316 n.comment('Generate the manual using asciidoc.')
317 n.rule('asciidoc',
318        command='asciidoc -a toc -o $out $in',
319        description='ASCIIDOC $in')
320 manual = n.build(doc('manual.html'), 'asciidoc', doc('manual.asciidoc'))
321 n.build('manual', 'phony',
322         order_only=manual)
323 n.newline()
324
325 n.comment('Generate Doxygen.')
326 n.rule('doxygen',
327        command='doxygen $in',
328        description='DOXYGEN $in')
329 n.variable('doxygen_mainpage_generator',
330            src('gen_doxygen_mainpage.sh'))
331 n.rule('doxygen_mainpage',
332        command='$doxygen_mainpage_generator $in > $out',
333        description='DOXYGEN_MAINPAGE $out')
334 mainpage = n.build(built('doxygen_mainpage'), 'doxygen_mainpage',
335                    ['README', 'HACKING', 'COPYING'],
336                    implicit=['$doxygen_mainpage_generator'])
337 n.build('doxygen', 'doxygen', doc('doxygen.config'),
338         implicit=mainpage)
339 n.newline()
340
341 if host != 'mingw':
342     n.comment('Regenerate build files if build script changes.')
343     n.rule('configure',
344            command=options.with_python + ' configure.py $configure_args',
345            generator=True)
346     n.build('build.ninja', 'configure',
347             implicit=['configure.py', 'misc/ninja_syntax.py'])
348     n.newline()
349
350 n.comment('Build only the main binary by default.')
351 n.default(ninja)
352 n.newline()
353
354 n.build('all', 'phony', all_targets)
355
356 print 'wrote %s.' % BUILD_FILENAME