~vcs-imports/kupfer/master-new

« back to all changes in this revision

Viewing changes to waflib/Options.py

  • Committer: Ulrik Sverdrup
  • Date: 2012-02-26 17:32:06 UTC
  • mto: This revision was merged to the branch mainline in revision 2918.
  • Revision ID: git-v1:684a1e79e28fa3d9e346bdf2c1659e7d2c6e7718
Add waf-light and waflib from waf-1.6.11

http://code.google.com/p/waf/
Acquired from: http://waf.googlecode.com/files/waf-1.6.11.tar.bz2

"""
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

3. The name of the author may not be used to endorse or promote products
   derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
"""

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/env python
 
2
# encoding: utf-8
 
3
# Scott Newton, 2005 (scottn)
 
4
# Thomas Nagy, 2006-2010 (ita)
 
5
 
 
6
"""
 
7
Support for waf command-line options
 
8
 
 
9
Provides default command-line options,
 
10
as well as custom ones, used by the ``options`` wscript function.
 
11
 
 
12
"""
 
13
 
 
14
import os, tempfile, optparse, sys, re
 
15
from waflib import Logs, Utils, Context
 
16
 
 
17
cmds = 'distclean configure build install clean uninstall check dist distcheck'.split()
 
18
"""
 
19
Constant representing the default waf commands displayed in::
 
20
 
 
21
        $ waf --help
 
22
 
 
23
"""
 
24
 
 
25
options = {}
 
26
"""
 
27
A dictionary representing the command-line options::
 
28
 
 
29
        $ waf --foo=bar
 
30
 
 
31
"""
 
32
 
 
33
commands = []
 
34
"""
 
35
List of commands to execute extracted from the command-line. This list is consumed during the execution, see :py:func:`waflib.Scripting.run_commands`.
 
36
"""
 
37
 
 
38
lockfile = os.environ.get('WAFLOCK', '.lock-waf_%s_build' % sys.platform)
 
39
try: cache_global = os.path.abspath(os.environ['WAFCACHE'])
 
40
except KeyError: cache_global = ''
 
41
platform = Utils.unversioned_sys_platform()
 
42
 
 
43
 
 
44
class opt_parser(optparse.OptionParser):
 
45
        """
 
46
        Command-line options parser.
 
47
        """
 
48
        def __init__(self, ctx):
 
49
                optparse.OptionParser.__init__(self, conflict_handler="resolve", version='waf %s (%s)' % (Context.WAFVERSION, Context.WAFREVISION))
 
50
 
 
51
                self.formatter.width = Logs.get_term_cols()
 
52
                p = self.add_option
 
53
                self.ctx = ctx
 
54
 
 
55
                jobs = ctx.jobs()
 
56
                p('-j', '--jobs',     dest='jobs',    default=jobs, type='int', help='amount of parallel jobs (%r)' % jobs)
 
57
                p('-k', '--keep',     dest='keep',    default=0,     action='count', help='keep running happily even if errors are found')
 
58
                p('-v', '--verbose',  dest='verbose', default=0,     action='count', help='verbosity level -v -vv or -vvv [default: 0]')
 
59
                p('--nocache',        dest='nocache', default=False, action='store_true', help='ignore the WAFCACHE (if set)')
 
60
                p('--zones',          dest='zones',   default='',    action='store', help='debugging zones (task_gen, deps, tasks, etc)')
 
61
 
 
62
                gr = optparse.OptionGroup(self, 'configure options')
 
63
                self.add_option_group(gr)
 
64
 
 
65
                gr.add_option('-o', '--out', action='store', default='', help='build dir for the project', dest='out')
 
66
                gr.add_option('-t', '--top', action='store', default='', help='src dir for the project', dest='top')
 
67
 
 
68
                default_prefix = os.environ.get('PREFIX')
 
69
                if not default_prefix:
 
70
                        if platform == 'win32':
 
71
                                d = tempfile.gettempdir()
 
72
                                default_prefix = d[0].upper() + d[1:]
 
73
                                # win32 preserves the case, but gettempdir does not
 
74
                        else:
 
75
                                default_prefix = '/usr/local/'
 
76
                gr.add_option('--prefix', dest='prefix', default=default_prefix, help='installation prefix [default: %r]' % default_prefix)
 
77
                gr.add_option('--download', dest='download', default=False, action='store_true', help='try to download the tools if missing')
 
78
 
 
79
 
 
80
                gr = optparse.OptionGroup(self, 'build and install options')
 
81
                self.add_option_group(gr)
 
82
 
 
83
                gr.add_option('-p', '--progress', dest='progress_bar', default=0, action='count', help= '-p: progress bar; -pp: ide output')
 
84
                gr.add_option('--targets',        dest='targets', default='', action='store', help='task generators, e.g. "target1,target2"')
 
85
 
 
86
                gr = optparse.OptionGroup(self, 'step options')
 
87
                self.add_option_group(gr)
 
88
                gr.add_option('--files',          dest='files', default='', action='store', help='files to process, by regexp, e.g. "*/main.c,*/test/main.o"')
 
89
 
 
90
                default_destdir = os.environ.get('DESTDIR', '')
 
91
                gr = optparse.OptionGroup(self, 'install/uninstall options')
 
92
                self.add_option_group(gr)
 
93
                gr.add_option('--destdir', help='installation root [default: %r]' % default_destdir, default=default_destdir, dest='destdir')
 
94
                gr.add_option('-f', '--force', dest='force', default=False, action='store_true', help='force file installation')
 
95
 
 
96
        def get_usage(self):
 
97
                """
 
98
                Return the message to print on ``waf --help``
 
99
                """
 
100
                cmds_str = {}
 
101
                for cls in Context.classes:
 
102
                        if not cls.cmd or cls.cmd == 'options':
 
103
                                continue
 
104
 
 
105
                        s = cls.__doc__ or ''
 
106
                        cmds_str[cls.cmd] = s
 
107
 
 
108
                if Context.g_module:
 
109
                        for (k, v) in Context.g_module.__dict__.items():
 
110
                                if k in ['options', 'init', 'shutdown']:
 
111
                                        continue
 
112
 
 
113
                                if type(v) is type(Context.create_context):
 
114
                                        if v.__doc__ and not k.startswith('_'):
 
115
                                                cmds_str[k] = v.__doc__
 
116
 
 
117
                just = 0
 
118
                for k in cmds_str:
 
119
                        just = max(just, len(k))
 
120
 
 
121
                lst = ['  %s: %s' % (k.ljust(just), v) for (k, v) in cmds_str.items()]
 
122
                lst.sort()
 
123
                ret = '\n'.join(lst)
 
124
 
 
125
                return '''waf [commands] [options]
 
126
 
 
127
Main commands (example: ./waf build -j4)
 
128
%s
 
129
''' % ret
 
130
 
 
131
 
 
132
class OptionsContext(Context.Context):
 
133
        """
 
134
        Collect custom options from wscript files and parses the command line.
 
135
        Set the global :py:const:`waflib.Options.commands` and :py:const:`waflib.Options.options` values.
 
136
        """
 
137
 
 
138
        cmd = 'options'
 
139
        fun = 'options'
 
140
 
 
141
        def __init__(self, **kw):
 
142
                super(OptionsContext, self).__init__(**kw)
 
143
 
 
144
                self.parser = opt_parser(self)
 
145
                """Instance of :py:class:`waflib.Options.opt_parser`"""
 
146
 
 
147
                self.option_groups = {}
 
148
 
 
149
        def jobs(self):
 
150
                """
 
151
                Find the amount of cpu cores to set the default amount of tasks executed in parallel. At
 
152
                runtime the options can be obtained from :py:const:`waflib.Options.options` ::
 
153
 
 
154
                        from waflib.Options import options
 
155
                        njobs = options.jobs
 
156
 
 
157
                :return: the amount of cpu cores
 
158
                :rtype: int
 
159
                """
 
160
                count = int(os.environ.get('JOBS', 0))
 
161
                if count < 1:
 
162
                        if 'NUMBER_OF_PROCESSORS' in os.environ:
 
163
                                # on Windows, use the NUMBER_OF_PROCESSORS environment variable
 
164
                                count = int(os.environ.get('NUMBER_OF_PROCESSORS', 1))
 
165
                        else:
 
166
                                # on everything else, first try the POSIX sysconf values
 
167
                                if hasattr(os, 'sysconf_names'):
 
168
                                        if 'SC_NPROCESSORS_ONLN' in os.sysconf_names:
 
169
                                                count = int(os.sysconf('SC_NPROCESSORS_ONLN'))
 
170
                                        elif 'SC_NPROCESSORS_CONF' in os.sysconf_names:
 
171
                                                count = int(os.sysconf('SC_NPROCESSORS_CONF'))
 
172
                                if not count and os.name not in ('nt', 'java'):
 
173
                                        try:
 
174
                                                tmp = self.cmd_and_log(['sysctl', '-n', 'hw.ncpu'], quiet=0)
 
175
                                        except Exception:
 
176
                                                pass
 
177
                                        else:
 
178
                                                if re.match('^[0-9]+$', tmp):
 
179
                                                        count = int(tmp)
 
180
                if count < 1:
 
181
                        count = 1
 
182
                elif count > 1024:
 
183
                        count = 1024
 
184
                return count
 
185
 
 
186
        def add_option(self, *k, **kw):
 
187
                """
 
188
                Wrapper for optparse.add_option::
 
189
 
 
190
                        def options(ctx):
 
191
                                ctx.add_option('-u', '--use', dest='use', default=False, action='store_true',
 
192
                                        help='a boolean option')
 
193
                """
 
194
                self.parser.add_option(*k, **kw)
 
195
 
 
196
        def add_option_group(self, *k, **kw):
 
197
                """
 
198
                Wrapper for optparse.add_option_group::
 
199
 
 
200
                        def options(ctx):
 
201
                                ctx.add_option_group('some options')
 
202
                                gr.add_option('-u', '--use', dest='use', default=False, action='store_true')
 
203
                """
 
204
                try:
 
205
                        gr = self.option_groups[k[0]]
 
206
                except:
 
207
                        gr = self.parser.add_option_group(*k, **kw)
 
208
                self.option_groups[k[0]] = gr
 
209
                return gr
 
210
 
 
211
        def get_option_group(self, opt_str):
 
212
                """
 
213
                Wrapper for optparse.get_option_group::
 
214
 
 
215
                        def options(ctx):
 
216
                                gr = ctx.get_option_group('configure options')
 
217
                                gr.add_option('-o', '--out', action='store', default='',
 
218
                                        help='build dir for the project', dest='out')
 
219
 
 
220
                """
 
221
                try:
 
222
                        return self.option_groups[opt_str]
 
223
                except KeyError:
 
224
                        for group in self.parser.option_groups:
 
225
                                if group.title == opt_str:
 
226
                                        return group
 
227
                        return None
 
228
 
 
229
        def parse_args(self, _args=None):
 
230
                """
 
231
                Parse arguments from a list (not bound to the command-line).
 
232
 
 
233
                :param _args: arguments
 
234
                :type _args: list of strings
 
235
                """
 
236
                global options, commands
 
237
                (options, leftover_args) = self.parser.parse_args(args=_args)
 
238
                commands = leftover_args
 
239
 
 
240
                if options.destdir:
 
241
                        options.destdir = os.path.abspath(os.path.expanduser(options.destdir))
 
242
 
 
243
                if options.verbose >= 1:
 
244
                        self.load('errcheck')
 
245
 
 
246
        def execute(self):
 
247
                """
 
248
                See :py:func:`waflib.Context.Context.execute`
 
249
                """
 
250
                super(OptionsContext, self).execute()
 
251
                self.parse_args()
 
252