source: rtems-source-builder/source-builder/sb/options.py @ c95c245

4.104.114.95
Last change on this file since c95c245 was c95c245, checked in by Chris Johns <chrisj@…>, on 04/15/13 at 00:13:43

PR 2116 - Fix the option parsing to handle both ' ' and '='.

  • Property mode set to 100644
File size: 18.6 KB
Line 
1#
2# RTEMS Tools Project (http://www.rtems.org/)
3# Copyright 2010-2013 Chris Johns (chrisj@rtems.org)
4# All rights reserved.
5#
6# This file is part of the RTEMS Tools package in 'rtems-tools'.
7#
8# Permission to use, copy, modify, and/or distribute this software for any
9# purpose with or without fee is hereby granted, provided that the above
10# copyright notice and this permission notice appear in all copies.
11#
12# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
13# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
14# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
15# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
16# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
17# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
18# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19
20#
21# Determine the defaults and load the specific file.
22#
23
24import glob
25import pprint
26import re
27import os
28import string
29
30import error
31import execute
32import git
33import macros
34import path
35import sys
36
37basepath = 'sb'
38
39class command_line:
40    """Process the command line in a common way for all Tool Builder commands."""
41
42    def __init__(self, argv, optargs, _defaults, command_path):
43        self._long_opts = {
44            # key                 macro                handler            param  defs   init
45            '--prefix'         : ('_prefix',           self._lo_path,     True,  None,  False),
46            '--topdir'         : ('_topdir',           self._lo_path,     True,  None,  False),
47            '--configdir'      : ('_configdir',        self._lo_path,     True,  None,  False),
48            '--builddir'       : ('_builddir',         self._lo_path,     True,  None,  False),
49            '--sourcedir'      : ('_sourcedir',        self._lo_path,     True,  None,  False),
50            '--tmppath'        : ('_tmppath',          self._lo_path,     True,  None,  False),
51            '--jobs'           : ('_jobs',             self._lo_jobs,     True,  'max', True),
52            '--log'            : ('_logfile',          self._lo_string,   True,  None,  False),
53            '--url'            : ('_url_base',         self._lo_string,   True,  None,  False),
54            '--no-download'    : ('_disable_download', self._lo_bool,     False, '0',   True),
55            '--macros'         : ('_macros',           self._lo_string,   True,  None,  False),
56            '--targetcflags'   : ('_targetcflags',     self._lo_string,   True,  None,  False),
57            '--targetcxxflags' : ('_targetcxxflags',   self._lo_string,   True,  None,  False),
58            '--libstdcxxflags' : ('_libstdcxxflags',   self._lo_string,   True,  None,  False),
59            '--force'          : ('_force',            self._lo_bool,     False, '0',   True),
60            '--quiet'          : ('_quiet',            self._lo_bool,     False, '0',   True),
61            '--trace'          : ('_trace',            self._lo_bool,     False, '0',   True),
62            '--dry-run'        : ('_dry_run',          self._lo_bool,     False, '0',   True),
63            '--warn-all'       : ('_warn_all',         self._lo_bool,     False, '0',   True),
64            '--no-clean'       : ('_no_clean',         self._lo_bool,     False, '0',   True),
65            '--keep-going'     : ('_keep_going',       self._lo_bool,     False, '0',   True),
66            '--always-clean'   : ('_always_clean',     self._lo_bool,     False, '0',   True),
67            '--no-install'     : ('_no_install',       self._lo_bool,     False, '0',   True),
68            '--host'           : ('_host',             self._lo_triplets, True,  None,  False),
69            '--build'          : ('_build',            self._lo_triplets, True,  None,  False),
70            '--target'         : ('_target',           self._lo_triplets, True,  None,  False),
71            '--help'           : (None,                self._lo_help,     False, None,  False)
72            }
73
74        self.command_path = command_path
75        self.command_name = path.basename(argv[0])
76        self.argv = argv
77        self.args = argv[1:]
78        self.optargs = optargs
79        self.defaults = _defaults
80        self.opts = { 'params' : [] }
81        for lo in self._long_opts:
82            self.opts[lo[2:]] = self._long_opts[lo][3]
83            if self._long_opts[lo][4]:
84                self.defaults[self._long_opts[lo][0]] = ('none', 'none', self._long_opts[lo][3])
85
86    def __str__(self):
87        def _dict(dd):
88            s = ''
89            ddl = dd.keys()
90            ddl.sort()
91            for d in ddl:
92                s += '  ' + d + ': ' + str(dd[d]) + '\n'
93            return s
94
95        s = 'command: ' + self.command() + \
96            '\nargs: ' + str(self.args) + \
97            '\nopts:\n' + _dict(self.opts)
98
99        return s
100
101    def _lo_string(self, opt, macro, value):
102        if value is None:
103            raise error.general('option requires a value: %s' % (opt))
104        self.opts[opt[2:]] = value
105        self.defaults[macro] = value
106
107    def _lo_path(self, opt, macro, value):
108        if value is None:
109            raise error.general('option requires a path: %s' % (opt))
110        value = path.shell(value)
111        self.opts[opt[2:]] = value
112        self.defaults[macro] = value
113
114    def _lo_jobs(self, opt, macro, value):
115        if value is None:
116            raise error.general('option requires a value: %s' % (opt))
117        ok = False
118        if value in ['max', 'none', 'half']:
119            ok = True
120        else:
121            try:
122                i = int(value)
123                ok = True
124            except:
125                pass
126            if not ok:
127                try:
128                    f = float(value)
129                    ok = True
130                except:
131                    pass
132        if not ok:
133            raise error.general('invalid jobs option: %s' % (value))
134        self.defaults[macro] = value
135        self.opts[opt[2:]] = value
136
137    def _lo_bool(self, opt, macro, value):
138        if value is not None:
139            raise error.general('option does not take a value: %s' % (opt))
140        self.opts[opt[2:]] = '1'
141        self.defaults[macro] = '1'
142
143    def _lo_triplets(self, opt, macro, value):
144        #
145        # This is a target triplet. Run it past config.sub to make make sure it
146        # is ok.  The target triplet is 'cpu-vendor-os'.
147        #
148        e = execute.capture_execution()
149        config_sub = path.join(self.command_path,
150                               basepath, 'config.sub')
151        exit_code, proc, output = e.shell(config_sub + ' ' + value)
152        if exit_code == 0:
153            value = output
154        self.defaults[macro] = ('triplet', 'none', value)
155        self.opts[opt[2:]] = value
156        _cpu = macro + '_cpu'
157        _arch = macro + '_arch'
158        _vendor = macro + '_vendor'
159        _os = macro + '_os'
160        _arch_value = ''
161        _vendor_value = ''
162        _os_value = ''
163        dash = value.find('-')
164        if dash >= 0:
165            _arch_value = value[:dash]
166            value = value[dash + 1:]
167        dash = value.find('-')
168        if dash >= 0:
169            _vendor_value = value[:dash]
170            value = value[dash + 1:]
171        if len(value):
172            _os_value = value
173        self.defaults[_cpu]    = _arch_value
174        self.defaults[_arch]   = _arch_value
175        self.defaults[_vendor] = _vendor_value
176        self.defaults[_os]     = _os_value
177
178    def _lo_help(self, opt, macro, value):
179        self.help()
180
181    def help(self):
182        print '%s: [options] [args]' % (self.command_name)
183        print 'RTEMS Source Builder, an RTEMS Tools Project (c) 2012-2013 Chris Johns'
184        print 'Options and arguments:'
185        print '--force                : Force the build to proceed'
186        print '--quiet                : Quiet output (not used)'
187        print '--trace                : Trace the execution'
188        print '--dry-run              : Do everything but actually run the build'
189        print '--warn-all             : Generate warnings'
190        print '--no-clean             : Do not clean up the build tree'
191        print '--always-clean         : Always clean the build tree, even with an error'
192        print '--jobs                 : Run with specified number of jobs, default: num CPUs.'
193        print '--host                 : Set the host triplet'
194        print '--build                : Set the build triplet'
195        print '--target               : Set the target triplet'
196        print '--prefix path          : Tools build prefix, ie where they are installed'
197        print '--topdir path          : Top of the build tree, default is $PWD'
198        print '--configdir path       : Path to the configuration directory, default: ./config'
199        print '--builddir path        : Path to the build directory, default: ./build'
200        print '--sourcedir path       : Path to the source directory, default: ./source'
201        print '--tmppath path         : Path to the temp directory, default: ./tmp'
202        print '--macros file[,[file]  : Macro format files to load after the defaults'
203        print '--log file             : Log file where all build out is written too'
204        print '--url url[,url]        : URL to look for source'
205        print '--no-download          : Disable the source downloader'
206        print '--no-install           : Do not install the packages to the prefix'
207        print '--targetcflags flags   : List of C flags for the target code'
208        print '--targetcxxflags flags : List of C++ flags for the target code'
209        print '--libstdcxxflags flags : List of C++ flags to build the target libstdc++ code'
210        print '--with-<label>         : Add the --with-<label> to the build'
211        print '--without-<label>      : Add the --without-<label> to the build'
212        if self.optargs:
213            for a in self.optargs:
214                print '%-22s : %s' % (a, self.optargs[a])
215        raise error.exit()
216
217    def process(self):
218        arg = 0
219        while arg < len(self.args):
220            a = self.args[arg]
221            if a == '-?':
222                self.help()
223            elif a.startswith('--'):
224                los = a.split('=')
225                lo = los[0]
226                if lo in self._long_opts:
227                    long_opt = self._long_opts[lo]
228                    if len(los) == 1:
229                        if long_opt[2]:
230                            if arg == len(self.args) - 1:
231                                raise error.general('option requires a parameter: %s' % (lo))
232                            arg += 1
233                            value = self.args[arg]
234                        else:
235                            value = None
236                    else:
237                        value = '='.join(los[1:])
238                    long_opt[1](lo, long_opt[0], value)
239            else:
240                self.opts['params'].append(a)
241            arg += 1
242
243    def post_process(self):
244        # Must have a host
245        if self.defaults['_host'] == self.defaults['nil']:
246            raise error.general('host not set')
247        # Handle the jobs for make
248        if '_ncpus' not in self.defaults:
249            raise error.general('host number of CPUs not set')
250        ncpus = self.jobs(self.defaults['_ncpus'])
251        if ncpus > 1:
252            self.defaults['_smp_mflags'] = '-j %d' % (ncpus)
253        else:
254            self.defaults['_smp_mflags'] = self.defaults['nil']
255        # Load user macro files
256        um = self.user_macros()
257        if um:
258            checked = path.exists(um)
259            if False in checked:
260                raise error.general('macro file not found: %s' % (um[checked.index(False)]))
261            for m in um:
262                self.defaults.load(m)
263        # Check the prefix permission
264        if not self.no_install() and not path.iswritable(self.defaults['_prefix']):
265            raise error.general('prefix is not writable: %s' % (path.host(self.defaults['_prefix'])))
266
267    def command(self):
268        return path.join(self.command_path, self.command_name)
269
270    def force(self):
271        return self.opts['force'] != '0'
272
273    def dry_run(self):
274        return self.opts['dry-run'] != '0'
275
276    def set_dry_run(self):
277        self.opts['dry-run'] = '1'
278
279    def quiet(self):
280        return self.opts['quiet'] != '0'
281
282    def trace(self):
283        return self.opts['trace'] != '0'
284
285    def warn_all(self):
286        return self.opts['warn-all'] != '0'
287
288    def keep_going(self):
289        return self.opts['keep-going'] != '0'
290
291    def no_clean(self):
292        return self.opts['no-clean'] != '0'
293
294    def always_clean(self):
295        return self.opts['always-clean'] != '0'
296
297    def no_install(self):
298        return self.opts['no-install'] != '0'
299
300    def user_macros(self):
301        #
302        # Return something even if it does not exist.
303        #
304        if self.opts['macros'] is None:
305            return None
306        um = []
307        configs = self.defaults.expand('%{_configdir}').split(':')
308        for m in self.opts['macros'].split(','):
309            if path.exists(m):
310                um += [m]
311            else:
312                # Get the expanded config macros then check them.
313                cm = path.expand(m, configs)
314                ccm = path.exists(cm)
315                if True in ccm:
316                    # Pick the first found
317                    um += [cm[ccm.index(True)]]
318                else:
319                    um += [m]
320        return um if len(um) else None
321
322    def jobs(self, cpus):
323        cpus = int(cpus)
324        if self.opts['jobs'] == 'none':
325            cpus = 0
326        elif self.opts['jobs'] == 'max':
327            pass
328        elif self.opts['jobs'] == 'half':
329            cpus = cpus / 2
330        else:
331            ok = False
332            try:
333                i = int(self.opts['jobs'])
334                cpus = i
335                ok = True
336            except:
337                pass
338            if not ok:
339                try:
340                    f = float(self.opts['jobs'])
341                    cpus = f * cpus
342                    ok = True
343                except:
344                    pass
345                if not ok:
346                    raise error.internal('bad jobs option: %s' % (self.opts['jobs']))
347        if cpus <= 0:
348            cpu = 1
349        return cpus
350
351    def params(self):
352        return self.opts['params']
353
354    def get_arg(self, arg):
355        if not arg in self.optargs:
356            raise error.internal('bad arg: %s' % (arg))
357        for a in self.args:
358            sa = a.split('=')
359            if sa[0].startswith(arg):
360                return sa
361        return None
362
363    def get_config_files(self, config):
364        #
365        # Convert to shell paths and return shell paths.
366        #
367        # @fixme should this use a passed in set of defaults and not
368        #        not the initial set of values ?
369        #
370        config = path.shell(config)
371        if '*' in config or '?' in config:
372            print config
373            configdir = path.dirname(config)
374            configbase = path.basename(config)
375            if len(configbase) == 0:
376                configbase = '*'
377            if not configbase.endswith('.cfg'):
378                configbase = configbase + '.cfg'
379            if len(configdir) == 0:
380                configdir = self.macros.expand(self.defaults['_configdir'])
381            configs = []
382            for cp in configdir.split(':'):
383                hostconfigdir = path.host(cp)
384                for f in glob.glob(os.path.join(hostconfigdir, configbase)):
385                    configs += path.shell(f)
386        else:
387            configs = [config]
388        return configs
389
390    def config_files(self):
391        configs = []
392        for config in self.opts['params']:
393            configs.extend(self.get_config_files(config))
394        return configs
395
396    def logfiles(self):
397        if 'log' in self.opts and self.opts['log'] is not None:
398            return self.opts['log'].split(',')
399        return ['stdout']
400
401    def urls(self):
402        if self.opts['url'] is not None:
403            return self.opts['url'].split(',')
404        return None
405
406    def download_disabled(self):
407        return self.opts['no-download'] != '0'
408
409def load(args, optargs = None, defaults = '%{_sbdir}/defaults.mc'):
410    """
411    Copy the defaults, get the host specific values and merge them overriding
412    any matching defaults, then create an options object to handle the command
413    line merging in any command line overrides. Finally post process the
414    command line.
415    """
416
417    #
418    # The path to this command.
419    #
420    command_path = path.dirname(args[0])
421    if len(command_path) == 0:
422        command_path = '.'
423
424    #
425    # The command line contains the base defaults object all build objects copy
426    # and modify by loading a configuration.
427    #
428    o = command_line(args,
429                     optargs,
430                     macros.macros(name = defaults,
431                                   sbdir = command_path),
432                     command_path)
433
434    overrides = None
435    if os.name == 'nt':
436        import windows
437        overrides = windows.load()
438    elif os.name == 'posix':
439        uname = os.uname()
440        try:
441            if uname[0].startswith('CYGWIN_NT'):
442                import windows
443                overrides = windows.load()
444            elif uname[0] == 'Darwin':
445                import darwin
446                overrides = darwin.load()
447            elif uname[0] == 'FreeBSD':
448                import freebsd
449                overrides = freebsd.load()
450            elif uname[0] == 'Linux':
451                import linux
452                overrides = linux.load()
453        except:
454            pass
455    else:
456        raise error.general('unsupported host type; please add')
457    if overrides is None:
458        raise error.general('no hosts defaults found; please add')
459    for k in overrides:
460        o.defaults[k] = overrides[k]
461
462    o.process()
463    o.post_process()
464
465    repo = git.repo(o.defaults.expand('%{_sbdir}'), o)
466    if repo.valid():
467        repo_valid = '1'
468        repo_head = repo.head()
469        repo_clean = repo.clean()
470        repo_id = repo_head
471        if not repo_clean:
472            repo_id += '-modified'
473    else:
474        repo_valid = '0'
475        repo_head = '%{nil}'
476        repo_clean = '%{nil}'
477        repo_id = 'no-repo'
478    o.defaults['_sbgit_valid'] = repo_valid
479    o.defaults['_sbgit_head']  = repo_head
480    o.defaults['_sbgit_clean'] = str(repo_clean)
481    o.defaults['_sbgit_id']    = repo_id
482    return o
483
484def run(args):
485    try:
486        _opts = load(args = args)
487        print 'Options:'
488        print _opts
489        print 'Defaults:'
490        print _opts.defaults
491    except error.general, gerr:
492        print gerr
493        sys.exit(1)
494    except error.internal, ierr:
495        print ierr
496        sys.exit(1)
497    except error.exit, eerr:
498        pass
499    except KeyboardInterrupt:
500        _notice(opts, 'abort: user terminated')
501        sys.exit(1)
502    sys.exit(0)
503
504if __name__ == '__main__':
505    run(sys.argv)
Note: See TracBrowser for help on using the repository browser.