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
28 import platform_helper
29 sys.path.insert(0, 'misc')
33 parser = OptionParser()
34 profilers = ['gmon', 'pprof']
35 parser.add_option('--platform',
36 help='target platform (' +
37 '/'.join(platform_helper.platforms()) + ')',
38 choices=platform_helper.platforms())
39 parser.add_option('--host',
40 help='host platform (' +
41 '/'.join(platform_helper.platforms()) + ')',
42 choices=platform_helper.platforms())
43 parser.add_option('--debug', action='store_true',
44 help='enable debugging extras',)
45 parser.add_option('--profile', metavar='TYPE',
47 help='enable profiling (' + '/'.join(profilers) + ')',)
48 parser.add_option('--with-gtest', metavar='PATH', help='ignored')
49 parser.add_option('--with-python', metavar='EXE',
50 help='use EXE as the Python interpreter',
51 default=os.path.basename(sys.executable))
52 parser.add_option('--force-pselect', action='store_true',
53 help='ppoll() is used by default where available, '
54 'but some platforms may need to use pselect instead',)
55 (options, args) = parser.parse_args()
57 print('ERROR: extra unparsed command-line arguments:', args)
60 platform = platform_helper.Platform(options.platform)
62 host = platform_helper.Platform(options.host)
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__) + '.')
73 n.variable('ninja_required_version', '1.3')
76 n.comment('The arguments passed to configure.py, for rerunning it.')
77 n.variable('configure_args', ' '.join(sys.argv[1:]))
78 env_keys = set(['CXX', 'AR', 'CFLAGS', 'LDFLAGS'])
79 configure_env = dict((k, os.environ[k]) for k in os.environ if k in env_keys)
81 config_str = ' '.join([k + '=' + pipes.quote(configure_env[k])
82 for k in configure_env])
83 n.variable('configure_env', config_str + '$ ')
86 CXX = configure_env.get('CXX', 'g++')
88 if platform.is_msvc():
93 return os.path.join('src', filename)
95 return os.path.join('$builddir', filename)
97 return os.path.join('doc', filename)
98 def cc(name, **kwargs):
99 return n.build(built(name + objext), 'cxx', src(name + '.c'), **kwargs)
100 def cxx(name, **kwargs):
101 return n.build(built(name + objext), 'cxx', src(name + '.cc'), **kwargs)
103 if platform.is_windows():
105 n.build(name, 'phony', exe)
109 n.variable('builddir', 'build')
110 n.variable('cxx', CXX)
111 if platform.is_msvc():
112 n.variable('ar', 'link')
114 n.variable('ar', configure_env.get('AR', 'ar'))
116 if platform.is_msvc():
117 cflags = ['/nologo', # Don't print startup banner.
118 '/Zi', # Create pdb with debug info.
119 '/W4', # Highest warning level.
120 '/WX', # Warnings as errors.
121 '/wd4530', '/wd4100', '/wd4706',
122 '/wd4512', '/wd4800', '/wd4702', '/wd4819',
123 # Disable warnings about passing "this" during initialization.
125 '/GR-', # Disable RTTI.
126 # Disable size_t -> int truncation warning.
127 # We never have strings or arrays larger than 2**31.
129 '/DNOMINMAX', '/D_CRT_SECURE_NO_WARNINGS',
130 '/D_VARIADIC_MAX=10',
131 '/DNINJA_PYTHON="%s"' % options.with_python]
132 if platform.msvc_needs_fs():
134 ldflags = ['/DEBUG', '/libpath:$builddir']
135 if not options.debug:
136 cflags += ['/Ox', '/DNDEBUG', '/GL']
137 ldflags += ['/LTCG', '/OPT:REF', '/OPT:ICF']
139 cflags = ['-g', '-Wall', '-Wextra',
141 '-Wno-unused-parameter',
144 '-fvisibility=hidden', '-pipe',
145 '-Wno-missing-field-initializers',
146 '-DNINJA_PYTHON="%s"' % options.with_python]
148 cflags += ['-D_GLIBCXX_DEBUG', '-D_GLIBCXX_DEBUG_PEDANTIC']
149 cflags.remove('-fno-rtti') # Needed for above pedanticness.
151 cflags += ['-O2', '-DNDEBUG']
152 if 'clang' in os.path.basename(CXX):
153 cflags += ['-fcolor-diagnostics']
154 if platform.is_mingw():
155 cflags += ['-D_WIN32_WINNT=0x0501']
156 ldflags = ['-L$builddir']
159 if platform.is_mingw():
160 cflags.remove('-fvisibility=hidden');
161 ldflags.append('-static')
162 elif platform.is_solaris():
163 cflags.remove('-fvisibility=hidden')
164 elif platform.is_msvc():
167 if options.profile == 'gmon':
169 ldflags.append('-pg')
170 elif options.profile == 'pprof':
171 cflags.append('-fno-omit-frame-pointer')
172 libs.extend(['-Wl,--no-as-needed', '-lprofiler'])
174 if (platform.is_linux() or platform.is_openbsd() or platform.is_bitrig()) and \
175 not options.force_pselect:
176 cflags.append('-DUSE_PPOLL')
178 def shell_escape(str):
179 """Escape str such that it's interpreted as a single argument by
182 # This isn't complete, but it's just enough to make NINJA_PYTHON work.
183 if platform.is_windows():
186 return "'%s'" % str.replace("'", "\\'")
189 if 'CFLAGS' in configure_env:
190 cflags.append(configure_env['CFLAGS'])
191 n.variable('cflags', ' '.join(shell_escape(flag) for flag in cflags))
192 if 'LDFLAGS' in configure_env:
193 ldflags.append(configure_env['LDFLAGS'])
194 n.variable('ldflags', ' '.join(shell_escape(flag) for flag in ldflags))
197 if platform.is_msvc():
199 command='$cxx /showIncludes $cflags -c $in /Fo$out',
200 description='CXX $out',
204 command='$cxx -MMD -MT $out -MF $out.d $cflags -c $in -o $out',
207 description='CXX $out')
212 command='lib /nologo /ltcg /out:$out $in',
213 description='LIB $out')
214 elif host.is_mingw():
216 command='cmd /c $ar cqs $out.tmp $in && move /Y $out.tmp $out',
217 description='AR $out')
220 command='rm -f $out && $ar crs $out $in',
221 description='AR $out')
224 if platform.is_msvc():
226 command='$cxx $in $libs /nologo /link $ldflags /out:$out',
227 description='LINK $out')
230 command='$cxx $ldflags -o $out $in $libs',
231 description='LINK $out')
236 if not platform.is_windows() and not platform.is_solaris():
237 n.comment('browse_py.h is used to inline browse.py.')
239 command='src/inline.sh $varname < $in > $out',
240 description='INLINE $out')
241 n.build(built('browse_py.h'), 'inline', src('browse.py'),
242 implicit='src/inline.sh',
243 variables=[('varname', 'kBrowsePy')])
246 objs += cxx('browse', order_only=built('browse_py.h'))
249 n.comment('the depfile parser and ninja lexers are generated using re2c.')
253 proc = subprocess.Popen(['re2c', '-V'], stdout=subprocess.PIPE)
254 return int(proc.communicate()[0], 10) >= 1103
259 command='re2c -b -i --no-generation-date -o $out $in',
260 description='RE2C $out')
261 # Generate the .cc files in the source directory so we can check them in.
262 n.build(src('depfile_parser.cc'), 're2c', src('depfile_parser.in.cc'))
263 n.build(src('lexer.cc'), 're2c', src('lexer.in.cc'))
265 print("warning: A compatible version of re2c (>= 0.11.3) was not found; "
266 "changes to src/*.in.cc will not affect your build.")
269 n.comment('Core source files all build into ninja library.')
270 for name in ['build',
289 if platform.is_windows():
290 for name in ['subprocess-win32',
291 'includes_normalize-win32',
293 'msvc_helper_main-win32']:
295 if platform.is_msvc():
296 objs += cxx('minidump-win32')
299 objs += cxx('subprocess-posix')
300 if platform.is_msvc():
301 ninja_lib = n.build(built('ninja.lib'), 'ar', objs)
303 ninja_lib = n.build(built('libninja.a'), 'ar', objs)
306 if platform.is_msvc():
307 libs.append('ninja.lib')
309 libs.append('-lninja')
313 n.comment('Main executable is library plus main() function.')
315 ninja = n.build(binary('ninja'), 'link', objs, implicit=ninja_lib,
316 variables=[('libs', libs)])
320 n.comment('Tests all build into ninja_test executable.')
327 for name in ['build_log_test',
330 'depfile_parser_test',
332 'disk_interface_test',
333 'edit_distance_test',
336 'manifest_parser_test',
343 if platform.is_windows():
344 for name in ['includes_normalize_test', 'msvc_helper_test']:
347 if not platform.is_windows():
348 test_libs.append('-lpthread')
349 ninja_test = n.build(binary('ninja_test'), 'link', objs, implicit=ninja_lib,
350 variables=[('ldflags', test_ldflags),
351 ('libs', test_libs)])
353 all_targets += ninja_test
356 n.comment('Ancillary executables.')
357 objs = cxx('build_log_perftest')
358 all_targets += n.build(binary('build_log_perftest'), 'link', objs,
359 implicit=ninja_lib, variables=[('libs', libs)])
360 objs = cxx('canon_perftest')
361 all_targets += n.build(binary('canon_perftest'), 'link', objs,
362 implicit=ninja_lib, variables=[('libs', libs)])
363 objs = cxx('depfile_parser_perftest')
364 all_targets += n.build(binary('depfile_parser_perftest'), 'link', objs,
365 implicit=ninja_lib, variables=[('libs', libs)])
366 objs = cxx('hash_collision_bench')
367 all_targets += n.build(binary('hash_collision_bench'), 'link', objs,
368 implicit=ninja_lib, variables=[('libs', libs)])
369 objs = cxx('manifest_parser_perftest')
370 all_targets += n.build(binary('manifest_parser_perftest'), 'link', objs,
371 implicit=ninja_lib, variables=[('libs', libs)])
374 n.comment('Generate a graph using the "graph" tool.')
376 command='./ninja -t graph all > $out')
378 command='dot -Tpng $in > $out')
379 dot = n.build(built('graph.dot'), 'gendot', ['ninja', 'build.ninja'])
380 n.build('graph.png', 'gengraph', dot)
383 n.comment('Generate the manual using asciidoc.')
385 command='asciidoc -b docbook -d book -o $out $in',
386 description='ASCIIDOC $out')
388 command='xsltproc --nonet doc/docbook.xsl $in > $out',
389 description='XSLTPROC $out')
390 xml = n.build(built('manual.xml'), 'asciidoc', doc('manual.asciidoc'))
391 manual = n.build(doc('manual.html'), 'xsltproc', xml,
392 implicit=doc('style.css'))
393 n.build('manual', 'phony',
397 n.comment('Generate Doxygen.')
399 command='doxygen $in',
400 description='DOXYGEN $in')
401 n.variable('doxygen_mainpage_generator',
402 src('gen_doxygen_mainpage.sh'))
403 n.rule('doxygen_mainpage',
404 command='$doxygen_mainpage_generator $in > $out',
405 description='DOXYGEN_MAINPAGE $out')
406 mainpage = n.build(built('doxygen_mainpage'), 'doxygen_mainpage',
407 ['README', 'COPYING'],
408 implicit=['$doxygen_mainpage_generator'])
409 n.build('doxygen', 'doxygen', doc('doxygen.config'),
413 if not host.is_mingw():
414 n.comment('Regenerate build files if build script changes.')
416 command='${configure_env}%s configure.py $configure_args' %
419 n.build('build.ninja', 'configure',
420 implicit=['configure.py', os.path.normpath('misc/ninja_syntax.py')])
427 n.comment('Packaging')
429 command="misc/packaging/rpmbuild.sh",
430 description='Building rpms..')
431 n.build('rpm', 'rpmbuild')
434 n.build('all', 'phony', all_targets)
436 print('wrote %s.' % BUILD_FILENAME)