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 __future__ import print_function
24 from optparse import OptionParser
27 import platform_helper
28 sys.path.insert(0, 'misc')
32 parser = OptionParser()
33 profilers = ['gmon', 'pprof']
34 parser.add_option('--platform',
35 help='target platform (' +
36 '/'.join(platform_helper.platforms()) + ')',
37 choices=platform_helper.platforms())
38 parser.add_option('--host',
39 help='host platform (' +
40 '/'.join(platform_helper.platforms()) + ')',
41 choices=platform_helper.platforms())
42 parser.add_option('--debug', action='store_true',
43 help='enable debugging extras',)
44 parser.add_option('--profile', metavar='TYPE',
46 help='enable profiling (' + '/'.join(profilers) + ')',)
47 parser.add_option('--with-gtest', metavar='PATH', help='ignored')
48 parser.add_option('--with-python', metavar='EXE',
49 help='use EXE as the Python interpreter',
50 default=os.path.basename(sys.executable))
51 parser.add_option('--force-pselect', action='store_true',
52 help='ppoll() is used by default where available, '
53 'but some platforms may need to use pselect instead',)
54 (options, args) = parser.parse_args()
56 print('ERROR: extra unparsed command-line arguments:', args)
59 platform = platform_helper.Platform(options.platform)
61 host = platform_helper.Platform(options.host)
65 BUILD_FILENAME = 'build.ninja'
66 buildfile = open(BUILD_FILENAME, 'w')
67 n = ninja_syntax.Writer(buildfile)
68 n.comment('This file is used to build ninja itself.')
69 n.comment('It is generated by ' + os.path.basename(__file__) + '.')
72 n.variable('ninja_required_version', '1.3')
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.is_msvc():
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.is_windows():
103 n.build(name, 'phony', exe)
107 n.variable('builddir', 'build')
108 n.variable('cxx', CXX)
109 if platform.is_msvc():
110 n.variable('ar', 'link')
112 n.variable('ar', configure_env.get('AR', 'ar'))
114 if platform.is_msvc():
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 '/D_VARIADIC_MAX=10',
129 '/DNINJA_PYTHON="%s"' % options.with_python]
130 if platform.msvc_needs_fs():
132 ldflags = ['/DEBUG', '/libpath:$builddir']
133 if not options.debug:
134 cflags += ['/Ox', '/DNDEBUG', '/GL']
135 ldflags += ['/LTCG', '/OPT:REF', '/OPT:ICF']
137 cflags = ['-g', '-Wall', '-Wextra',
139 '-Wno-unused-parameter',
142 '-fvisibility=hidden', '-pipe',
143 '-Wno-missing-field-initializers',
144 '-DNINJA_PYTHON="%s"' % options.with_python]
146 cflags += ['-D_GLIBCXX_DEBUG', '-D_GLIBCXX_DEBUG_PEDANTIC']
147 cflags.remove('-fno-rtti') # Needed for above pedanticness.
149 cflags += ['-O2', '-DNDEBUG']
150 if 'clang' in os.path.basename(CXX):
151 cflags += ['-fcolor-diagnostics']
152 if platform.is_mingw():
153 cflags += ['-D_WIN32_WINNT=0x0501']
154 ldflags = ['-L$builddir']
157 if platform.is_mingw():
158 cflags.remove('-fvisibility=hidden');
159 ldflags.append('-static')
160 elif platform.is_sunos5():
161 cflags.remove('-fvisibility=hidden')
162 elif platform.is_msvc():
165 if options.profile == 'gmon':
167 ldflags.append('-pg')
168 elif options.profile == 'pprof':
169 cflags.append('-fno-omit-frame-pointer')
170 libs.extend(['-Wl,--no-as-needed', '-lprofiler'])
172 if (platform.is_linux() or platform.is_openbsd() or platform.is_bitrig()) and \
173 not options.force_pselect:
174 cflags.append('-DUSE_PPOLL')
176 def shell_escape(str):
177 """Escape str such that it's interpreted as a single argument by
180 # This isn't complete, but it's just enough to make NINJA_PYTHON work.
181 if platform.is_windows():
184 return "'%s'" % str.replace("'", "\\'")
187 if 'CFLAGS' in configure_env:
188 cflags.append(configure_env['CFLAGS'])
189 n.variable('cflags', ' '.join(shell_escape(flag) for flag in cflags))
190 if 'LDFLAGS' in configure_env:
191 ldflags.append(configure_env['LDFLAGS'])
192 n.variable('ldflags', ' '.join(shell_escape(flag) for flag in ldflags))
195 if platform.is_msvc():
197 command='$cxx /showIncludes $cflags -c $in /Fo$out',
198 description='CXX $out',
202 command='$cxx -MMD -MT $out -MF $out.d $cflags -c $in -o $out',
205 description='CXX $out')
210 command='lib /nologo /ltcg /out:$out $in',
211 description='LIB $out')
212 elif host.is_mingw():
214 command='cmd /c $ar cqs $out.tmp $in && move /Y $out.tmp $out',
215 description='AR $out')
218 command='rm -f $out && $ar crs $out $in',
219 description='AR $out')
222 if platform.is_msvc():
224 command='$cxx $in $libs /nologo /link $ldflags /out:$out',
225 description='LINK $out')
228 command='$cxx $ldflags -o $out $in $libs',
229 description='LINK $out')
234 if not platform.is_windows() and not platform.is_solaris():
235 n.comment('browse_py.h is used to inline browse.py.')
237 command='src/inline.sh $varname < $in > $out',
238 description='INLINE $out')
239 n.build(built('browse_py.h'), 'inline', src('browse.py'),
240 implicit='src/inline.sh',
241 variables=[('varname', 'kBrowsePy')])
244 objs += cxx('browse', order_only=built('browse_py.h'))
247 n.comment('the depfile parser and ninja lexers are generated using re2c.')
251 proc = subprocess.Popen(['re2c', '-V'], stdout=subprocess.PIPE)
252 return int(proc.communicate()[0], 10) >= 1103
257 command='re2c -b -i --no-generation-date -o $out $in',
258 description='RE2C $out')
259 # Generate the .cc files in the source directory so we can check them in.
260 n.build(src('depfile_parser.cc'), 're2c', src('depfile_parser.in.cc'))
261 n.build(src('lexer.cc'), 're2c', src('lexer.in.cc'))
263 print("warning: A compatible version of re2c (>= 0.11.3) was not found; "
264 "changes to src/*.in.cc will not affect your build.")
267 n.comment('Core source files all build into ninja library.')
268 for name in ['build',
287 if platform.is_windows():
288 for name in ['subprocess-win32',
289 'includes_normalize-win32',
291 'msvc_helper_main-win32']:
293 if platform.is_msvc():
294 objs += cxx('minidump-win32')
297 objs += cxx('subprocess-posix')
298 if platform.is_msvc():
299 ninja_lib = n.build(built('ninja.lib'), 'ar', objs)
301 ninja_lib = n.build(built('libninja.a'), 'ar', objs)
304 if platform.is_msvc():
305 libs.append('ninja.lib')
307 libs.append('-lninja')
311 n.comment('Main executable is library plus main() function.')
313 ninja = n.build(binary('ninja'), 'link', objs, implicit=ninja_lib,
314 variables=[('libs', libs)])
318 n.comment('Tests all build into ninja_test executable.')
325 for name in ['build_log_test',
328 'depfile_parser_test',
330 'disk_interface_test',
331 'edit_distance_test',
334 'manifest_parser_test',
341 if platform.is_windows():
342 for name in ['includes_normalize_test', 'msvc_helper_test']:
345 if not platform.is_windows():
346 test_libs.append('-lpthread')
347 ninja_test = n.build(binary('ninja_test'), 'link', objs, implicit=ninja_lib,
348 variables=[('ldflags', test_ldflags),
349 ('libs', test_libs)])
351 all_targets += ninja_test
354 n.comment('Ancillary executables.')
355 objs = cxx('build_log_perftest')
356 all_targets += n.build(binary('build_log_perftest'), 'link', objs,
357 implicit=ninja_lib, variables=[('libs', libs)])
358 objs = cxx('canon_perftest')
359 all_targets += n.build(binary('canon_perftest'), 'link', objs,
360 implicit=ninja_lib, variables=[('libs', libs)])
361 objs = cxx('depfile_parser_perftest')
362 all_targets += n.build(binary('depfile_parser_perftest'), 'link', objs,
363 implicit=ninja_lib, variables=[('libs', libs)])
364 objs = cxx('hash_collision_bench')
365 all_targets += n.build(binary('hash_collision_bench'), 'link', objs,
366 implicit=ninja_lib, variables=[('libs', libs)])
367 objs = cxx('manifest_parser_perftest')
368 all_targets += n.build(binary('manifest_parser_perftest'), 'link', objs,
369 implicit=ninja_lib, variables=[('libs', libs)])
372 n.comment('Generate a graph using the "graph" tool.')
374 command='./ninja -t graph all > $out')
376 command='dot -Tpng $in > $out')
377 dot = n.build(built('graph.dot'), 'gendot', ['ninja', 'build.ninja'])
378 n.build('graph.png', 'gengraph', dot)
381 n.comment('Generate the manual using asciidoc.')
383 command='asciidoc -b docbook -d book -o $out $in',
384 description='ASCIIDOC $out')
386 command='xsltproc --nonet doc/docbook.xsl $in > $out',
387 description='XSLTPROC $out')
388 xml = n.build(built('manual.xml'), 'asciidoc', doc('manual.asciidoc'))
389 manual = n.build(doc('manual.html'), 'xsltproc', xml,
390 implicit=doc('style.css'))
391 n.build('manual', 'phony',
395 n.comment('Generate Doxygen.')
397 command='doxygen $in',
398 description='DOXYGEN $in')
399 n.variable('doxygen_mainpage_generator',
400 src('gen_doxygen_mainpage.sh'))
401 n.rule('doxygen_mainpage',
402 command='$doxygen_mainpage_generator $in > $out',
403 description='DOXYGEN_MAINPAGE $out')
404 mainpage = n.build(built('doxygen_mainpage'), 'doxygen_mainpage',
405 ['README', 'COPYING'],
406 implicit=['$doxygen_mainpage_generator'])
407 n.build('doxygen', 'doxygen', doc('doxygen.config'),
411 if not host.is_mingw():
412 n.comment('Regenerate build files if build script changes.')
414 command='${configure_env}%s configure.py $configure_args' %
417 n.build('build.ninja', 'configure',
418 implicit=['configure.py', os.path.normpath('misc/ninja_syntax.py')])
425 n.comment('Packaging')
427 command="misc/packaging/rpmbuild.sh",
428 description='Building rpms..')
429 n.build('rpm', 'rpmbuild')
432 n.build('all', 'phony', all_targets)
434 print('wrote %s.' % BUILD_FILENAME)