3 # Copyright 2001 Google Inc. All Rights Reserved.
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
9 # http://www.apache.org/licenses/LICENSE-2.0
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.
17 """Script that generates the build.ninja for ninja itself.
19 Projects that use ninja themselves should either write a similar script
20 or use a meta-build system that supports Ninja output."""
22 from optparse import OptionParser
25 sys.path.insert(0, 'misc')
29 parser = OptionParser()
30 platforms = ['linux', 'freebsd', 'mingw', 'windows']
31 profilers = ['gmon', 'pprof']
32 parser.add_option('--platform',
33 help='target platform (' + '/'.join(platforms) + ')',
35 parser.add_option('--host',
36 help='host platform (' + '/'.join(platforms) + ')',
38 parser.add_option('--debug', action='store_true',
39 help='enable debugging extras',)
40 parser.add_option('--profile', metavar='TYPE',
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 parser.add_option('--with-msvc-helper', metavar='NAME',
49 help="name for ninja-msvc-helper binary (MSVC only)")
50 (options, args) = parser.parse_args()
52 print 'ERROR: extra unparsed command-line arguments:', args
55 platform = options.platform
57 platform = sys.platform
58 if platform.startswith('linux'):
60 elif platform.startswith('freebsd'):
62 elif platform.startswith('mingw'):
64 elif platform.startswith('win'):
66 host = options.host or platform
68 BUILD_FILENAME = 'build.ninja'
69 buildfile = open(BUILD_FILENAME, 'w')
70 n = ninja_syntax.Writer(buildfile)
71 n.comment('This file is used to build ninja itself.')
72 n.comment('It is generated by ' + os.path.basename(__file__) + '.')
75 n.comment('The arguments passed to configure.py, for rerunning it.')
76 n.variable('configure_args', ' '.join(sys.argv[1:]))
77 env_keys = set(['CXX', 'AR', 'CFLAGS', 'LDFLAGS'])
78 configure_env = dict((k, os.environ[k]) for k in os.environ if k in env_keys)
80 config_str = ' '.join([k + '=' + configure_env[k] for k in configure_env])
81 n.variable('configure_env', config_str + '$ ')
84 CXX = configure_env.get('CXX', 'g++')
86 if platform == 'windows':
91 return os.path.join('src', filename)
93 return os.path.join('$builddir', filename)
95 return os.path.join('doc', filename)
96 def cc(name, **kwargs):
97 return n.build(built(name + objext), 'cxx', src(name + '.c'), **kwargs)
98 def cxx(name, **kwargs):
99 return n.build(built(name + objext), 'cxx', src(name + '.cc'), **kwargs)
101 if platform in ('mingw', 'windows'):
103 n.build(name, 'phony', exe)
107 n.variable('builddir', 'build')
108 n.variable('cxx', CXX)
109 if platform == 'windows':
110 n.variable('ar', 'link')
112 n.variable('ar', configure_env.get('AR', 'ar'))
114 if platform == 'windows':
115 cflags = ['/nologo', # Don't print startup banner.
116 '/Zi', # Create pdb with debug info.
117 '/W4', # Highest warning level.
118 '/WX', # Warnings as errors.
119 '/wd4530', '/wd4100', '/wd4706',
120 '/wd4512', '/wd4800', '/wd4702', '/wd4819',
121 # Disable warnings about passing "this" during initialization.
123 '/GR-', # Disable RTTI.
124 # Disable size_t -> int truncation warning.
125 # We never have strings or arrays larger than 2**31.
127 '/DNOMINMAX', '/D_CRT_SECURE_NO_WARNINGS',
128 '/DNINJA_PYTHON="%s"' % options.with_python]
129 ldflags = ['/DEBUG', '/libpath:$builddir']
130 if not options.debug:
131 cflags += ['/Ox', '/DNDEBUG', '/GL']
132 ldflags += ['/LTCG', '/OPT:REF', '/OPT:ICF']
134 cflags = ['-g', '-Wall', '-Wextra',
136 '-Wno-unused-parameter',
139 '-fvisibility=hidden', '-pipe',
140 '-DNINJA_PYTHON="%s"' % options.with_python]
142 cflags += ['-D_GLIBCXX_DEBUG', '-D_GLIBCXX_DEBUG_PEDANTIC']
143 cflags.remove('-fno-rtti') # Needed for above pedanticness.
145 cflags += ['-O2', '-DNDEBUG']
146 if 'clang' in os.path.basename(CXX):
147 cflags += ['-fcolor-diagnostics']
148 if platform == 'mingw':
149 cflags += ['-D_WIN32_WINNT=0x0501']
150 ldflags = ['-L$builddir']
153 if platform == 'mingw':
154 cflags.remove('-fvisibility=hidden');
155 ldflags.append('-static')
156 elif platform == 'sunos5':
157 cflags.remove('-fvisibility=hidden')
158 elif platform == 'windows':
161 if options.profile == 'gmon':
163 ldflags.append('-pg')
164 elif options.profile == 'pprof':
165 libs.append('-lprofiler')
167 def shell_escape(str):
168 """Escape str such that it's interpreted as a single argument by the shell."""
169 # This isn't complete, but it's just enough to make NINJA_PYTHON work.
170 if platform in ('windows', 'mingw'):
173 return "'%s'" % str.replace("'", "\\'")
176 if 'CFLAGS' in configure_env:
177 cflags.append(configure_env['CFLAGS'])
178 n.variable('cflags', ' '.join(shell_escape(flag) for flag in cflags))
179 if 'LDFLAGS' in configure_env:
180 ldflags.append(configure_env['LDFLAGS'])
181 n.variable('ldflags', ' '.join(shell_escape(flag) for flag in ldflags))
184 if platform == 'windows':
186 if options.with_msvc_helper:
187 compiler = '%s -o $out -- $cxx /showIncludes' % options.with_msvc_helper
189 command='%s $cflags -c $in /Fo$out' % compiler,
191 description='CXX $out')
194 command='$cxx -MMD -MT $out -MF $out.d $cflags -c $in -o $out',
196 description='CXX $out')
199 if host == 'windows':
201 command='lib /nologo /ltcg /out:$out $in',
202 description='LIB $out')
203 elif host == 'mingw':
205 command='cmd /c $ar cqs $out.tmp $in && move /Y $out.tmp $out',
206 description='AR $out')
209 command='rm -f $out && $ar crs $out $in',
210 description='AR $out')
213 if platform == 'windows':
215 command='$cxx $in $libs /nologo /link $ldflags /out:$out',
216 description='LINK $out')
219 command='$cxx $ldflags -o $out $in $libs',
220 description='LINK $out')
225 if platform not in ('mingw', 'windows'):
226 n.comment('browse_py.h is used to inline browse.py.')
228 command='src/inline.sh $varname < $in > $out',
229 description='INLINE $out')
230 n.build(built('browse_py.h'), 'inline', src('browse.py'),
231 implicit='src/inline.sh',
232 variables=[('varname', 'kBrowsePy')])
235 objs += cxx('browse', order_only=built('browse_py.h'))
238 n.comment('the depfile parser and ninja lexers are generated using re2c.')
242 subprocess.call(['re2c', '-v'], stdout=subprocess.PIPE)
248 command='re2c -b -i --no-generation-date -o $out $in',
249 description='RE2C $out')
250 # Generate the .cc files in the source directory so we can check them in.
251 n.build(src('depfile_parser.cc'), 're2c', src('depfile_parser.in.cc'))
252 n.build(src('lexer.cc'), 're2c', src('lexer.in.cc'))
254 print ("warning: re2c not found; changes to src/*.in.cc will not affect "
258 n.comment('Core source files all build into ninja library.')
259 for name in ['build',
275 if platform in ('mingw', 'windows'):
276 objs += cxx('subprocess-win32')
277 if platform == 'windows':
278 objs += cxx('includes_normalize-win32')
279 objs += cxx('msvc_helper-win32')
280 objs += cxx('minidump-win32')
283 objs += cxx('subprocess-posix')
284 if platform == 'windows':
285 ninja_lib = n.build(built('ninja.lib'), 'ar', objs)
287 ninja_lib = n.build(built('libninja.a'), 'ar', objs)
290 if platform == 'windows':
291 libs.append('ninja.lib')
293 libs.append('-lninja')
297 n.comment('Main executable is library plus main() function.')
299 ninja = n.build(binary('ninja'), 'link', objs, implicit=ninja_lib,
300 variables=[('libs', libs)])
304 if platform == 'windows':
305 n.comment('Helper for working with MSVC.')
306 msvc_helper = n.build(binary('ninja-msvc-helper'), 'link',
307 cxx('msvc_helper_main-win32'),
309 variables=[('libs', libs)])
310 n.default(msvc_helper)
312 all_targets += msvc_helper
314 n.comment('Tests all build into ninja_test executable.')
321 if options.with_gtest:
322 path = options.with_gtest
324 gtest_all_incs = '-I%s -I%s' % (path, os.path.join(path, 'include'))
325 if platform == 'windows':
326 gtest_cflags = '/nologo /EHsc /Zi ' + gtest_all_incs
328 gtest_cflags = '-fvisibility=hidden ' + gtest_all_incs
329 objs += n.build(built('gtest-all' + objext), 'cxx',
330 os.path.join(path, 'src', 'gtest-all.cc'),
331 variables=[('cflags', gtest_cflags)])
332 objs += n.build(built('gtest_main' + objext), 'cxx',
333 os.path.join(path, 'src', 'gtest_main.cc'),
334 variables=[('cflags', gtest_cflags)])
336 test_cflags = cflags + ['-DGTEST_HAS_RTTI=0',
337 '-I%s' % os.path.join(path, 'include')]
338 elif platform == 'windows':
339 test_libs.extend(['gtest_main.lib', 'gtest.lib'])
341 test_libs.extend(['-lgtest_main', '-lgtest'])
343 for name in ['build_log_test',
346 'depfile_parser_test',
347 'disk_interface_test',
348 'edit_distance_test',
351 'manifest_parser_test',
356 objs += cxx(name, variables=[('cflags', test_cflags)])
357 if platform == 'windows':
358 for name in ['includes_normalize_test', 'msvc_helper_test']:
359 objs += cxx(name, variables=[('cflags', test_cflags)])
361 if platform != 'mingw' and platform != 'windows':
362 test_libs.append('-lpthread')
363 ninja_test = n.build(binary('ninja_test'), 'link', objs, implicit=ninja_lib,
364 variables=[('ldflags', test_ldflags),
365 ('libs', test_libs)])
367 all_targets += ninja_test
370 n.comment('Ancilliary executables.')
371 objs = cxx('parser_perftest')
372 all_targets += n.build(binary('parser_perftest'), 'link', objs,
373 implicit=ninja_lib, variables=[('libs', libs)])
374 objs = cxx('build_log_perftest')
375 all_targets += n.build(binary('build_log_perftest'), 'link', objs,
376 implicit=ninja_lib, variables=[('libs', libs)])
377 objs = cxx('canon_perftest')
378 all_targets += n.build(binary('canon_perftest'), 'link', objs,
379 implicit=ninja_lib, variables=[('libs', libs)])
380 objs = cxx('hash_collision_bench')
381 all_targets += n.build(binary('hash_collision_bench'), 'link', objs,
382 implicit=ninja_lib, variables=[('libs', libs)])
385 n.comment('Generate a graph using the "graph" tool.')
387 command='./ninja -t graph all > $out')
389 command='dot -Tpng $in > $out')
390 dot = n.build(built('graph.dot'), 'gendot', ['ninja', 'build.ninja'])
391 n.build('graph.png', 'gengraph', dot)
394 n.comment('Generate the manual using asciidoc.')
396 command='asciidoc -a toc -a max-width=45em -o $out $in',
397 description='ASCIIDOC $in')
398 manual = n.build(doc('manual.html'), 'asciidoc', doc('manual.asciidoc'))
399 n.build('manual', 'phony',
403 n.comment('Generate Doxygen.')
405 command='doxygen $in',
406 description='DOXYGEN $in')
407 n.variable('doxygen_mainpage_generator',
408 src('gen_doxygen_mainpage.sh'))
409 n.rule('doxygen_mainpage',
410 command='$doxygen_mainpage_generator $in > $out',
411 description='DOXYGEN_MAINPAGE $out')
412 mainpage = n.build(built('doxygen_mainpage'), 'doxygen_mainpage',
413 ['README', 'COPYING'],
414 implicit=['$doxygen_mainpage_generator'])
415 n.build('doxygen', 'doxygen', doc('doxygen.config'),
420 n.comment('Regenerate build files if build script changes.')
422 command='${configure_env}%s configure.py $configure_args' %
425 n.build('build.ninja', 'configure',
426 implicit=['configure.py', os.path.normpath('misc/ninja_syntax.py')])
433 n.comment('Packaging')
437 --define \"rel `git rev-parse --short HEAD`\" \
438 --define '_topdir %(pwd)/rpm-build' \
439 --define '_builddir %{_topdir}' \
440 --define '_rpmdir %{_topdir}' \
441 --define '_srcrpmdir %{_topdir}' \
442 --define '_rpmfilename %%{NAME}-%%{VERSION}-%%{RELEASE}.%%{ARCH}.rpm' \
443 --define '_specdir %{_topdir}' \
444 --define '_sourcedir %{_topdir}' \
446 -bb misc/packaging/ninja.spec",
447 description='Building RPM..')
448 n.build('rpm', 'rpmbuild',
449 implicit=['ninja','README', 'COPYING', doc('manual.html')])
452 n.build('all', 'phony', all_targets)
454 print 'wrote %s.' % BUILD_FILENAME