source: rtems-source-builder/source-builder/sb/options.py @ 2cc7a97

4.104.114.95
Last change on this file since 2cc7a97 was 2cc7a97, checked in by Chris Johns <chrisj@…>, on 04/15/13 at 02:16:26

PR 2117 - Only check the prefix is writable if installing and not a dry run.

  • Property mode set to 100644
File size: 18.4 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
264    def command(self):
265        return path.join(self.command_path, self.command_name)
266
267    def force(self):
268        return self.opts['force'] != '0'
269
270    def dry_run(self):
271        return self.opts['dry-run'] != '0'
272
273    def set_dry_run(self):
274        self.opts['dry-run'] = '1'
275
276    def quiet(self):
277        return self.opts['quiet'] != '0'
278
279    def trace(self):
280        return self.opts['trace'] != '0'
281
282    def warn_all(self):
283        return self.opts['warn-all'] != '0'
284
285    def keep_going(self):
286        return self.opts['keep-going'] != '0'
287
288    def no_clean(self):
289        return self.opts['no-clean'] != '0'
290
291    def always_clean(self):
292        return self.opts['always-clean'] != '0'
293
294    def no_install(self):
295        return self.opts['no-install'] != '0'
296
297    def user_macros(self):
298        #
299        # Return something even if it does not exist.
300        #
301        if self.opts['macros'] is None:
302            return None
303        um = []
304        configs = self.defaults.expand('%{_configdir}').split(':')
305        for m in self.opts['macros'].split(','):
306            if path.exists(m):
307                um += [m]
308            else:
309                # Get the expanded config macros then check them.
310                cm = path.expand(m, configs)
311                ccm = path.exists(cm)
312                if True in ccm:
313                    # Pick the first found
314                    um += [cm[ccm.index(True)]]
315                else:
316                    um += [m]
317        return um if len(um) else None
318
319    def jobs(self, cpus):
320        cpus = int(cpus)
321        if self.opts['jobs'] == 'none':
322            cpus = 0
323        elif self.opts['jobs'] == 'max':
324            pass
325        elif self.opts['jobs'] == 'half':
326            cpus = cpus / 2
327        else:
328            ok = False
329            try:
330                i = int(self.opts['jobs'])
331                cpus = i
332                ok = True
333            except:
334                pass
335            if not ok:
336                try:
337                    f = float(self.opts['jobs'])
338                    cpus = f * cpus
339                    ok = True
340                except:
341                    pass
342                if not ok:
343                    raise error.internal('bad jobs option: %s' % (self.opts['jobs']))
344        if cpus <= 0:
345            cpu = 1
346        return cpus
347
348    def params(self):
349        return self.opts['params']
350
351    def get_arg(self, arg):
352        if not arg in self.optargs:
353            raise error.internal('bad arg: %s' % (arg))
354        for a in self.args:
355            sa = a.split('=')
356            if sa[0].startswith(arg):
357                return sa
358        return None
359
360    def get_config_files(self, config):
361        #
362        # Convert to shell paths and return shell paths.
363        #
364        # @fixme should this use a passed in set of defaults and not
365        #        not the initial set of values ?
366        #
367        config = path.shell(config)
368        if '*' in config or '?' in config:
369            print config
370            configdir = path.dirname(config)
371            configbase = path.basename(config)
372            if len(configbase) == 0:
373                configbase = '*'
374            if not configbase.endswith('.cfg'):
375                configbase = configbase + '.cfg'
376            if len(configdir) == 0:
377                configdir = self.macros.expand(self.defaults['_configdir'])
378            configs = []
379            for cp in configdir.split(':'):
380                hostconfigdir = path.host(cp)
381                for f in glob.glob(os.path.join(hostconfigdir, configbase)):
382                    configs += path.shell(f)
383        else:
384            configs = [config]
385        return configs
386
387    def config_files(self):
388        configs = []
389        for config in self.opts['params']:
390            configs.extend(self.get_config_files(config))
391        return configs
392
393    def logfiles(self):
394        if 'log' in self.opts and self.opts['log'] is not None:
395            return self.opts['log'].split(',')
396        return ['stdout']
397
398    def urls(self):
399        if self.opts['url'] is not None:
400            return self.opts['url'].split(',')
401        return None
402
403    def download_disabled(self):
404        return self.opts['no-download'] != '0'
405
406def load(args, optargs = None, defaults = '%{_sbdir}/defaults.mc'):
407    """
408    Copy the defaults, get the host specific values and merge them overriding
409    any matching defaults, then create an options object to handle the command
410    line merging in any command line overrides. Finally post process the
411    command line.
412    """
413
414    #
415    # The path to this command.
416    #
417    command_path = path.dirname(args[0])
418    if len(command_path) == 0:
419        command_path = '.'
420
421    #
422    # The command line contains the base defaults object all build objects copy
423    # and modify by loading a configuration.
424    #
425    o = command_line(args,
426                     optargs,
427                     macros.macros(name = defaults,
428                                   sbdir = command_path),
429                     command_path)
430
431    overrides = None
432    if os.name == 'nt':
433        import windows
434        overrides = windows.load()
435    elif os.name == 'posix':
436        uname = os.uname()
437        try:
438            if uname[0].startswith('CYGWIN_NT'):
439                import windows
440                overrides = windows.load()
441            elif uname[0] == 'Darwin':
442                import darwin
443                overrides = darwin.load()
444            elif uname[0] == 'FreeBSD':
445                import freebsd
446                overrides = freebsd.load()
447            elif uname[0] == 'Linux':
448                import linux
449                overrides = linux.load()
450        except:
451            pass
452    else:
453        raise error.general('unsupported host type; please add')
454    if overrides is None:
455        raise error.general('no hosts defaults found; please add')
456    for k in overrides:
457        o.defaults[k] = overrides[k]
458
459    o.process()
460    o.post_process()
461
462    repo = git.repo(o.defaults.expand('%{_sbdir}'), o)
463    if repo.valid():
464        repo_valid = '1'
465        repo_head = repo.head()
466        repo_clean = repo.clean()
467        repo_id = repo_head
468        if not repo_clean:
469            repo_id += '-modified'
470    else:
471        repo_valid = '0'
472        repo_head = '%{nil}'
473        repo_clean = '%{nil}'
474        repo_id = 'no-repo'
475    o.defaults['_sbgit_valid'] = repo_valid
476    o.defaults['_sbgit_head']  = repo_head
477    o.defaults['_sbgit_clean'] = str(repo_clean)
478    o.defaults['_sbgit_id']    = repo_id
479    return o
480
481def run(args):
482    try:
483        _opts = load(args = args)
484        print 'Options:'
485        print _opts
486        print 'Defaults:'
487        print _opts.defaults
488    except error.general, gerr:
489        print gerr
490        sys.exit(1)
491    except error.internal, ierr:
492        print ierr
493        sys.exit(1)
494    except error.exit, eerr:
495        pass
496    except KeyboardInterrupt:
497        _notice(opts, 'abort: user terminated')
498        sys.exit(1)
499    sys.exit(0)
500
501if __name__ == '__main__':
502    run(sys.argv)
Note: See TracBrowser for help on using the repository browser.