Merge pull request #401 from syntheticpp/win-network-path
[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 parser.add_option('--with-msvc-helper', metavar='NAME',
49                   help="name for ninja-msvc-helper binary (MSVC only)")
50 (options, args) = parser.parse_args()
51 if args:
52     print 'ERROR: extra unparsed command-line arguments:', args
53     sys.exit(1)
54
55 platform = options.platform
56 if platform is None:
57     platform = sys.platform
58     if platform.startswith('linux'):
59         platform = 'linux'
60     elif platform.startswith('freebsd'):
61         platform = 'freebsd'
62     elif platform.startswith('mingw'):
63         platform = 'mingw'
64     elif platform.startswith('win'):
65         platform = 'windows'
66 host = options.host or platform
67
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__) + '.')
73 n.newline()
74
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)
79 if configure_env:
80     config_str = ' '.join([k + '=' + configure_env[k] for k in configure_env])
81     n.variable('configure_env', config_str + '$ ')
82 n.newline()
83
84 CXX = configure_env.get('CXX', 'g++')
85 objext = '.o'
86 if platform == 'windows':
87     CXX = 'cl'
88     objext = '.obj'
89
90 def src(filename):
91     return os.path.join('src', filename)
92 def built(filename):
93     return os.path.join('$builddir', filename)
94 def doc(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)
100 def binary(name):
101     if platform in ('mingw', 'windows'):
102         exe = name + '.exe'
103         n.build(name, 'phony', exe)
104         return exe
105     return name
106
107 n.variable('builddir', 'build')
108 n.variable('cxx', CXX)
109 if platform == 'windows':
110     n.variable('ar', 'link')
111 else:
112     n.variable('ar', configure_env.get('AR', 'ar'))
113
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               '/GR-',  # Disable RTTI.
122               # Disable size_t -> int truncation warning.
123               # We never have strings or arrays larger than 2**31.
124               '/wd4267',
125               '/DNOMINMAX', '/D_CRT_SECURE_NO_WARNINGS',
126               '/DNINJA_PYTHON="%s"' % options.with_python]
127     ldflags = ['/DEBUG', '/libpath:$builddir']
128     if not options.debug:
129         cflags += ['/Ox', '/DNDEBUG', '/GL']
130         ldflags += ['/LTCG', '/OPT:REF', '/OPT:ICF']
131 else:
132     cflags = ['-g', '-Wall', '-Wextra',
133               '-Wno-deprecated',
134               '-Wno-unused-parameter',
135               '-fno-rtti',
136               '-fno-exceptions',
137               '-fvisibility=hidden', '-pipe',
138               '-DNINJA_PYTHON="%s"' % options.with_python]
139     if options.debug:
140         cflags += ['-D_GLIBCXX_DEBUG', '-D_GLIBCXX_DEBUG_PEDANTIC']
141     else:
142         cflags += ['-O2', '-DNDEBUG']
143     if 'clang' in os.path.basename(CXX):
144         cflags += ['-fcolor-diagnostics']
145     if platform == 'mingw':
146         cflags += ['-D_WIN32_WINNT=0x0501']
147     ldflags = ['-L$builddir']
148 libs = []
149
150 if platform == 'mingw':
151     cflags.remove('-fvisibility=hidden');
152     ldflags.append('-static')
153 elif platform == 'sunos5':
154     cflags.remove('-fvisibility=hidden')
155 elif platform == 'windows':
156     pass
157 else:
158     if options.profile == 'gmon':
159         cflags.append('-pg')
160         ldflags.append('-pg')
161     elif options.profile == 'pprof':
162         libs.append('-lprofiler')
163
164 def shell_escape(str):
165     """Escape str such that it's interpreted as a single argument by the shell."""
166     # This isn't complete, but it's just enough to make NINJA_PYTHON work.
167     if platform in ('windows', 'mingw'):
168       return str
169     if '"' in str:
170         return "'%s'" % str.replace("'", "\\'")
171     return str
172
173 if 'CFLAGS' in configure_env:
174     cflags.append(configure_env['CFLAGS'])
175 n.variable('cflags', ' '.join(shell_escape(flag) for flag in cflags))
176 if 'LDFLAGS' in configure_env:
177     ldflags.append(configure_env['LDFLAGS'])
178 n.variable('ldflags', ' '.join(shell_escape(flag) for flag in ldflags))
179 n.newline()
180
181 if platform == 'windows':
182     compiler = '$cxx'
183     if options.with_msvc_helper:
184         compiler = '%s -o $out -- $cxx /showIncludes' % options.with_msvc_helper
185     n.rule('cxx',
186         command='%s $cflags -c $in /Fo$out' % compiler,
187         depfile='$out.d',
188         description='CXX $out')
189 else:
190     n.rule('cxx',
191         command='$cxx -MMD -MT $out -MF $out.d $cflags -c $in -o $out',
192         depfile='$out.d',
193         description='CXX $out')
194 n.newline()
195
196 if host == 'windows':
197     n.rule('ar',
198            command='lib /nologo /ltcg /out:$out $in',
199            description='LIB $out')
200 elif host == 'mingw':
201     n.rule('ar',
202            command='cmd /c $ar cqs $out.tmp $in && move /Y $out.tmp $out',
203            description='AR $out')
204 else:
205     n.rule('ar',
206            command='rm -f $out && $ar crs $out $in',
207            description='AR $out')
208 n.newline()
209
210 if platform == 'windows':
211     n.rule('link',
212         command='$cxx $in $libs /nologo /link $ldflags /out:$out',
213         description='LINK $out')
214 else:
215     n.rule('link',
216         command='$cxx $ldflags -o $out $in $libs',
217         description='LINK $out')
218 n.newline()
219
220 objs = []
221
222 if platform not in ('mingw', 'windows'):
223     n.comment('browse_py.h is used to inline browse.py.')
224     n.rule('inline',
225            command='src/inline.sh $varname < $in > $out',
226            description='INLINE $out')
227     n.build(built('browse_py.h'), 'inline', src('browse.py'),
228             implicit='src/inline.sh',
229             variables=[('varname', 'kBrowsePy')])
230     n.newline()
231
232     objs += cxx('browse', order_only=built('browse_py.h'))
233     n.newline()
234
235 n.comment('the depfile parser and ninja lexers are generated using re2c.')
236 def has_re2c():
237     import subprocess
238     try:
239         subprocess.call(['re2c', '-v'], stdout=subprocess.PIPE)
240         return True
241     except OSError:
242         return False
243 if has_re2c():
244     n.rule('re2c',
245            command='re2c -b -i --no-generation-date -o $out $in',
246            description='RE2C $out')
247     # Generate the .cc files in the source directory so we can check them in.
248     n.build(src('depfile_parser.cc'), 're2c', src('depfile_parser.in.cc'))
249     n.build(src('lexer.cc'), 're2c', src('lexer.in.cc'))
250 else:
251     print ("warning: re2c not found; changes to src/*.in.cc will not affect "
252            "your build.")
253 n.newline()
254
255 n.comment('Core source files all build into ninja library.')
256 for name in ['build',
257              'build_log',
258              'clean',
259              'depfile_parser',
260              'disk_interface',
261              'edit_distance',
262              'eval_env',
263              'explain',
264              'graph',
265              'graphviz',
266              'lexer',
267              'manifest_parser',
268              'metrics',
269              'state',
270              'util']:
271     objs += cxx(name)
272 if platform in ('mingw', 'windows'):
273     objs += cxx('subprocess-win32')
274     if platform == 'windows':
275         objs += cxx('includes_normalize-win32')
276         objs += cxx('msvc_helper-win32')
277         objs += cxx('minidump-win32')
278     objs += cc('getopt')
279 else:
280     objs += cxx('subprocess-posix')
281 if platform == 'windows':
282     ninja_lib = n.build(built('ninja.lib'), 'ar', objs)
283 else:
284     ninja_lib = n.build(built('libninja.a'), 'ar', objs)
285 n.newline()
286
287 if platform == 'windows':
288     libs.append('ninja.lib')
289 else:
290     libs.append('-lninja')
291
292 all_targets = []
293
294 n.comment('Main executable is library plus main() function.')
295 objs = cxx('ninja')
296 ninja = n.build(binary('ninja'), 'link', objs, implicit=ninja_lib,
297                 variables=[('libs', libs)])
298 n.newline()
299 all_targets += ninja
300
301 if platform == 'windows':
302     n.comment('Helper for working with MSVC.')
303     msvc_helper = n.build(binary('ninja-msvc-helper'), 'link',
304                           cxx('msvc_helper_main-win32'),
305                           implicit=ninja_lib,
306                           variables=[('libs', libs)])
307     n.default(msvc_helper)
308     n.newline()
309     all_targets += msvc_helper
310
311 n.comment('Tests all build into ninja_test executable.')
312
313 variables = []
314 test_cflags = None
315 test_ldflags = None
316 test_libs = libs
317 objs = []
318 if options.with_gtest:
319     path = options.with_gtest
320
321     gtest_all_incs = '-I%s -I%s' % (path, os.path.join(path, 'include'))
322     if platform == 'windows':
323         gtest_cflags = '/nologo /EHsc ' + gtest_all_incs
324     else:
325         gtest_cflags = '-fvisibility=hidden ' + gtest_all_incs
326     objs += n.build(built('gtest-all' + objext), 'cxx',
327                     os.path.join(path, 'src', 'gtest-all.cc'),
328                     variables=[('cflags', gtest_cflags)])
329     objs += n.build(built('gtest_main' + objext), 'cxx',
330                     os.path.join(path, 'src', 'gtest_main.cc'),
331                     variables=[('cflags', gtest_cflags)])
332
333     test_cflags = cflags + ['-DGTEST_HAS_RTTI=0',
334                             '-I%s' % os.path.join(path, 'include')]
335 elif platform == 'windows':
336     test_libs.extend(['gtest_main.lib', 'gtest.lib'])
337 else:
338     test_libs.extend(['-lgtest_main', '-lgtest'])
339
340 for name in ['build_log_test',
341              'build_test',
342              'clean_test',
343              'depfile_parser_test',
344              'disk_interface_test',
345              'edit_distance_test',
346              'graph_test',
347              'lexer_test',
348              'manifest_parser_test',
349              'state_test',
350              'subprocess_test',
351              'test',
352              'util_test']:
353     objs += cxx(name, variables=[('cflags', test_cflags)])
354 if platform == 'windows':
355     for name in ['includes_normalize_test', 'msvc_helper_test']:
356         objs += cxx(name, variables=[('cflags', test_cflags)])
357
358 if platform != 'mingw' and platform != 'windows':
359     test_libs.append('-lpthread')
360 ninja_test = n.build(binary('ninja_test'), 'link', objs, implicit=ninja_lib,
361                      variables=[('ldflags', test_ldflags),
362                                 ('libs', test_libs)])
363 n.newline()
364 all_targets += ninja_test
365
366
367 n.comment('Ancilliary executables.')
368 objs = cxx('parser_perftest')
369 all_targets += n.build(binary('parser_perftest'), 'link', objs,
370                        implicit=ninja_lib, variables=[('libs', libs)])
371 objs = cxx('build_log_perftest')
372 all_targets += n.build(binary('build_log_perftest'), 'link', objs,
373                        implicit=ninja_lib, variables=[('libs', libs)])
374 objs = cxx('canon_perftest')
375 all_targets += n.build(binary('canon_perftest'), 'link', objs,
376                        implicit=ninja_lib, variables=[('libs', libs)])
377 objs = cxx('hash_collision_bench')
378 all_targets += n.build(binary('hash_collision_bench'), 'link', objs,
379                               implicit=ninja_lib, variables=[('libs', libs)])
380 n.newline()
381
382 n.comment('Generate a graph using the "graph" tool.')
383 n.rule('gendot',
384        command='./ninja -t graph > $out')
385 n.rule('gengraph',
386        command='dot -Tpng $in > $out')
387 dot = n.build(built('graph.dot'), 'gendot', ['ninja', 'build.ninja'])
388 n.build('graph.png', 'gengraph', dot)
389 n.newline()
390
391 n.comment('Generate the manual using asciidoc.')
392 n.rule('asciidoc',
393        command='asciidoc -a toc -a max-width=45em -o $out $in',
394        description='ASCIIDOC $in')
395 manual = n.build(doc('manual.html'), 'asciidoc', doc('manual.asciidoc'))
396 n.build('manual', 'phony',
397         order_only=manual)
398 n.newline()
399
400 n.comment('Generate Doxygen.')
401 n.rule('doxygen',
402        command='doxygen $in',
403        description='DOXYGEN $in')
404 n.variable('doxygen_mainpage_generator',
405            src('gen_doxygen_mainpage.sh'))
406 n.rule('doxygen_mainpage',
407        command='$doxygen_mainpage_generator $in > $out',
408        description='DOXYGEN_MAINPAGE $out')
409 mainpage = n.build(built('doxygen_mainpage'), 'doxygen_mainpage',
410                    ['README', 'COPYING'],
411                    implicit=['$doxygen_mainpage_generator'])
412 n.build('doxygen', 'doxygen', doc('doxygen.config'),
413         implicit=mainpage)
414 n.newline()
415
416 if host != 'mingw':
417     n.comment('Regenerate build files if build script changes.')
418     n.rule('configure',
419            command='${configure_env}%s configure.py $configure_args' %
420                options.with_python,
421            generator=True)
422     n.build('build.ninja', 'configure',
423             implicit=['configure.py', os.path.normpath('misc/ninja_syntax.py')])
424     n.newline()
425
426 n.default(ninja)
427 n.newline()
428
429 if host == 'linux':
430     n.comment('Packaging')
431     n.rule('rpmbuild',
432            command="rpmbuild \
433            --define 'ver git' \
434            --define \"rel `git rev-parse --short HEAD`\" \
435            --define '_topdir %(pwd)/rpm-build' \
436            --define '_builddir %{_topdir}' \
437            --define '_rpmdir %{_topdir}' \
438            --define '_srcrpmdir %{_topdir}' \
439            --define '_rpmfilename %%{NAME}-%%{VERSION}-%%{RELEASE}.%%{ARCH}.rpm' \
440            --define '_specdir %{_topdir}' \
441            --define '_sourcedir  %{_topdir}' \
442            --quiet \
443            -bb misc/packaging/ninja.spec",
444            description='Building RPM..')
445     n.build('rpm', 'rpmbuild',
446             implicit=['ninja','README', 'COPYING', doc('manual.html')])
447     n.newline()
448
449 n.build('all', 'phony', all_targets)
450
451 print 'wrote %s.' % BUILD_FILENAME