コード例 #1
0
ファイル: __init__.py プロジェクト: bslassey/spidernode
    def __init__(self,
                 config,
                 environ=os.environ,
                 argv=sys.argv,
                 stdout=sys.stdout,
                 stderr=sys.stderr):
        dict.__setitem__(self, '__builtins__', self.BUILTINS)

        self._paths = []
        self._templates = set()
        # Store the real function and its dependencies, behind each
        # DummyFunction generated from @depends.
        self._depends = {}
        self._seen = set()

        self._options = OrderedDict()
        # Store the raw values returned by @depends functions
        self._results = {}
        # Store values for each Option, as per returned by Option.get_value
        self._option_values = {}
        # Store raw option (as per command line or environment) for each Option
        self._raw_options = {}

        # Store options added with `imply_option`, and the reason they were
        # added (which can either have been given to `imply_option`, or
        # inferred.
        self._implied_options = {}

        # Store all results from _prepare_function
        self._prepared_functions = set()

        self._helper = CommandLineHelper(environ, argv)

        assert isinstance(config, dict)
        self._config, self._stdout, self._stderr = config, stdout, stderr

        self._help = None
        self._help_option = self.option_impl('--help',
                                             help='print this message')
        self._seen.add(self._help_option)
        # self._option_impl('--help') will have set this if --help was on the
        # command line.
        if self._option_values[self._help_option]:
            self._help = HelpFormatter(argv[0])
            self._help.add(self._help_option)
コード例 #2
0
ファイル: test_options.py プロジェクト: MekliCZ/positron
    def test_basic(self):
        helper = CommandLineHelper({}, ['cmd', '--foo', '--bar'])

        self.assertEquals(['--foo', '--bar'], list(helper))

        helper.add('--enable-qux')

        self.assertEquals(['--foo', '--bar', '--enable-qux'], list(helper))

        value, option = helper.handle(Option('--bar'))
        self.assertEquals(['--foo', '--enable-qux'], list(helper))
        self.assertEquals(PositiveOptionValue(), value)
        self.assertEquals('--bar', option)

        value, option = helper.handle(Option('--baz'))
        self.assertEquals(['--foo', '--enable-qux'], list(helper))
        self.assertEquals(NegativeOptionValue(), value)
        self.assertEquals(None, option)
コード例 #3
0
ファイル: __init__.py プロジェクト: Natim/gecko-dev
    def __init__(self, config, environ=os.environ, argv=sys.argv,
                 stdout=sys.stdout, stderr=sys.stderr):
        dict.__setitem__(self, '__builtins__', self.BUILTINS)

        self._paths = []
        self._templates = set()
        # Store the real function and its dependencies, behind each
        # DummyFunction generated from @depends.
        self._depends = {}
        self._seen = set()

        self._options = OrderedDict()
        # Store the raw values returned by @depends functions
        self._results = {}
        # Store values for each Option, as per returned by Option.get_value
        self._option_values = {}
        # Store raw option (as per command line or environment) for each Option
        self._raw_options = {}

        # Store options added with `imply_option`, and the reason they were
        # added (which can either have been given to `imply_option`, or
        # inferred.
        self._implied_options = {}

        # Store all results from _prepare_function
        self._prepared_functions = set()

        self._helper = CommandLineHelper(environ, argv)

        assert isinstance(config, dict)
        self._config, self._stdout, self._stderr = config, stdout, stderr

        self._help = None
        self._help_option = self.option_impl('--help',
                                             help='print this message')
        self._seen.add(self._help_option)
        # self._option_impl('--help') will have set this if --help was on the
        # command line.
        if self._option_values[self._help_option]:
            self._help = HelpFormatter(argv[0])
            self._help.add(self._help_option)
コード例 #4
0
    def test_basic(self):
        helper = CommandLineHelper({}, ["cmd", "--foo", "--bar"])

        self.assertEquals(["--foo", "--bar"], list(helper))

        helper.add("--enable-qux")

        self.assertEquals(["--foo", "--bar", "--enable-qux"], list(helper))

        value, option = helper.handle(Option("--bar"))
        self.assertEquals(["--foo", "--enable-qux"], list(helper))
        self.assertEquals(PositiveOptionValue(), value)
        self.assertEquals("--bar", option)

        value, option = helper.handle(Option("--baz"))
        self.assertEquals(["--foo", "--enable-qux"], list(helper))
        self.assertEquals(NegativeOptionValue(), value)
        self.assertEquals(None, option)

        with self.assertRaises(AssertionError):
            CommandLineHelper({}, ["--foo", "--bar"])
コード例 #5
0
    def test_basic(self):
        helper = CommandLineHelper({}, ['cmd', '--foo', '--bar'])

        self.assertEquals(['--foo', '--bar'], list(helper))

        helper.add('--enable-qux')

        self.assertEquals(['--foo', '--bar', '--enable-qux'], list(helper))

        value, option = helper.handle(Option('--bar'))
        self.assertEquals(['--foo', '--enable-qux'], list(helper))
        self.assertEquals(PositiveOptionValue(), value)
        self.assertEquals('--bar', option)

        value, option = helper.handle(Option('--baz'))
        self.assertEquals(['--foo', '--enable-qux'], list(helper))
        self.assertEquals(NegativeOptionValue(), value)
        self.assertEquals(None, option)

        with self.assertRaises(AssertionError):
            CommandLineHelper({}, ['--foo', '--bar'])
コード例 #6
0
ファイル: __init__.py プロジェクト: linclark/gecko-dev
    def __init__(self, config, environ=os.environ, argv=sys.argv,
                 stdout=sys.stdout, stderr=sys.stderr):
        dict.__setitem__(self, '__builtins__', self.BUILTINS)

        self._paths = []
        self._templates = set()
        self._depends = {}
        self._seen = set()

        self._options = OrderedDict()
        # Store the raw values returned by @depends functions
        self._results = {}
        # Store several kind of information:
        # - value for each Option, as per returned by Option.get_value
        # - raw option (as per command line or environment) for each value
        # - config set by each @depends function
        self._db = {}

        # Store options added with `imply_option`, and the reason they were
        # added (which can either have been given to `imply_option`, or
        # infered.
        self._implied_options = {}

        self._helper = CommandLineHelper(environ, argv)

        self._config, self._stdout, self._stderr = config, stdout, stderr

        self._help = None
        self._help_option = self.option_impl('--help',
                                             help='print this message')
        self._seen.add(self._help_option)
        # self._option_impl('--help') will have set this if --help was on the
        # command line.
        if self._db[self._help_option]:
            self._help = HelpFormatter(argv[0])
            self._help.add(self._help_option)
コード例 #7
0
    def test_possible_origins(self):
        with self.assertRaises(InvalidOptionError):
            Option('--foo', possible_origins='command-line')

        helper = CommandLineHelper({'BAZ': '1'}, ['cmd', '--foo', '--bar'])
        foo = Option('--foo',
                     possible_origins=('command-line',))
        value, option = helper.handle(foo)
        self.assertEquals(PositiveOptionValue(), value)
        self.assertEquals('command-line', value.origin)
        self.assertEquals('--foo', option)

        bar = Option('--bar',
                     possible_origins=('mozconfig',))
        with self.assertRaisesRegexp(InvalidOptionError,
            "--bar can not be set by command-line. Values are accepted from: mozconfig"):
            helper.handle(bar)

        baz = Option(env='BAZ',
                     possible_origins=('implied',))
        with self.assertRaisesRegexp(InvalidOptionError,
            "BAZ=1 can not be set by environment. Values are accepted from: implied"):
            helper.handle(baz)
コード例 #8
0
    def test_possible_origins(self):
        with self.assertRaises(InvalidOptionError):
            Option("--foo", possible_origins="command-line")

        helper = CommandLineHelper({"BAZ": "1"}, ["cmd", "--foo", "--bar"])
        foo = Option("--foo", possible_origins=("command-line",))
        value, option = helper.handle(foo)
        self.assertEquals(PositiveOptionValue(), value)
        self.assertEquals("command-line", value.origin)
        self.assertEquals("--foo", option)

        bar = Option("--bar", possible_origins=("mozconfig",))
        with self.assertRaisesRegexp(
            InvalidOptionError,
            "--bar can not be set by command-line. Values are accepted from: mozconfig",
        ):
            helper.handle(bar)

        baz = Option(env="BAZ", possible_origins=("implied",))
        with self.assertRaisesRegexp(
            InvalidOptionError,
            "BAZ=1 can not be set by environment. Values are accepted from: implied",
        ):
            helper.handle(baz)
コード例 #9
0
    def test_possible_origins(self):
        with self.assertRaises(InvalidOptionError):
            Option('--foo', possible_origins='command-line')

        helper = CommandLineHelper({'BAZ': '1'}, ['cmd', '--foo', '--bar'])
        foo = Option('--foo',
                     possible_origins=('command-line',))
        value, option = helper.handle(foo)
        self.assertEquals(PositiveOptionValue(), value)
        self.assertEquals('command-line', value.origin)
        self.assertEquals('--foo', option)

        bar = Option('--bar',
                     possible_origins=('mozconfig',))
        with self.assertRaisesRegexp(InvalidOptionError,
            "--bar can not be set by command-line. Values are accepted from: mozconfig"):
            helper.handle(bar)

        baz = Option(env='BAZ',
                     possible_origins=('implied',))
        with self.assertRaisesRegexp(InvalidOptionError,
            "BAZ=1 can not be set by environment. Values are accepted from: implied"):
            helper.handle(baz)
コード例 #10
0
    def test_precedence(self):
        foo = Option("--with-foo", nargs="*")
        helper = CommandLineHelper({}, ["cmd", "--with-foo=a,b"])
        value, option = helper.handle(foo)
        self.assertEquals(PositiveOptionValue(("a", "b")), value)
        self.assertEquals("command-line", value.origin)
        self.assertEquals("--with-foo=a,b", option)

        helper = CommandLineHelper({}, ["cmd", "--with-foo=a,b", "--without-foo"])
        value, option = helper.handle(foo)
        self.assertEquals(NegativeOptionValue(), value)
        self.assertEquals("command-line", value.origin)
        self.assertEquals("--without-foo", option)

        helper = CommandLineHelper({}, ["cmd", "--without-foo", "--with-foo=a,b"])
        value, option = helper.handle(foo)
        self.assertEquals(PositiveOptionValue(("a", "b")), value)
        self.assertEquals("command-line", value.origin)
        self.assertEquals("--with-foo=a,b", option)

        foo = Option("--with-foo", env="FOO", nargs="*")
        helper = CommandLineHelper({"FOO": ""}, ["cmd", "--with-foo=a,b"])
        value, option = helper.handle(foo)
        self.assertEquals(PositiveOptionValue(("a", "b")), value)
        self.assertEquals("command-line", value.origin)
        self.assertEquals("--with-foo=a,b", option)

        helper = CommandLineHelper({"FOO": "a,b"}, ["cmd", "--without-foo"])
        value, option = helper.handle(foo)
        self.assertEquals(NegativeOptionValue(), value)
        self.assertEquals("command-line", value.origin)
        self.assertEquals("--without-foo", option)

        helper = CommandLineHelper({"FOO": ""}, ["cmd", "--with-bar=a,b"])
        value, option = helper.handle(foo)
        self.assertEquals(NegativeOptionValue(), value)
        self.assertEquals("environment", value.origin)
        self.assertEquals("FOO=", option)

        helper = CommandLineHelper({"FOO": "a,b"}, ["cmd", "--without-bar"])
        value, option = helper.handle(foo)
        self.assertEquals(PositiveOptionValue(("a", "b")), value)
        self.assertEquals("environment", value.origin)
        self.assertEquals("FOO=a,b", option)

        helper = CommandLineHelper({}, ["cmd", "--with-foo=a,b", "FOO="])
        value, option = helper.handle(foo)
        self.assertEquals(NegativeOptionValue(), value)
        self.assertEquals("command-line", value.origin)
        self.assertEquals("FOO=", option)

        helper = CommandLineHelper({}, ["cmd", "--without-foo", "FOO=a,b"])
        value, option = helper.handle(foo)
        self.assertEquals(PositiveOptionValue(("a", "b")), value)
        self.assertEquals("command-line", value.origin)
        self.assertEquals("FOO=a,b", option)

        helper = CommandLineHelper({}, ["cmd", "FOO=", "--with-foo=a,b"])
        value, option = helper.handle(foo)
        self.assertEquals(PositiveOptionValue(("a", "b")), value)
        self.assertEquals("command-line", value.origin)
        self.assertEquals("--with-foo=a,b", option)

        helper = CommandLineHelper({}, ["cmd", "FOO=a,b", "--without-foo"])
        value, option = helper.handle(foo)
        self.assertEquals(NegativeOptionValue(), value)
        self.assertEquals("command-line", value.origin)
        self.assertEquals("--without-foo", option)
コード例 #11
0
ファイル: __init__.py プロジェクト: MekliCZ/positron
    def __init__(self, config, environ=os.environ, argv=sys.argv,
                 stdout=sys.stdout, stderr=sys.stderr, logger=None):
        dict.__setitem__(self, '__builtins__', self.BUILTINS)

        self._paths = []
        self._all_paths = set()
        self._templates = set()
        # Store the real function and its dependencies, behind each
        # DependsFunction generated from @depends.
        self._depends = {}
        self._seen = set()
        # Store the @imports added to a given function.
        self._imports = {}

        self._options = OrderedDict()
        # Store raw option (as per command line or environment) for each Option
        self._raw_options = OrderedDict()

        # Store options added with `imply_option`, and the reason they were
        # added (which can either have been given to `imply_option`, or
        # inferred. Their order matters, so use a list.
        self._implied_options = []

        # Store all results from _prepare_function
        self._prepared_functions = set()

        # Queue of functions to execute, with their arguments
        self._execution_queue = []

        self._helper = CommandLineHelper(environ, argv)

        assert isinstance(config, dict)
        self._config = config

        if logger is None:
            logger = moz_logger = logging.getLogger('moz.configure')
            logger.setLevel(logging.DEBUG)
            formatter = logging.Formatter('%(levelname)s: %(message)s')
            handler = ConfigureOutputHandler(stdout, stderr)
            handler.setFormatter(formatter)
            queue_debug = handler.queue_debug
            logger.addHandler(handler)

        else:
            assert isinstance(logger, logging.Logger)
            moz_logger = None
            @contextmanager
            def queue_debug():
                yield

        log_namespace = {
            k: getattr(logger, k)
            for k in ('debug', 'info', 'warning', 'error')
        }
        log_namespace['queue_debug'] = queue_debug
        self.log_impl = ReadOnlyNamespace(**log_namespace)

        self._help = None
        self._help_option = self.option_impl('--help',
                                             help='print this message')
        self._seen.add(self._help_option)
        if self._value_for(self._help_option):
            self._help = HelpFormatter(argv[0])
            self._help.add(self._help_option)
        elif moz_logger:
            handler = logging.FileHandler('config.log', mode='w', delay=True)
            handler.setFormatter(formatter)
            logger.addHandler(handler)
コード例 #12
0
ファイル: __init__.py プロジェクト: wizAmit/gecko-dev
class ConfigureSandbox(dict):
    """Represents a sandbox for executing Python code for build configuration.
    This is a different kind of sandboxing than the one used for moz.build
    processing.

    The sandbox has 8 primitives:
    - option
    - depends
    - template
    - imports
    - include
    - set_config
    - set_define
    - imply_option

    `option`, `include`, `set_config`, `set_define` and `imply_option` are
    functions. `depends`, `template`, and `imports` are decorators.

    These primitives are declared as name_impl methods to this class and
    the mapping name -> name_impl is done automatically in __getitem__.

    Additional primitives should be frowned upon to keep the sandbox itself as
    simple as possible. Instead, helpers should be created within the sandbox
    with the existing primitives.

    The sandbox is given, at creation, a dict where the yielded configuration
    will be stored.

        config = {}
        sandbox = ConfigureSandbox(config)
        sandbox.run(path)
        do_stuff(config)
    """

    # The default set of builtins. We expose unicode as str to make sandboxed
    # files more python3-ready.
    BUILTINS = ReadOnlyDict(
        {
            b: __builtins__[b]
            for b in ('None', 'False', 'True', 'int', 'bool', 'any', 'all',
                      'len', 'list', 'tuple', 'set', 'dict', 'isinstance')
        },
        __import__=forbidden_import,
        str=unicode)

    # Expose a limited set of functions from os.path
    OS = ReadOnlyNamespace(path=ReadOnlyNamespace(
        **{
            k: getattr(mozpath, k, getattr(os.path, k))
            for k in ('abspath', 'basename', 'dirname', 'exists', 'isabs',
                      'isdir', 'isfile', 'join', 'normpath', 'realpath',
                      'relpath')
        }))

    def __init__(self,
                 config,
                 environ=os.environ,
                 argv=sys.argv,
                 stdout=sys.stdout,
                 stderr=sys.stderr,
                 logger=None):
        dict.__setitem__(self, '__builtins__', self.BUILTINS)

        self._paths = []
        self._templates = set()
        # Store the real function and its dependencies, behind each
        # DependsFunction generated from @depends.
        self._depends = {}
        self._seen = set()
        # Store the @imports added to a given function.
        self._imports = {}

        self._options = OrderedDict()
        # Store the raw values returned by @depends functions
        self._results = {}
        # Store values for each Option, as per returned by Option.get_value
        self._option_values = {}
        # Store raw option (as per command line or environment) for each Option
        self._raw_options = {}

        # Store options added with `imply_option`, and the reason they were
        # added (which can either have been given to `imply_option`, or
        # inferred.
        self._implied_options = {}

        # Store all results from _prepare_function
        self._prepared_functions = set()

        self._helper = CommandLineHelper(environ, argv)

        assert isinstance(config, dict)
        self._config = config

        if logger is None:
            logger = moz_logger = logging.getLogger('moz.configure')
            logger.setLevel(logging.DEBUG)
            formatter = logging.Formatter('%(levelname)s: %(message)s')
            handler = ConfigureOutputHandler(stdout, stderr)
            handler.setFormatter(formatter)
            queue_debug = handler.queue_debug
            logger.addHandler(handler)

        else:
            assert isinstance(logger, logging.Logger)
            moz_logger = None

            @contextmanager
            def queue_debug():
                yield

        log_namespace = {
            k: getattr(logger, k)
            for k in ('debug', 'info', 'warning', 'error')
        }
        log_namespace['queue_debug'] = queue_debug
        self.log_impl = ReadOnlyNamespace(**log_namespace)

        self._help = None
        self._help_option = self.option_impl('--help',
                                             help='print this message')
        self._seen.add(self._help_option)
        # self._option_impl('--help') will have set this if --help was on the
        # command line.
        if self._option_values[self._help_option]:
            self._help = HelpFormatter(argv[0])
            self._help.add(self._help_option)
        elif moz_logger:
            handler = logging.FileHandler('config.log', mode='w', delay=True)
            handler.setFormatter(formatter)
            logger.addHandler(handler)

    def exec_file(self, path):
        '''Execute one file within the sandbox. Users of this class probably
        want to use `run` instead.'''

        if self._paths:
            path = mozpath.join(mozpath.dirname(self._paths[-1]), path)
            if not mozpath.basedir(path, (mozpath.dirname(self._paths[0]), )):
                raise ConfigureError(
                    'Cannot include `%s` because it is not in a subdirectory '
                    'of `%s`' % (path, mozpath.dirname(self._paths[0])))
        else:
            path = mozpath.realpath(mozpath.abspath(path))
        if path in self._paths:
            raise ConfigureError(
                'Cannot include `%s` because it was included already.' % path)
        self._paths.append(path)

        source = open(path, 'rb').read()

        code = compile(source, path, 'exec')

        exec(code, self)

        self._paths.pop(-1)

    def run(self, path):
        '''Executes the given file within the sandbox, and ensure the overall
        consistency of the executed script.'''
        self.exec_file(path)

        # All command line arguments should have been removed (handled) by now.
        for arg in self._helper:
            without_value = arg.split('=', 1)[0]
            if arg in self._implied_options:
                frameinfo, reason = self._implied_options[arg]
                raise ConfigureError(
                    '`%s`, emitted from `%s` line `%d`, was not handled.' %
                    (without_value, frameinfo[1], frameinfo[2]))
            raise InvalidOptionError('Unknown option: %s' % without_value)

        # All options must be referenced by some @depends function
        for option in self._options.itervalues():
            if option not in self._seen:
                raise ConfigureError(
                    'Option `%s` is not handled ; reference it with a @depends'
                    % option.option)

        if self._help:
            with LineIO(self.log_impl.info) as out:
                self._help.usage(out)

    def __getitem__(self, key):
        impl = '%s_impl' % key
        func = getattr(self, impl, None)
        if func:
            return func

        return super(ConfigureSandbox, self).__getitem__(key)

    def __setitem__(self, key, value):
        if (key in self.BUILTINS or key == '__builtins__'
                or hasattr(self, '%s_impl' % key)):
            raise KeyError('Cannot reassign builtins')

        if inspect.isfunction(value) and value not in self._templates:
            value, _ = self._prepare_function(value)

        elif (not isinstance(value, DependsFunction)
              and value not in self._templates and
              not (inspect.isclass(value) and issubclass(value, Exception))):
            raise KeyError('Cannot assign `%s` because it is neither a '
                           '@depends nor a @template' % key)

        return super(ConfigureSandbox, self).__setitem__(key, value)

    def _resolve(self, arg, need_help_dependency=True):
        if isinstance(arg, DependsFunction):
            assert arg in self._depends
            func, deps = self._depends[arg]
            assert not inspect.isgeneratorfunction(func)
            assert func in self._results
            if need_help_dependency and self._help_option not in deps:
                raise ConfigureError("Missing @depends for `%s`: '--help'" %
                                     func.__name__)
            result = self._results[func]
            return result
        return arg

    def option_impl(self, *args, **kwargs):
        '''Implementation of option()
        This function creates and returns an Option() object, passing it the
        resolved arguments (uses the result of functions when functions are
        passed). In most cases, the result of this function is not expected to
        be used.
        Command line argument/environment variable parsing for this Option is
        handled here.
        '''
        args = [self._resolve(arg) for arg in args]
        kwargs = {k: self._resolve(v) for k, v in kwargs.iteritems()}
        option = Option(*args, **kwargs)
        if option.name in self._options:
            raise ConfigureError('Option `%s` already defined' %
                                 self._options[option.name].option)
        if option.env in self._options:
            raise ConfigureError('Option `%s` already defined' %
                                 self._options[option.env].option)
        if option.name:
            self._options[option.name] = option
        if option.env:
            self._options[option.env] = option

        try:
            value, option_string = self._helper.handle(option)
        except ConflictingOptionError as e:
            frameinfo, reason = self._implied_options[e.arg]
            raise InvalidOptionError(
                "'%s' implied by '%s' conflicts with '%s' from the %s" %
                (e.arg, reason, e.old_arg, e.old_origin))

        if self._help:
            self._help.add(option)

        self._option_values[option] = value
        self._raw_options[option] = (option_string.split('=', 1)[0]
                                     if option_string else option_string)
        return option

    def depends_impl(self, *args):
        '''Implementation of @depends()
        This function is a decorator. It returns a function that subsequently
        takes a function and returns a dummy function. The dummy function
        identifies the actual function for the sandbox, while preventing
        further function calls from within the sandbox.

        @depends() takes a variable number of option strings or dummy function
        references. The decorated function is called as soon as the decorator
        is called, and the arguments it receives are the OptionValue or
        function results corresponding to each of the arguments to @depends.
        As an exception, when a HelpFormatter is attached, only functions that
        have '--help' in their @depends argument list are called.

        The decorated function is altered to use a different global namespace
        for its execution. This different global namespace exposes a limited
        set of functions from os.path.
        '''
        if not args:
            raise ConfigureError('@depends needs at least one argument')

        resolved_args = []
        dependencies = []
        for arg in args:
            if isinstance(arg, types.StringTypes):
                prefix, name, values = Option.split_option(arg)
                if values != ():
                    raise ConfigureError("Option must not contain an '='")
                if name not in self._options:
                    raise ConfigureError("'%s' is not a known option. "
                                         "Maybe it's declared too late?" % arg)
                arg = self._options[name]
                self._seen.add(arg)
                dependencies.append(arg)
                assert arg in self._option_values or self._help
                resolved_arg = self._option_values.get(arg)
            elif isinstance(arg, DependsFunction):
                assert arg in self._depends
                dependencies.append(arg)
                arg, _ = self._depends[arg]
                resolved_arg = self._results.get(arg)
            else:
                raise TypeError(
                    "Cannot use object of type '%s' as argument to @depends" %
                    type(arg))
            resolved_args.append(resolved_arg)
        dependencies = tuple(dependencies)

        def decorator(func):
            if inspect.isgeneratorfunction(func):
                raise ConfigureError(
                    'Cannot decorate generator functions with @depends')
            func, glob = self._prepare_function(func)
            dummy = wraps(func)(DependsFunction())
            self._depends[dummy] = func, dependencies
            with_help = self._help_option in dependencies
            if with_help:
                for arg in args:
                    if isinstance(arg, DependsFunction):
                        _, deps = self._depends[arg]
                        if self._help_option not in deps:
                            raise ConfigureError(
                                "`%s` depends on '--help' and `%s`. "
                                "`%s` must depend on '--help'" %
                                (func.__name__, arg.__name__, arg.__name__))

            if not self._help or with_help:
                self._results[func] = func(*resolved_args)

            return dummy

        return decorator

    def include_impl(self, what):
        '''Implementation of include().
        Allows to include external files for execution in the sandbox.
        It is possible to use a @depends function as argument, in which case
        the result of the function is the file name to include. This latter
        feature is only really meant for --enable-application/--enable-project.
        '''
        what = self._resolve(what)
        if what:
            if not isinstance(what, types.StringTypes):
                raise TypeError("Unexpected type: '%s'" % type(what))
            self.exec_file(what)

    def template_impl(self, func):
        '''Implementation of @template.
        This function is a decorator. Template functions are called
        immediately. They are altered so that their global namespace exposes
        a limited set of functions from os.path, as well as `depends` and
        `option`.
        Templates allow to simplify repetitive constructs, or to implement
        helper decorators and somesuch.
        '''
        template, glob = self._prepare_function(func)
        glob.update((k[:-len('_impl')], getattr(self, k)) for k in dir(self)
                    if k.endswith('_impl') and k != 'template_impl')
        glob.update((k, v) for k, v in self.iteritems() if k not in glob)

        # Any function argument to the template must be prepared to be sandboxed.
        # If the template itself returns a function (in which case, it's very
        # likely a decorator), that function must be prepared to be sandboxed as
        # well.
        def wrap_template(template):
            isfunction = inspect.isfunction

            def maybe_prepare_function(obj):
                if isfunction(obj):
                    func, _ = self._prepare_function(obj)
                    return func
                return obj

            # The following function may end up being prepared to be sandboxed,
            # so it mustn't depend on anything from the global scope in this
            # file. It can however depend on variables from the closure, thus
            # maybe_prepare_function and isfunction are declared above to be
            # available there.
            @wraps(template)
            def wrapper(*args, **kwargs):
                args = [maybe_prepare_function(arg) for arg in args]
                kwargs = {
                    k: maybe_prepare_function(v)
                    for k, v in kwargs.iteritems()
                }
                ret = template(*args, **kwargs)
                if isfunction(ret):
                    return wrap_template(ret)
                return ret

            return wrapper

        wrapper = wrap_template(template)
        self._templates.add(wrapper)
        return wrapper

    RE_MODULE = re.compile('^[a-zA-Z0-9_\.]+$')

    def imports_impl(self, _import, _from=None, _as=None):
        '''Implementation of @imports.
        This decorator imports the given _import from the given _from module
        optionally under a different _as name.
        The options correspond to the various forms for the import builtin.
            @imports('sys')
            @imports(_from='mozpack', _import='path', _as='mozpath')
        '''
        for value, required in ((_import, True), (_from, False), (_as, False)):
            if not isinstance(value, types.StringTypes) and not (
                    required or value is None):
                raise TypeError("Unexpected type: '%s'" % type(value))
            if value is not None and not self.RE_MODULE.match(value):
                raise ValueError("Invalid argument to @imports: '%s'" % value)

        def decorator(func):
            if func in self._prepared_functions:
                raise ConfigureError(
                    '@imports must appear after other decorators')
            # For the imports to apply in the order they appear in the
            # .configure file, we accumulate them in reverse order and apply
            # them later.
            imports = self._imports.setdefault(func, [])
            imports.insert(0, (_from, _import, _as))
            return func

        return decorator

    def _apply_imports(self, func, glob):
        for _from, _import, _as in self._imports.get(func, ()):
            # The special `__sandbox__` module gives access to the sandbox
            # instance.
            if _from is None and _import == '__sandbox__':
                glob[_as or _import] = self
                continue
            # Special case for the open() builtin, because otherwise, using it
            # fails with "IOError: file() constructor not accessible in
            # restricted mode"
            if _from == '__builtin__' and _import == 'open':
                glob[_as or _import] = \
                    lambda *args, **kwargs: open(*args, **kwargs)
                continue
            # Until this proves to be a performance problem, just construct an
            # import statement and execute it.
            import_line = ''
            if _from:
                import_line += 'from %s ' % _from
            import_line += 'import %s' % _import
            if _as:
                import_line += ' as %s' % _as
            # Some versions of python fail with "SyntaxError: unqualified exec
            # is not allowed in function '_apply_imports' it contains a nested
            # function with free variable" when using the exec function.
            exec import_line in {}, glob

    def _resolve_and_set(self, data, name, value):
        # Don't set anything when --help was on the command line
        if self._help:
            return
        name = self._resolve(name, need_help_dependency=False)
        if name is None:
            return
        if not isinstance(name, types.StringTypes):
            raise TypeError("Unexpected type: '%s'" % type(name))
        if name in data:
            raise ConfigureError(
                "Cannot add '%s' to configuration: Key already "
                "exists" % name)
        value = self._resolve(value, need_help_dependency=False)
        if value is not None:
            data[name] = value

    def set_config_impl(self, name, value):
        '''Implementation of set_config().
        Set the configuration items with the given name to the given value.
        Both `name` and `value` can be references to @depends functions,
        in which case the result from these functions is used. If the result
        of either function is None, the configuration item is not set.
        '''
        self._resolve_and_set(self._config, name, value)

    def set_define_impl(self, name, value):
        '''Implementation of set_define().
        Set the define with the given name to the given value. Both `name` and
        `value` can be references to @depends functions, in which case the
        result from these functions is used. If the result of either function
        is None, the define is not set. If the result is False, the define is
        explicitly undefined (-U).
        '''
        defines = self._config.setdefault('DEFINES', {})
        self._resolve_and_set(defines, name, value)

    def imply_option_impl(self, option, value, reason=None):
        '''Implementation of imply_option().
        Injects additional options as if they had been passed on the command
        line. The `option` argument is a string as in option()'s `name` or
        `env`. The option must be declared after `imply_option` references it.
        The `value` argument indicates the value to pass to the option.
        It can be:
        - True. In this case `imply_option` injects the positive option
          (--enable-foo/--with-foo).
              imply_option('--enable-foo', True)
              imply_option('--disable-foo', True)
          are both equivalent to `--enable-foo` on the command line.

        - False. In this case `imply_option` injects the negative option
          (--disable-foo/--without-foo).
              imply_option('--enable-foo', False)
              imply_option('--disable-foo', False)
          are both equivalent to `--disable-foo` on the command line.

        - None. In this case `imply_option` does nothing.
              imply_option('--enable-foo', None)
              imply_option('--disable-foo', None)
          are both equivalent to not passing any flag on the command line.

        - a string or a tuple. In this case `imply_option` injects the positive
          option with the given value(s).
              imply_option('--enable-foo', 'a')
              imply_option('--disable-foo', 'a')
          are both equivalent to `--enable-foo=a` on the command line.
              imply_option('--enable-foo', ('a', 'b'))
              imply_option('--disable-foo', ('a', 'b'))
          are both equivalent to `--enable-foo=a,b` on the command line.

        Because imply_option('--disable-foo', ...) can be misleading, it is
        recommended to use the positive form ('--enable' or '--with') for
        `option`.

        The `value` argument can also be (and usually is) a reference to a
        @depends function, in which case the result of that function will be
        used as per the descripted mapping above.

        The `reason` argument indicates what caused the option to be implied.
        It is necessary when it cannot be inferred from the `value`.
        '''
        # Don't do anything when --help was on the command line
        if self._help:
            return
        if not reason and isinstance(value, DependsFunction):
            deps = self._depends[value][1]
            possible_reasons = [d for d in deps if d != self._help_option]
            if len(possible_reasons) == 1:
                if isinstance(possible_reasons[0], Option):
                    reason = (self._raw_options.get(possible_reasons[0])
                              or possible_reasons[0].option)

        if not reason or not isinstance(value, DependsFunction):
            raise ConfigureError(
                "Cannot infer what implies '%s'. Please add a `reason` to "
                "the `imply_option` call." % option)

        value = self._resolve(value, need_help_dependency=False)
        if value is not None:
            if isinstance(value, OptionValue):
                pass
            elif value is True:
                value = PositiveOptionValue()
            elif value is False or value == ():
                value = NegativeOptionValue()
            elif isinstance(value, types.StringTypes):
                value = PositiveOptionValue((value, ))
            elif isinstance(value, tuple):
                value = PositiveOptionValue(value)
            else:
                raise TypeError("Unexpected type: '%s'" % type(value))

            option = value.format(option)
            self._helper.add(option, 'implied')
            self._implied_options[option] = inspect.stack()[1], reason

    def _prepare_function(self, func):
        '''Alter the given function global namespace with the common ground
        for @depends, and @template.
        '''
        if not inspect.isfunction(func):
            raise TypeError("Unexpected type: '%s'" % type(func))
        if func in self._prepared_functions:
            return func, func.func_globals

        glob = SandboxedGlobal(
            (k, v) for k, v in func.func_globals.iteritems()
            if (inspect.isfunction(v) and v not in self._templates) or (
                inspect.isclass(v) and issubclass(v, Exception)))
        glob.update(
            __builtins__=self.BUILTINS,
            __file__=self._paths[-1] if self._paths else '',
            os=self.OS,
            log=self.log_impl,
        )
        self._apply_imports(func, glob)
        func = wraps(func)(types.FunctionType(func.func_code, glob,
                                              func.__name__,
                                              func.func_defaults,
                                              func.func_closure))
        self._prepared_functions.add(func)
        return func, glob
コード例 #13
0
ファイル: __init__.py プロジェクト: bslassey/spidernode
class ConfigureSandbox(dict):
    """Represents a sandbox for executing Python code for build configuration.
    This is a different kind of sandboxing than the one used for moz.build
    processing.

    The sandbox has 5 primitives:
    - option
    - depends
    - template
    - advanced
    - include

    `option` and `include` are functions. `depends`, `template` and `advanced`
    are decorators.

    These primitives are declared as name_impl methods to this class and
    the mapping name -> name_impl is done automatically in __getitem__.

    Additional primitives should be frowned upon to keep the sandbox itself as
    simple as possible. Instead, helpers should be created within the sandbox
    with the existing primitives.

    The sandbox is given, at creation, a dict where the yielded configuration
    will be stored.

        config = {}
        sandbox = ConfigureSandbox(config)
        sandbox.run(path)
        do_stuff(config)
    """

    # The default set of builtins.
    BUILTINS = ReadOnlyDict(
        {
            b: __builtins__[b]
            for b in ('None', 'False', 'True', 'int', 'bool', 'any', 'all',
                      'len', 'list', 'tuple', 'set', 'dict', 'isinstance')
        },
        __import__=forbidden_import)

    # Expose a limited set of functions from os.path
    OS = ReadOnlyNamespace(path=ReadOnlyNamespace(
        **{
            k: getattr(mozpath, k, getattr(os.path, k))
            for k in ('abspath', 'basename', 'dirname', 'exists', 'isabs',
                      'isdir', 'isfile', 'join', 'normpath', 'realpath',
                      'relpath')
        }))

    def __init__(self,
                 config,
                 environ=os.environ,
                 argv=sys.argv,
                 stdout=sys.stdout,
                 stderr=sys.stderr):
        dict.__setitem__(self, '__builtins__', self.BUILTINS)

        self._paths = []
        self._templates = set()
        # Store the real function and its dependencies, behind each
        # DummyFunction generated from @depends.
        self._depends = {}
        self._seen = set()

        self._options = OrderedDict()
        # Store the raw values returned by @depends functions
        self._results = {}
        # Store values for each Option, as per returned by Option.get_value
        self._option_values = {}
        # Store raw option (as per command line or environment) for each Option
        self._raw_options = {}

        # Store options added with `imply_option`, and the reason they were
        # added (which can either have been given to `imply_option`, or
        # inferred.
        self._implied_options = {}

        # Store all results from _prepare_function
        self._prepared_functions = set()

        self._helper = CommandLineHelper(environ, argv)

        assert isinstance(config, dict)
        self._config, self._stdout, self._stderr = config, stdout, stderr

        self._help = None
        self._help_option = self.option_impl('--help',
                                             help='print this message')
        self._seen.add(self._help_option)
        # self._option_impl('--help') will have set this if --help was on the
        # command line.
        if self._option_values[self._help_option]:
            self._help = HelpFormatter(argv[0])
            self._help.add(self._help_option)

    def exec_file(self, path):
        '''Execute one file within the sandbox. Users of this class probably
        want to use `run` instead.'''

        if self._paths:
            path = mozpath.join(mozpath.dirname(self._paths[-1]), path)
            if not mozpath.basedir(path, (mozpath.dirname(self._paths[0]), )):
                raise ConfigureError(
                    'Cannot include `%s` because it is not in a subdirectory '
                    'of `%s`' % (path, mozpath.dirname(self._paths[0])))
        else:
            path = mozpath.realpath(mozpath.abspath(path))
        if path in self._paths:
            raise ConfigureError(
                'Cannot include `%s` because it was included already.' % path)
        self._paths.append(path)

        source = open(path, 'rb').read()

        code = compile(source, path, 'exec')

        exec(code, self)

        self._paths.pop(-1)

    def run(self, path):
        '''Executes the given file within the sandbox, and ensure the overall
        consistency of the executed script.'''
        self.exec_file(path)

        # All command line arguments should have been removed (handled) by now.
        for arg in self._helper:
            without_value = arg.split('=', 1)[0]
            if arg in self._implied_options:
                frameinfo, reason = self._implied_options[arg]
                raise ConfigureError(
                    '`%s`, emitted from `%s` line `%d`, was not handled.' %
                    (without_value, frameinfo[1], frameinfo[2]))
            raise InvalidOptionError('Unknown option: %s' % without_value)

        # All options must be referenced by some @depends function
        for option in self._options.itervalues():
            if option not in self._seen:
                raise ConfigureError(
                    'Option `%s` is not handled ; reference it with a @depends'
                    % option.option)

        if self._help:
            self._help.usage(self._stdout)

    def __getitem__(self, key):
        impl = '%s_impl' % key
        func = getattr(self, impl, None)
        if func:
            return func

        return super(ConfigureSandbox, self).__getitem__(key)

    def __setitem__(self, key, value):
        if (key in self.BUILTINS or key == '__builtins__'
                or hasattr(self, '%s_impl' % key)):
            raise KeyError('Cannot reassign builtins')

        if (not isinstance(value, DummyFunction)
                and value not in self._templates):
            raise KeyError('Cannot assign `%s` because it is neither a '
                           '@depends nor a @template' % key)

        return super(ConfigureSandbox, self).__setitem__(key, value)

    def _resolve(self, arg, need_help_dependency=True):
        if isinstance(arg, DummyFunction):
            assert arg in self._depends
            func, deps = self._depends[arg]
            assert not inspect.isgeneratorfunction(func)
            assert func in self._results
            if need_help_dependency and self._help_option not in deps:
                raise ConfigureError("Missing @depends for `%s`: '--help'" %
                                     func.__name__)
            result = self._results[func]
            return result
        return arg

    def option_impl(self, *args, **kwargs):
        '''Implementation of option()
        This function creates and returns an Option() object, passing it the
        resolved arguments (uses the result of functions when functions are
        passed). In most cases, the result of this function is not expected to
        be used.
        Command line argument/environment variable parsing for this Option is
        handled here.
        '''
        args = [self._resolve(arg) for arg in args]
        kwargs = {k: self._resolve(v) for k, v in kwargs.iteritems()}
        option = Option(*args, **kwargs)
        if option.name in self._options:
            raise ConfigureError('Option `%s` already defined' %
                                 self._options[option.name].option)
        if option.env in self._options:
            raise ConfigureError('Option `%s` already defined' %
                                 self._options[option.env].option)
        if option.name:
            self._options[option.name] = option
        if option.env:
            self._options[option.env] = option

        try:
            value, option_string = self._helper.handle(option)
        except ConflictingOptionError as e:
            frameinfo, reason = self._implied_options[e.arg]
            raise InvalidOptionError(
                "'%s' implied by '%s' conflicts with '%s' from the %s" %
                (e.arg, reason, e.old_arg, e.old_origin))

        if self._help:
            self._help.add(option)

        self._option_values[option] = value
        self._raw_options[option] = (option_string.split('=', 1)[0]
                                     if option_string else option_string)
        return option

    def depends_impl(self, *args):
        '''Implementation of @depends()
        This function is a decorator. It returns a function that subsequently
        takes a function and returns a dummy function. The dummy function
        identifies the actual function for the sandbox, while preventing
        further function calls from within the sandbox.

        @depends() takes a variable number of option strings or dummy function
        references. The decorated function is called as soon as the decorator
        is called, and the arguments it receives are the OptionValue or
        function results corresponding to each of the arguments to @depends.
        As an exception, when a HelpFormatter is attached, only functions that
        have '--help' in their @depends argument list are called.

        The decorated function is altered to use a different global namespace
        for its execution. This different global namespace exposes a limited
        set of functions from os.path.
        '''
        if not args:
            raise ConfigureError('@depends needs at least one argument')

        resolved_args = []
        dependencies = []
        for arg in args:
            if isinstance(arg, types.StringTypes):
                prefix, name, values = Option.split_option(arg)
                if values != ():
                    raise ConfigureError("Option must not contain an '='")
                if name not in self._options:
                    raise ConfigureError("'%s' is not a known option. "
                                         "Maybe it's declared too late?" % arg)
                arg = self._options[name]
                self._seen.add(arg)
                dependencies.append(arg)
                assert arg in self._option_values or self._help
                resolved_arg = self._option_values.get(arg)
            elif isinstance(arg, DummyFunction):
                assert arg in self._depends
                dependencies.append(arg)
                arg, _ = self._depends[arg]
                resolved_arg = self._results.get(arg)
            else:
                raise TypeError(
                    "Cannot use object of type '%s' as argument to @depends" %
                    type(arg))
            resolved_args.append(resolved_arg)
        dependencies = tuple(dependencies)

        def decorator(func):
            if inspect.isgeneratorfunction(func):
                raise ConfigureError(
                    'Cannot decorate generator functions with @depends')
            func, glob = self._prepare_function(func)
            dummy = wraps(func)(DummyFunction())
            self._depends[dummy] = func, dependencies
            with_help = self._help_option in dependencies
            if with_help:
                for arg in args:
                    if isinstance(arg, DummyFunction):
                        _, deps = self._depends[arg]
                        if self._help_option not in deps:
                            raise ConfigureError(
                                "`%s` depends on '--help' and `%s`. "
                                "`%s` must depend on '--help'" %
                                (func.__name__, arg.__name__, arg.__name__))

            if not self._help or with_help:
                self._results[func] = func(*resolved_args)

            return dummy

        return decorator

    def include_impl(self, what):
        '''Implementation of include().
        Allows to include external files for execution in the sandbox.
        It is possible to use a @depends function as argument, in which case
        the result of the function is the file name to include. This latter
        feature is only really meant for --enable-application/--enable-project.
        '''
        what = self._resolve(what)
        if what:
            if not isinstance(what, types.StringTypes):
                raise TypeError("Unexpected type: '%s'" % type(what))
            self.exec_file(what)

    def template_impl(self, func):
        '''Implementation of @template.
        This function is a decorator. Template functions are called
        immediately. They are altered so that their global namespace exposes
        a limited set of functions from os.path, as well as `advanced`,
        `depends` and `option`.
        Templates allow to simplify repetitive constructs, or to implement
        helper decorators and somesuch.
        '''
        template, glob = self._prepare_function(func)
        glob.update((k[:-len('_impl')], getattr(self, k)) for k in dir(self)
                    if k.endswith('_impl') and k != 'template_impl')
        self._templates.add(template)
        return template

    def advanced_impl(self, func):
        '''Implementation of @advanced.
        This function gives the decorated function access to the complete set
        of builtins, allowing the import keyword as an expected side effect.
        '''
        func, glob = self._prepare_function(func)
        glob.update(__builtins__=__builtins__)
        return func

    def _resolve_and_set(self, data, name, value):
        # Don't set anything when --help was on the command line
        if self._help:
            return
        name = self._resolve(name, need_help_dependency=False)
        if name is None:
            return
        if not isinstance(name, types.StringTypes):
            raise TypeError("Unexpected type: '%s'" % type(name))
        if name in data:
            raise ConfigureError(
                "Cannot add '%s' to configuration: Key already "
                "exists" % name)
        value = self._resolve(value, need_help_dependency=False)
        if value is not None:
            data[name] = value

    def set_config_impl(self, name, value):
        '''Implementation of set_config().
        Set the configuration items with the given name to the given value.
        Both `name` and `value` can be references to @depends functions,
        in which case the result from these functions is used. If the result
        of either function is None, the configuration item is not set.
        '''
        self._resolve_and_set(self._config, name, value)

    def set_define_impl(self, name, value):
        '''Implementation of set_define().
        Set the define with the given name to the given value. Both `name` and
        `value` can be references to @depends functions, in which case the
        result from these functions is used. If the result of either function
        is None, the define is not set. If the result is False, the define is
        explicitly undefined (-U).
        '''
        defines = self._config.setdefault('DEFINES', {})
        self._resolve_and_set(defines, name, value)

    def imply_option_impl(self, option, value, reason=None):
        '''Implementation of imply_option().
        Injects additional options as if they had been passed on the command
        line. The `option` argument is a string as in option()'s `name` or
        `env`. The option must be declared after `imply_option` references it.
        The `value` argument indicates the value to pass to the option.
        It can be:
        - True. In this case `imply_option` injects the positive option
          (--enable-foo/--with-foo).
              imply_option('--enable-foo', True)
              imply_option('--disable-foo', True)
          are both equivalent to `--enable-foo` on the command line.

        - False. In this case `imply_option` injects the negative option
          (--disable-foo/--without-foo).
              imply_option('--enable-foo', False)
              imply_option('--disable-foo', False)
          are both equivalent to `--disable-foo` on the command line.

        - None. In this case `imply_option` does nothing.
              imply_option('--enable-foo', None)
              imply_option('--disable-foo', None)
          are both equivalent to not passing any flag on the command line.

        - a string or a tuple. In this case `imply_option` injects the positive
          option with the given value(s).
              imply_option('--enable-foo', 'a')
              imply_option('--disable-foo', 'a')
          are both equivalent to `--enable-foo=a` on the command line.
              imply_option('--enable-foo', ('a', 'b'))
              imply_option('--disable-foo', ('a', 'b'))
          are both equivalent to `--enable-foo=a,b` on the command line.

        Because imply_option('--disable-foo', ...) can be misleading, it is
        recommended to use the positive form ('--enable' or '--with') for
        `option`.

        The `value` argument can also be (and usually is) a reference to a
        @depends function, in which case the result of that function will be
        used as per the descripted mapping above.

        The `reason` argument indicates what caused the option to be implied.
        It is necessary when it cannot be inferred from the `value`.
        '''
        # Don't do anything when --help was on the command line
        if self._help:
            return
        if not reason and isinstance(value, DummyFunction):
            deps = self._depends[value][1]
            possible_reasons = [d for d in deps if d != self._help_option]
            if len(possible_reasons) == 1:
                if isinstance(possible_reasons[0], Option):
                    reason = (self._raw_options.get(possible_reasons[0])
                              or possible_reasons[0].option)

        if not reason or not isinstance(value, DummyFunction):
            raise ConfigureError(
                "Cannot infer what implies '%s'. Please add a `reason` to "
                "the `imply_option` call." % option)

        value = self._resolve(value, need_help_dependency=False)
        if value is not None:
            if isinstance(value, OptionValue):
                pass
            elif value is True:
                value = PositiveOptionValue()
            elif value is False or value == ():
                value = NegativeOptionValue()
            elif isinstance(value, types.StringTypes):
                value = PositiveOptionValue((value, ))
            elif isinstance(value, tuple):
                value = PositiveOptionValue(value)
            else:
                raise TypeError("Unexpected type: '%s'" % type(value))

            option = value.format(option)
            self._helper.add(option, 'implied')
            self._implied_options[option] = inspect.stack()[1], reason

    def _prepare_function(self, func):
        '''Alter the given function global namespace with the common ground
        for @depends, @template and @advanced.
        '''
        if not inspect.isfunction(func):
            raise TypeError("Unexpected type: '%s'" % type(func))
        if func in self._prepared_functions:
            return func, func.func_globals

        glob = SandboxedGlobal(func.func_globals)
        glob.update(
            __builtins__=self.BUILTINS,
            __file__=self._paths[-1],
            os=self.OS,
        )
        func = wraps(func)(types.FunctionType(func.func_code, glob,
                                              func.__name__,
                                              func.func_defaults,
                                              func.func_closure))
        self._prepared_functions.add(func)
        return func, glob
コード例 #14
0
    def test_extra_args(self):
        foo = Option('--with-foo', env='FOO', nargs='*')
        helper = CommandLineHelper({}, ['cmd'])
        helper.add('FOO=a,b,c', 'other-origin')
        value, option = helper.handle(foo)
        self.assertEquals(PositiveOptionValue(('a', 'b', 'c')), value)
        self.assertEquals('other-origin', value.origin)
        self.assertEquals('FOO=a,b,c', option)

        helper = CommandLineHelper({}, ['cmd'])
        helper.add('FOO=a,b,c', 'other-origin')
        helper.add('--with-foo=a,b,c', 'other-origin')
        value, option = helper.handle(foo)
        self.assertEquals(PositiveOptionValue(('a', 'b', 'c')), value)
        self.assertEquals('other-origin', value.origin)
        self.assertEquals('--with-foo=a,b,c', option)

        # Adding conflicting options is not allowed.
        helper = CommandLineHelper({}, ['cmd'])
        helper.add('FOO=a,b,c', 'other-origin')
        with self.assertRaises(ConflictingOptionError) as cm:
            helper.add('FOO=', 'other-origin')
        self.assertEqual('FOO=', cm.exception.arg)
        self.assertEqual('other-origin', cm.exception.origin)
        self.assertEqual('FOO=a,b,c', cm.exception.old_arg)
        self.assertEqual('other-origin', cm.exception.old_origin)
        with self.assertRaises(ConflictingOptionError) as cm:
            helper.add('FOO=a,b', 'other-origin')
        self.assertEqual('FOO=a,b', cm.exception.arg)
        self.assertEqual('other-origin', cm.exception.origin)
        self.assertEqual('FOO=a,b,c', cm.exception.old_arg)
        self.assertEqual('other-origin', cm.exception.old_origin)
        # But adding the same is allowed.
        helper.add('FOO=a,b,c', 'other-origin')
        value, option = helper.handle(foo)
        self.assertEquals(PositiveOptionValue(('a', 'b', 'c')), value)
        self.assertEquals('other-origin', value.origin)
        self.assertEquals('FOO=a,b,c', option)

        # The same rule as above applies when using the option form vs. the
        # variable form. But we can't detect it when .add is called.
        helper = CommandLineHelper({}, ['cmd'])
        helper.add('FOO=a,b,c', 'other-origin')
        helper.add('--without-foo', 'other-origin')
        with self.assertRaises(ConflictingOptionError) as cm:
            helper.handle(foo)
        self.assertEqual('--without-foo', cm.exception.arg)
        self.assertEqual('other-origin', cm.exception.origin)
        self.assertEqual('FOO=a,b,c', cm.exception.old_arg)
        self.assertEqual('other-origin', cm.exception.old_origin)
        helper = CommandLineHelper({}, ['cmd'])
        helper.add('FOO=a,b,c', 'other-origin')
        helper.add('--with-foo=a,b', 'other-origin')
        with self.assertRaises(ConflictingOptionError) as cm:
            helper.handle(foo)
        self.assertEqual('--with-foo=a,b', cm.exception.arg)
        self.assertEqual('other-origin', cm.exception.origin)
        self.assertEqual('FOO=a,b,c', cm.exception.old_arg)
        self.assertEqual('other-origin', cm.exception.old_origin)
        helper = CommandLineHelper({}, ['cmd'])
        helper.add('FOO=a,b,c', 'other-origin')
        helper.add('--with-foo=a,b,c', 'other-origin')
        value, option = helper.handle(foo)
        self.assertEquals(PositiveOptionValue(('a', 'b', 'c')), value)
        self.assertEquals('other-origin', value.origin)
        self.assertEquals('--with-foo=a,b,c', option)

        # Conflicts are also not allowed against what is in the
        # environment/on the command line.
        helper = CommandLineHelper({}, ['cmd', '--with-foo=a,b'])
        helper.add('FOO=a,b,c', 'other-origin')
        with self.assertRaises(ConflictingOptionError) as cm:
            helper.handle(foo)
        self.assertEqual('FOO=a,b,c', cm.exception.arg)
        self.assertEqual('other-origin', cm.exception.origin)
        self.assertEqual('--with-foo=a,b', cm.exception.old_arg)
        self.assertEqual('command-line', cm.exception.old_origin)

        helper = CommandLineHelper({}, ['cmd', '--with-foo=a,b'])
        helper.add('--without-foo', 'other-origin')
        with self.assertRaises(ConflictingOptionError) as cm:
            helper.handle(foo)
        self.assertEqual('--without-foo', cm.exception.arg)
        self.assertEqual('other-origin', cm.exception.origin)
        self.assertEqual('--with-foo=a,b', cm.exception.old_arg)
        self.assertEqual('command-line', cm.exception.old_origin)
コード例 #15
0
ファイル: __init__.py プロジェクト: wizAmit/gecko-dev
    def __init__(self,
                 config,
                 environ=os.environ,
                 argv=sys.argv,
                 stdout=sys.stdout,
                 stderr=sys.stderr,
                 logger=None):
        dict.__setitem__(self, '__builtins__', self.BUILTINS)

        self._paths = []
        self._templates = set()
        # Store the real function and its dependencies, behind each
        # DependsFunction generated from @depends.
        self._depends = {}
        self._seen = set()
        # Store the @imports added to a given function.
        self._imports = {}

        self._options = OrderedDict()
        # Store the raw values returned by @depends functions
        self._results = {}
        # Store values for each Option, as per returned by Option.get_value
        self._option_values = {}
        # Store raw option (as per command line or environment) for each Option
        self._raw_options = {}

        # Store options added with `imply_option`, and the reason they were
        # added (which can either have been given to `imply_option`, or
        # inferred.
        self._implied_options = {}

        # Store all results from _prepare_function
        self._prepared_functions = set()

        self._helper = CommandLineHelper(environ, argv)

        assert isinstance(config, dict)
        self._config = config

        if logger is None:
            logger = moz_logger = logging.getLogger('moz.configure')
            logger.setLevel(logging.DEBUG)
            formatter = logging.Formatter('%(levelname)s: %(message)s')
            handler = ConfigureOutputHandler(stdout, stderr)
            handler.setFormatter(formatter)
            queue_debug = handler.queue_debug
            logger.addHandler(handler)

        else:
            assert isinstance(logger, logging.Logger)
            moz_logger = None

            @contextmanager
            def queue_debug():
                yield

        log_namespace = {
            k: getattr(logger, k)
            for k in ('debug', 'info', 'warning', 'error')
        }
        log_namespace['queue_debug'] = queue_debug
        self.log_impl = ReadOnlyNamespace(**log_namespace)

        self._help = None
        self._help_option = self.option_impl('--help',
                                             help='print this message')
        self._seen.add(self._help_option)
        # self._option_impl('--help') will have set this if --help was on the
        # command line.
        if self._option_values[self._help_option]:
            self._help = HelpFormatter(argv[0])
            self._help.add(self._help_option)
        elif moz_logger:
            handler = logging.FileHandler('config.log', mode='w', delay=True)
            handler.setFormatter(formatter)
            logger.addHandler(handler)
コード例 #16
0
ファイル: __init__.py プロジェクト: leplatrem/gecko-dev
class ConfigureSandbox(dict):
    """Represents a sandbox for executing Python code for build configuration.
    This is a different kind of sandboxing than the one used for moz.build
    processing.

    The sandbox has 8 primitives:
    - option
    - depends
    - template
    - imports
    - include
    - set_config
    - set_define
    - imply_option

    `option`, `include`, `set_config`, `set_define` and `imply_option` are
    functions. `depends`, `template`, and `imports` are decorators.

    These primitives are declared as name_impl methods to this class and
    the mapping name -> name_impl is done automatically in __getitem__.

    Additional primitives should be frowned upon to keep the sandbox itself as
    simple as possible. Instead, helpers should be created within the sandbox
    with the existing primitives.

    The sandbox is given, at creation, a dict where the yielded configuration
    will be stored.

        config = {}
        sandbox = ConfigureSandbox(config)
        sandbox.run(path)
        do_stuff(config)
    """

    # The default set of builtins. We expose unicode as str to make sandboxed
    # files more python3-ready.
    BUILTINS = ReadOnlyDict({
        b: __builtins__[b]
        for b in ('None', 'False', 'True', 'int', 'bool', 'any', 'all', 'len',
                  'list', 'tuple', 'set', 'dict', 'isinstance')
    }, __import__=forbidden_import, str=unicode)

    # Expose a limited set of functions from os.path
    OS = ReadOnlyNamespace(path=ReadOnlyNamespace(**{
        k: getattr(mozpath, k, getattr(os.path, k))
        for k in ('abspath', 'basename', 'dirname', 'exists', 'isabs', 'isdir',
                  'isfile', 'join', 'normpath', 'realpath', 'relpath')
    }))

    def __init__(self, config, environ=os.environ, argv=sys.argv,
                 stdout=sys.stdout, stderr=sys.stderr, logger=None):
        dict.__setitem__(self, '__builtins__', self.BUILTINS)

        self._paths = []
        self._templates = set()
        # Store the real function and its dependencies, behind each
        # DependsFunction generated from @depends.
        self._depends = {}
        self._seen = set()
        # Store the @imports added to a given function.
        self._imports = {}

        self._options = OrderedDict()
        # Store the raw values returned by @depends functions
        self._results = {}
        # Store values for each Option, as per returned by Option.get_value
        self._option_values = {}
        # Store raw option (as per command line or environment) for each Option
        self._raw_options = {}

        # Store options added with `imply_option`, and the reason they were
        # added (which can either have been given to `imply_option`, or
        # inferred.
        self._implied_options = {}

        # Store all results from _prepare_function
        self._prepared_functions = set()

        self._helper = CommandLineHelper(environ, argv)

        assert isinstance(config, dict)
        self._config = config

        if logger is None:
            logger = moz_logger = logging.getLogger('moz.configure')
            logger.setLevel(logging.DEBUG)
            formatter = logging.Formatter('%(levelname)s: %(message)s')
            handler = ConfigureOutputHandler(stdout, stderr)
            handler.setFormatter(formatter)
            queue_debug = handler.queue_debug
            logger.addHandler(handler)

        else:
            assert isinstance(logger, logging.Logger)
            moz_logger = None
            @contextmanager
            def queue_debug():
                yield

        log_namespace = {
            k: getattr(logger, k)
            for k in ('debug', 'info', 'warning', 'error')
        }
        log_namespace['queue_debug'] = queue_debug
        self.log_impl = ReadOnlyNamespace(**log_namespace)

        self._help = None
        self._help_option = self.option_impl('--help',
                                             help='print this message')
        self._seen.add(self._help_option)
        # self._option_impl('--help') will have set this if --help was on the
        # command line.
        if self._option_values[self._help_option]:
            self._help = HelpFormatter(argv[0])
            self._help.add(self._help_option)
        elif moz_logger:
            handler = logging.FileHandler('config.log', mode='w', delay=True)
            handler.setFormatter(formatter)
            logger.addHandler(handler)

    def exec_file(self, path):
        '''Execute one file within the sandbox. Users of this class probably
        want to use `run` instead.'''

        if self._paths:
            path = mozpath.join(mozpath.dirname(self._paths[-1]), path)
            if not mozpath.basedir(path, (mozpath.dirname(self._paths[0]),)):
                raise ConfigureError(
                    'Cannot include `%s` because it is not in a subdirectory '
                    'of `%s`' % (path, mozpath.dirname(self._paths[0])))
        else:
            path = mozpath.realpath(mozpath.abspath(path))
        if path in self._paths:
            raise ConfigureError(
                'Cannot include `%s` because it was included already.' % path)
        self._paths.append(path)

        source = open(path, 'rb').read()

        code = compile(source, path, 'exec')

        exec(code, self)

        self._paths.pop(-1)

    def run(self, path):
        '''Executes the given file within the sandbox, and ensure the overall
        consistency of the executed script.'''
        self.exec_file(path)

        # All command line arguments should have been removed (handled) by now.
        for arg in self._helper:
            without_value = arg.split('=', 1)[0]
            if arg in self._implied_options:
                frameinfo, reason = self._implied_options[arg]
                raise ConfigureError(
                    '`%s`, emitted from `%s` line `%d`, was not handled.'
                    % (without_value, frameinfo[1], frameinfo[2]))
            raise InvalidOptionError('Unknown option: %s' % without_value)

        # All options must be referenced by some @depends function
        for option in self._options.itervalues():
            if option not in self._seen:
                raise ConfigureError(
                    'Option `%s` is not handled ; reference it with a @depends'
                    % option.option
                )

        if self._help:
            with LineIO(self.log_impl.info) as out:
                self._help.usage(out)

    def __getitem__(self, key):
        impl = '%s_impl' % key
        func = getattr(self, impl, None)
        if func:
            return func

        return super(ConfigureSandbox, self).__getitem__(key)

    def __setitem__(self, key, value):
        if (key in self.BUILTINS or key == '__builtins__' or
                hasattr(self, '%s_impl' % key)):
            raise KeyError('Cannot reassign builtins')

        if inspect.isfunction(value) and value not in self._templates:
            value, _ = self._prepare_function(value)

        elif (not isinstance(value, DependsFunction) and
                value not in self._templates and
                not (inspect.isclass(value) and issubclass(value, Exception))):
            raise KeyError('Cannot assign `%s` because it is neither a '
                           '@depends nor a @template' % key)

        return super(ConfigureSandbox, self).__setitem__(key, value)

    def _resolve(self, arg, need_help_dependency=True):
        if isinstance(arg, DependsFunction):
            assert arg in self._depends
            func, deps = self._depends[arg]
            assert not inspect.isgeneratorfunction(func)
            assert func in self._results
            if need_help_dependency and self._help_option not in deps:
                raise ConfigureError("Missing @depends for `%s`: '--help'" %
                                     func.__name__)
            result = self._results[func]
            return result
        return arg

    def option_impl(self, *args, **kwargs):
        '''Implementation of option()
        This function creates and returns an Option() object, passing it the
        resolved arguments (uses the result of functions when functions are
        passed). In most cases, the result of this function is not expected to
        be used.
        Command line argument/environment variable parsing for this Option is
        handled here.
        '''
        args = [self._resolve(arg) for arg in args]
        kwargs = {k: self._resolve(v) for k, v in kwargs.iteritems()}
        option = Option(*args, **kwargs)
        if option.name in self._options:
            raise ConfigureError('Option `%s` already defined'
                                 % self._options[option.name].option)
        if option.env in self._options:
            raise ConfigureError('Option `%s` already defined'
                                 % self._options[option.env].option)
        if option.name:
            self._options[option.name] = option
        if option.env:
            self._options[option.env] = option

        try:
            value, option_string = self._helper.handle(option)
        except ConflictingOptionError as e:
            frameinfo, reason = self._implied_options[e.arg]
            raise InvalidOptionError(
                "'%s' implied by '%s' conflicts with '%s' from the %s"
                % (e.arg, reason, e.old_arg, e.old_origin))

        if self._help:
            self._help.add(option)

        self._option_values[option] = value
        self._raw_options[option] = (option_string.split('=', 1)[0]
                                     if option_string else option_string)
        return option

    def depends_impl(self, *args):
        '''Implementation of @depends()
        This function is a decorator. It returns a function that subsequently
        takes a function and returns a dummy function. The dummy function
        identifies the actual function for the sandbox, while preventing
        further function calls from within the sandbox.

        @depends() takes a variable number of option strings or dummy function
        references. The decorated function is called as soon as the decorator
        is called, and the arguments it receives are the OptionValue or
        function results corresponding to each of the arguments to @depends.
        As an exception, when a HelpFormatter is attached, only functions that
        have '--help' in their @depends argument list are called.

        The decorated function is altered to use a different global namespace
        for its execution. This different global namespace exposes a limited
        set of functions from os.path.
        '''
        if not args:
            raise ConfigureError('@depends needs at least one argument')

        resolved_args = []
        dependencies = []
        for arg in args:
            if isinstance(arg, types.StringTypes):
                prefix, name, values = Option.split_option(arg)
                if values != ():
                    raise ConfigureError("Option must not contain an '='")
                if name not in self._options:
                    raise ConfigureError("'%s' is not a known option. "
                                         "Maybe it's declared too late?"
                                         % arg)
                arg = self._options[name]
                self._seen.add(arg)
                dependencies.append(arg)
                assert arg in self._option_values or self._help
                resolved_arg = self._option_values.get(arg)
            elif isinstance(arg, DependsFunction):
                assert arg in self._depends
                dependencies.append(arg)
                arg, _ = self._depends[arg]
                resolved_arg = self._results.get(arg)
            else:
                raise TypeError(
                    "Cannot use object of type '%s' as argument to @depends"
                    % type(arg))
            resolved_args.append(resolved_arg)
        dependencies = tuple(dependencies)

        def decorator(func):
            if inspect.isgeneratorfunction(func):
                raise ConfigureError(
                    'Cannot decorate generator functions with @depends')
            func, glob = self._prepare_function(func)
            dummy = wraps(func)(DependsFunction())
            self._depends[dummy] = func, dependencies
            with_help = self._help_option in dependencies
            if with_help:
                for arg in args:
                    if isinstance(arg, DependsFunction):
                        _, deps = self._depends[arg]
                        if self._help_option not in deps:
                            raise ConfigureError(
                                "`%s` depends on '--help' and `%s`. "
                                "`%s` must depend on '--help'"
                                % (func.__name__, arg.__name__, arg.__name__))

            if not self._help or with_help:
                self._results[func] = func(*resolved_args)

            return dummy

        return decorator

    def include_impl(self, what):
        '''Implementation of include().
        Allows to include external files for execution in the sandbox.
        It is possible to use a @depends function as argument, in which case
        the result of the function is the file name to include. This latter
        feature is only really meant for --enable-application/--enable-project.
        '''
        what = self._resolve(what)
        if what:
            if not isinstance(what, types.StringTypes):
                raise TypeError("Unexpected type: '%s'" % type(what))
            self.exec_file(what)

    def template_impl(self, func):
        '''Implementation of @template.
        This function is a decorator. Template functions are called
        immediately. They are altered so that their global namespace exposes
        a limited set of functions from os.path, as well as `depends` and
        `option`.
        Templates allow to simplify repetitive constructs, or to implement
        helper decorators and somesuch.
        '''
        template, glob = self._prepare_function(func)
        glob.update(
            (k[:-len('_impl')], getattr(self, k))
            for k in dir(self) if k.endswith('_impl') and k != 'template_impl'
        )
        glob.update((k, v) for k, v in self.iteritems() if k not in glob)

        # Any function argument to the template must be prepared to be sandboxed.
        # If the template itself returns a function (in which case, it's very
        # likely a decorator), that function must be prepared to be sandboxed as
        # well.
        def wrap_template(template):
            isfunction = inspect.isfunction

            def maybe_prepare_function(obj):
                if isfunction(obj):
                    func, _ = self._prepare_function(obj)
                    return func
                return obj

            # The following function may end up being prepared to be sandboxed,
            # so it mustn't depend on anything from the global scope in this
            # file. It can however depend on variables from the closure, thus
            # maybe_prepare_function and isfunction are declared above to be
            # available there.
            @wraps(template)
            def wrapper(*args, **kwargs):
                args = [maybe_prepare_function(arg) for arg in args]
                kwargs = {k: maybe_prepare_function(v)
                          for k, v in kwargs.iteritems()}
                ret = template(*args, **kwargs)
                if isfunction(ret):
                    return wrap_template(ret)
                return ret
            return wrapper

        wrapper = wrap_template(template)
        self._templates.add(wrapper)
        return wrapper

    RE_MODULE = re.compile('^[a-zA-Z0-9_\.]+$')

    def imports_impl(self, _import, _from=None, _as=None):
        '''Implementation of @imports.
        This decorator imports the given _import from the given _from module
        optionally under a different _as name.
        The options correspond to the various forms for the import builtin.
            @imports('sys')
            @imports(_from='mozpack', _import='path', _as='mozpath')
        '''
        for value, required in (
                (_import, True), (_from, False), (_as, False)):
            if not isinstance(value, types.StringTypes) and not (
                    required or value is None):
                raise TypeError("Unexpected type: '%s'" % type(value))
            if value is not None and not self.RE_MODULE.match(value):
                raise ValueError("Invalid argument to @imports: '%s'" % value)

        def decorator(func):
            if func in self._prepared_functions:
                raise ConfigureError(
                    '@imports must appear after other decorators')
            # For the imports to apply in the order they appear in the
            # .configure file, we accumulate them in reverse order and apply
            # them later.
            imports = self._imports.setdefault(func, [])
            imports.insert(0, (_from, _import, _as))
            return func

        return decorator

    def _apply_imports(self, func, glob):
        for _from, _import, _as in self._imports.get(func, ()):
            # The special `__sandbox__` module gives access to the sandbox
            # instance.
            if _from is None and _import == '__sandbox__':
                glob[_as or _import] = self
                continue
            # Special case for the open() builtin, because otherwise, using it
            # fails with "IOError: file() constructor not accessible in
            # restricted mode"
            if _from == '__builtin__' and _import == 'open':
                glob[_as or _import] = \
                    lambda *args, **kwargs: open(*args, **kwargs)
                continue
            # Until this proves to be a performance problem, just construct an
            # import statement and execute it.
            import_line = ''
            if _from:
                import_line += 'from %s ' % _from
            import_line += 'import %s' % _import
            if _as:
                import_line += ' as %s' % _as
            # Some versions of python fail with "SyntaxError: unqualified exec
            # is not allowed in function '_apply_imports' it contains a nested
            # function with free variable" when using the exec function.
            exec import_line in {}, glob

    def _resolve_and_set(self, data, name, value):
        # Don't set anything when --help was on the command line
        if self._help:
            return
        name = self._resolve(name, need_help_dependency=False)
        if name is None:
            return
        if not isinstance(name, types.StringTypes):
            raise TypeError("Unexpected type: '%s'" % type(name))
        if name in data:
            raise ConfigureError(
                "Cannot add '%s' to configuration: Key already "
                "exists" % name)
        value = self._resolve(value, need_help_dependency=False)
        if value is not None:
            data[name] = value

    def set_config_impl(self, name, value):
        '''Implementation of set_config().
        Set the configuration items with the given name to the given value.
        Both `name` and `value` can be references to @depends functions,
        in which case the result from these functions is used. If the result
        of either function is None, the configuration item is not set.
        '''
        self._resolve_and_set(self._config, name, value)

    def set_define_impl(self, name, value):
        '''Implementation of set_define().
        Set the define with the given name to the given value. Both `name` and
        `value` can be references to @depends functions, in which case the
        result from these functions is used. If the result of either function
        is None, the define is not set. If the result is False, the define is
        explicitly undefined (-U).
        '''
        defines = self._config.setdefault('DEFINES', {})
        self._resolve_and_set(defines, name, value)

    def imply_option_impl(self, option, value, reason=None):
        '''Implementation of imply_option().
        Injects additional options as if they had been passed on the command
        line. The `option` argument is a string as in option()'s `name` or
        `env`. The option must be declared after `imply_option` references it.
        The `value` argument indicates the value to pass to the option.
        It can be:
        - True. In this case `imply_option` injects the positive option
          (--enable-foo/--with-foo).
              imply_option('--enable-foo', True)
              imply_option('--disable-foo', True)
          are both equivalent to `--enable-foo` on the command line.

        - False. In this case `imply_option` injects the negative option
          (--disable-foo/--without-foo).
              imply_option('--enable-foo', False)
              imply_option('--disable-foo', False)
          are both equivalent to `--disable-foo` on the command line.

        - None. In this case `imply_option` does nothing.
              imply_option('--enable-foo', None)
              imply_option('--disable-foo', None)
          are both equivalent to not passing any flag on the command line.

        - a string or a tuple. In this case `imply_option` injects the positive
          option with the given value(s).
              imply_option('--enable-foo', 'a')
              imply_option('--disable-foo', 'a')
          are both equivalent to `--enable-foo=a` on the command line.
              imply_option('--enable-foo', ('a', 'b'))
              imply_option('--disable-foo', ('a', 'b'))
          are both equivalent to `--enable-foo=a,b` on the command line.

        Because imply_option('--disable-foo', ...) can be misleading, it is
        recommended to use the positive form ('--enable' or '--with') for
        `option`.

        The `value` argument can also be (and usually is) a reference to a
        @depends function, in which case the result of that function will be
        used as per the descripted mapping above.

        The `reason` argument indicates what caused the option to be implied.
        It is necessary when it cannot be inferred from the `value`.
        '''
        # Don't do anything when --help was on the command line
        if self._help:
            return
        if not reason and isinstance(value, DependsFunction):
            deps = self._depends[value][1]
            possible_reasons = [d for d in deps if d != self._help_option]
            if len(possible_reasons) == 1:
                if isinstance(possible_reasons[0], Option):
                    reason = (self._raw_options.get(possible_reasons[0]) or
                              possible_reasons[0].option)

        if not reason or not isinstance(value, DependsFunction):
            raise ConfigureError(
                "Cannot infer what implies '%s'. Please add a `reason` to "
                "the `imply_option` call."
                % option)

        value = self._resolve(value, need_help_dependency=False)
        if value is not None:
            if isinstance(value, OptionValue):
                pass
            elif value is True:
                value = PositiveOptionValue()
            elif value is False or value == ():
                value = NegativeOptionValue()
            elif isinstance(value, types.StringTypes):
                value = PositiveOptionValue((value,))
            elif isinstance(value, tuple):
                value = PositiveOptionValue(value)
            else:
                raise TypeError("Unexpected type: '%s'" % type(value))

            option = value.format(option)
            self._helper.add(option, 'implied')
            self._implied_options[option] = inspect.stack()[1], reason

    def _prepare_function(self, func):
        '''Alter the given function global namespace with the common ground
        for @depends, and @template.
        '''
        if not inspect.isfunction(func):
            raise TypeError("Unexpected type: '%s'" % type(func))
        if func in self._prepared_functions:
            return func, func.func_globals

        glob = SandboxedGlobal(
            (k, v) for k, v in func.func_globals.iteritems()
            if (inspect.isfunction(v) and v not in self._templates) or (
                inspect.isclass(v) and issubclass(v, Exception))
        )
        glob.update(
            __builtins__=self.BUILTINS,
            __file__=self._paths[-1] if self._paths else '',
            os=self.OS,
            log=self.log_impl,
        )
        self._apply_imports(func, glob)
        func = wraps(func)(types.FunctionType(
            func.func_code,
            glob,
            func.__name__,
            func.func_defaults,
            func.func_closure
        ))
        self._prepared_functions.add(func)
        return func, glob
コード例 #17
0
    def test_precedence(self):
        foo = Option('--with-foo', nargs='*')
        helper = CommandLineHelper({}, ['cmd', '--with-foo=a,b'])
        value, option = helper.handle(foo)
        self.assertEquals(PositiveOptionValue(('a', 'b')), value)
        self.assertEquals('command-line', value.origin)
        self.assertEquals('--with-foo=a,b', option)

        helper = CommandLineHelper({},
                                   ['cmd', '--with-foo=a,b', '--without-foo'])
        value, option = helper.handle(foo)
        self.assertEquals(NegativeOptionValue(), value)
        self.assertEquals('command-line', value.origin)
        self.assertEquals('--without-foo', option)

        helper = CommandLineHelper({},
                                   ['cmd', '--without-foo', '--with-foo=a,b'])
        value, option = helper.handle(foo)
        self.assertEquals(PositiveOptionValue(('a', 'b')), value)
        self.assertEquals('command-line', value.origin)
        self.assertEquals('--with-foo=a,b', option)

        foo = Option('--with-foo', env='FOO', nargs='*')
        helper = CommandLineHelper({'FOO': ''}, ['cmd', '--with-foo=a,b'])
        value, option = helper.handle(foo)
        self.assertEquals(PositiveOptionValue(('a', 'b')), value)
        self.assertEquals('command-line', value.origin)
        self.assertEquals('--with-foo=a,b', option)

        helper = CommandLineHelper({'FOO': 'a,b'}, ['cmd', '--without-foo'])
        value, option = helper.handle(foo)
        self.assertEquals(NegativeOptionValue(), value)
        self.assertEquals('command-line', value.origin)
        self.assertEquals('--without-foo', option)

        helper = CommandLineHelper({'FOO': ''}, ['cmd', '--with-bar=a,b'])
        value, option = helper.handle(foo)
        self.assertEquals(NegativeOptionValue(), value)
        self.assertEquals('environment', value.origin)
        self.assertEquals('FOO=', option)

        helper = CommandLineHelper({'FOO': 'a,b'}, ['cmd', '--without-bar'])
        value, option = helper.handle(foo)
        self.assertEquals(PositiveOptionValue(('a', 'b')), value)
        self.assertEquals('environment', value.origin)
        self.assertEquals('FOO=a,b', option)

        helper = CommandLineHelper({}, ['cmd', '--with-foo=a,b', 'FOO='])
        value, option = helper.handle(foo)
        self.assertEquals(NegativeOptionValue(), value)
        self.assertEquals('command-line', value.origin)
        self.assertEquals('FOO=', option)

        helper = CommandLineHelper({}, ['cmd', '--without-foo', 'FOO=a,b'])
        value, option = helper.handle(foo)
        self.assertEquals(PositiveOptionValue(('a', 'b')), value)
        self.assertEquals('command-line', value.origin)
        self.assertEquals('FOO=a,b', option)

        helper = CommandLineHelper({}, ['cmd', 'FOO=', '--with-foo=a,b'])
        value, option = helper.handle(foo)
        self.assertEquals(PositiveOptionValue(('a', 'b')), value)
        self.assertEquals('command-line', value.origin)
        self.assertEquals('--with-foo=a,b', option)

        helper = CommandLineHelper({}, ['cmd', 'FOO=a,b', '--without-foo'])
        value, option = helper.handle(foo)
        self.assertEquals(NegativeOptionValue(), value)
        self.assertEquals('command-line', value.origin)
        self.assertEquals('--without-foo', option)
コード例 #18
0
ファイル: __init__.py プロジェクト: ciwei100000/mozjs-debian
class ConfigureSandbox(dict):
    """Represents a sandbox for executing Python code for build configuration.
    This is a different kind of sandboxing than the one used for moz.build
    processing.

    The sandbox has 9 primitives:
    - option
    - depends
    - template
    - imports
    - include
    - set_config
    - set_define
    - imply_option
    - only_when

    `option`, `include`, `set_config`, `set_define` and `imply_option` are
    functions. `depends`, `template`, and `imports` are decorators. `only_when`
    is a context_manager.

    These primitives are declared as name_impl methods to this class and
    the mapping name -> name_impl is done automatically in __getitem__.

    Additional primitives should be frowned upon to keep the sandbox itself as
    simple as possible. Instead, helpers should be created within the sandbox
    with the existing primitives.

    The sandbox is given, at creation, a dict where the yielded configuration
    will be stored.

        config = {}
        sandbox = ConfigureSandbox(config)
        sandbox.run(path)
        do_stuff(config)
    """

    # The default set of builtins. We expose unicode as str to make sandboxed
    # files more python3-ready.
    BUILTINS = ReadOnlyDict({
        b: getattr(__builtin__, b, None)
        for b in ('None', 'False', 'True', 'int', 'bool', 'any', 'all', 'len',
                  'list', 'tuple', 'set', 'dict', 'isinstance', 'getattr',
                  'hasattr', 'enumerate', 'range', 'zip', 'AssertionError',
                  '__build_class__',  # will be None on py2
                  )
    }, __import__=forbidden_import, str=six.text_type)

    # Expose a limited set of functions from os.path
    OS = ReadOnlyNamespace(path=ReadOnlyNamespace(**{
        k: getattr(mozpath, k, getattr(os.path, k))
        for k in ('abspath', 'basename', 'dirname', 'isabs', 'join',
                  'normcase', 'normpath', 'realpath', 'relpath')
    }))

    def __init__(self, config, environ=os.environ, argv=sys.argv,
                 stdout=sys.stdout, stderr=sys.stderr, logger=None):
        dict.__setitem__(self, '__builtins__', self.BUILTINS)

        self._environ = dict(environ)

        self._paths = []
        self._all_paths = set()
        self._templates = set()
        # Associate SandboxDependsFunctions to DependsFunctions.
        self._depends = OrderedDict()
        self._seen = set()
        # Store the @imports added to a given function.
        self._imports = {}

        self._options = OrderedDict()
        # Store raw option (as per command line or environment) for each Option
        self._raw_options = OrderedDict()

        # Store options added with `imply_option`, and the reason they were
        # added (which can either have been given to `imply_option`, or
        # inferred. Their order matters, so use a list.
        self._implied_options = []

        # Store all results from _prepare_function
        self._prepared_functions = set()

        # Queue of functions to execute, with their arguments
        self._execution_queue = []

        # Store the `when`s associated to some options.
        self._conditions = {}

        # A list of conditions to apply as a default `when` for every *_impl()
        self._default_conditions = []

        self._helper = CommandLineHelper(environ, argv)

        assert isinstance(config, dict)
        self._config = config

        # Tracks how many templates "deep" we are in the stack.
        self._template_depth = 0

        logging.addLevelName(TRACE, 'TRACE')
        if logger is None:
            logger = moz_logger = logging.getLogger('moz.configure')
            logger.setLevel(logging.DEBUG)
            formatter = logging.Formatter('%(levelname)s: %(message)s')
            handler = ConfigureOutputHandler(stdout, stderr)
            handler.setFormatter(formatter)
            queue_debug = handler.queue_debug
            logger.addHandler(handler)

        else:
            assert isinstance(logger, logging.Logger)
            moz_logger = None
            @contextmanager
            def queue_debug():
                yield

        self._logger = logger

        # Some callers will manage to log a bytestring with characters in it
        # that can't be converted to ascii. Make our log methods robust to this
        # by detecting the encoding that a producer is likely to have used.
        encoding = getpreferredencoding()

        def wrapped_log_method(logger, key):
            method = getattr(logger, key)

            def wrapped(*args, **kwargs):
                out_args = [
                    six.ensure_text(arg, encoding=encoding or 'utf-8')
                    if isinstance(arg, six.binary_type) else arg for arg in args
                ]
                return method(*out_args, **kwargs)
            return wrapped

        log_namespace = {
            k: wrapped_log_method(logger, k)
            for k in ('debug', 'info', 'warning', 'error')
        }
        log_namespace['queue_debug'] = queue_debug
        self.log_impl = ReadOnlyNamespace(**log_namespace)

        self._help = None
        self._help_option = self.option_impl(
            '--help', help='print this message', category=HELP_OPTIONS_CATEGORY)
        self._seen.add(self._help_option)

        self._always = DependsFunction(self, lambda: True, [])
        self._never = DependsFunction(self, lambda: False, [])

        if self._value_for(self._help_option):
            self._help = HelpFormatter(argv[0])
            self._help.add(self._help_option)
        elif moz_logger:
            handler = logging.FileHandler('config.log', mode='w', delay=True,
                                          encoding='utf-8')
            handler.setFormatter(formatter)
            logger.addHandler(handler)

    def include_file(self, path):
        '''Include one file in the sandbox. Users of this class probably want
        to use `run` instead.

        Note: this will execute all template invocations, as well as @depends
        functions that depend on '--help', but nothing else.
        '''

        if self._paths:
            path = mozpath.join(mozpath.dirname(self._paths[-1]), path)
            path = mozpath.normpath(path)
            if not mozpath.basedir(path, (mozpath.dirname(self._paths[0]),)):
                raise ConfigureError(
                    'Cannot include `%s` because it is not in a subdirectory '
                    'of `%s`' % (path, mozpath.dirname(self._paths[0])))
        else:
            path = mozpath.realpath(mozpath.abspath(path))
        if path in self._all_paths:
            raise ConfigureError(
                'Cannot include `%s` because it was included already.' % path)
        self._paths.append(path)
        self._all_paths.add(path)

        source = open(path, 'rb').read()

        code = compile(source, path, 'exec')

        exec_(code, self)

        self._paths.pop(-1)

    def run(self, path=None):
        '''Executes the given file within the sandbox, as well as everything
        pending from any other included file, and ensure the overall
        consistency of the executed script(s).'''
        if path:
            self.include_file(path)

        for option in six.itervalues(self._options):
            # All options must be referenced by some @depends function
            if option not in self._seen:
                raise ConfigureError(
                    'Option `%s` is not handled ; reference it with a @depends'
                    % option.option
                )

            self._value_for(option)

        # All implied options should exist.
        for implied_option in self._implied_options:
            value = self._resolve(implied_option.value)
            if value is not None:
                # There are two ways to end up here: either the implied option
                # is unknown, or it's known but there was a dependency loop
                # that prevented the implication from being applied.
                option = self._options.get(implied_option.name)
                if not option:
                    raise ConfigureError(
                        '`%s`, emitted from `%s` line %d, is unknown.'
                        % (implied_option.option, implied_option.caller[1],
                           implied_option.caller[2]))
                # If the option is known, check that the implied value doesn't
                # conflict with what value was attributed to the option.
                if (implied_option.when and
                        not self._value_for(implied_option.when)):
                    continue
                option_value = self._value_for_option(option)
                if value != option_value:
                    reason = implied_option.reason
                    if isinstance(reason, Option):
                        reason = self._raw_options.get(reason) or reason.option
                        reason = reason.split('=', 1)[0]
                    value = OptionValue.from_(value)
                    raise InvalidOptionError(
                        "'%s' implied by '%s' conflicts with '%s' from the %s"
                        % (value.format(option.option), reason,
                           option_value.format(option.option), option_value.origin))

        # All options should have been removed (handled) by now.
        for arg in self._helper:
            without_value = arg.split('=', 1)[0]
            msg = 'Unknown option: %s' % without_value
            if self._help:
                self._logger.warning(msg)
            else:
                raise InvalidOptionError(msg)

        # Run the execution queue
        for func, args in self._execution_queue:
            func(*args)

        if self._help:
            with LineIO(self.log_impl.info) as out:
                self._help.usage(out)

    def __getitem__(self, key):
        impl = '%s_impl' % key
        func = getattr(self, impl, None)
        if func:
            return func

        return super(ConfigureSandbox, self).__getitem__(key)

    def __setitem__(self, key, value):
        if (key in self.BUILTINS or key == '__builtins__' or
                hasattr(self, '%s_impl' % key)):
            raise KeyError('Cannot reassign builtins')

        if inspect.isfunction(value) and value not in self._templates:
            value = self._prepare_function(value)

        elif (not isinstance(value, SandboxDependsFunction) and
                value not in self._templates and
                not (inspect.isclass(value) and issubclass(value, Exception))):
            raise KeyError('Cannot assign `%s` because it is neither a '
                           '@depends nor a @template' % key)

        if isinstance(value, SandboxDependsFunction):
            self._depends[value].name = key

        return super(ConfigureSandbox, self).__setitem__(key, value)

    def _resolve(self, arg):
        if isinstance(arg, SandboxDependsFunction):
            return self._value_for_depends(self._depends[arg])
        return arg

    def _value_for(self, obj):
        if isinstance(obj, SandboxDependsFunction):
            assert obj in self._depends
            return self._value_for_depends(self._depends[obj])

        elif isinstance(obj, DependsFunction):
            return self._value_for_depends(obj)

        elif isinstance(obj, Option):
            return self._value_for_option(obj)

        assert False

    @memoize
    def _value_for_depends(self, obj):
        value = obj.result()
        self._logger.log(TRACE, '%r = %r', obj, value)
        return value

    @memoize
    def _value_for_option(self, option):
        implied = {}
        matching_implied_options = [
            o for o in self._implied_options if o.name in (option.name, option.env)
        ]
        # Update self._implied_options before going into the loop with the non-matching
        # options.
        self._implied_options = [
            o for o in self._implied_options if o.name not in (option.name, option.env)
        ]

        for implied_option in matching_implied_options:
            if (implied_option.when and
                not self._value_for(implied_option.when)):
                continue

            value = self._resolve(implied_option.value)

            if value is not None:
                value = OptionValue.from_(value)
                opt = value.format(implied_option.option)
                self._helper.add(opt, 'implied')
                implied[opt] = implied_option

        try:
            value, option_string = self._helper.handle(option)
        except ConflictingOptionError as e:
            reason = implied[e.arg].reason
            if isinstance(reason, Option):
                reason = self._raw_options.get(reason) or reason.option
                reason = reason.split('=', 1)[0]
            raise InvalidOptionError(
                "'%s' implied by '%s' conflicts with '%s' from the %s"
                % (e.arg, reason, e.old_arg, e.old_origin))

        if value.origin == 'implied':
            recursed_value = getattr(self, '__value_for_option').get((option,))
            if recursed_value is not None:
                _, filename, line, _, _, _ = implied[value.format(option.option)].caller
                raise ConfigureError(
                    "'%s' appears somewhere in the direct or indirect dependencies when "
                    "resolving imply_option at %s:%d" % (option.option, filename, line))

        if option_string:
            self._raw_options[option] = option_string

        when = self._conditions.get(option)
        # If `when` resolves to a false-ish value, we always return None.
        # This makes option(..., when='--foo') equivalent to
        # option(..., when=depends('--foo')(lambda x: x)).
        if when and not self._value_for(when) and value is not None:
            # If the option was passed explicitly, we throw an error that
            # the option is not available. Except when the option was passed
            # from the environment, because that would be too cumbersome.
            if value.origin not in ('default', 'environment'):
                raise InvalidOptionError(
                    '%s is not available in this configuration'
                    % option_string.split('=', 1)[0])
            self._logger.log(TRACE, '%r = None', option)
            return None

        self._logger.log(TRACE, '%r = %r', option, value)
        return value

    def _dependency(self, arg, callee_name, arg_name=None):
        if isinstance(arg, six.string_types):
            prefix, name, values = Option.split_option(arg)
            if values != ():
                raise ConfigureError("Option must not contain an '='")
            if name not in self._options:
                raise ConfigureError("'%s' is not a known option. "
                                     "Maybe it's declared too late?"
                                     % arg)
            arg = self._options[name]
            self._seen.add(arg)
        elif isinstance(arg, SandboxDependsFunction):
            assert arg in self._depends
            arg = self._depends[arg]
        else:
            raise TypeError(
                "Cannot use object of type '%s' as %sargument to %s"
                % (type(arg).__name__, '`%s` ' % arg_name if arg_name else '',
                   callee_name))
        return arg

    def _normalize_when(self, when, callee_name):
        if when is True:
            when = self._always
        elif when is False:
            when = self._never
        elif when is not None:
            when = self._dependency(when, callee_name, 'when')

        if self._default_conditions:
            # Create a pseudo @depends function for the combination of all
            # default conditions and `when`.
            dependencies = [when] if when else []
            dependencies.extend(self._default_conditions)
            if len(dependencies) == 1:
                return dependencies[0]
            return CombinedDependsFunction(self, all, dependencies)
        return when

    @contextmanager
    def only_when_impl(self, when):
        '''Implementation of only_when()

        `only_when` is a context manager that essentially makes calls to
        other sandbox functions within the context block ignored.
        '''
        when = self._normalize_when(when, 'only_when')
        if when and self._default_conditions[-1:] != [when]:
            self._default_conditions.append(when)
            yield
            self._default_conditions.pop()
        else:
            yield

    def option_impl(self, *args, **kwargs):
        '''Implementation of option()
        This function creates and returns an Option() object, passing it the
        resolved arguments (uses the result of functions when functions are
        passed). In most cases, the result of this function is not expected to
        be used.
        Command line argument/environment variable parsing for this Option is
        handled here.
        '''
        when = self._normalize_when(kwargs.get('when'), 'option')
        args = [self._resolve(arg) for arg in args]
        kwargs = {k: self._resolve(v) for k, v in six.iteritems(kwargs)
                  if k != 'when'}
        # The Option constructor needs to look up the stack to infer a category
        # for the Option, since the category is based on the filename where the
        # Option is defined. However, if the Option is defined in a template, we
        # want the category to reference the caller of the template rather than
        # the caller of the option() function.
        kwargs['define_depth'] = self._template_depth * 3
        option = Option(*args, **kwargs)
        if when:
            self._conditions[option] = when
        if option.name in self._options:
            raise ConfigureError('Option `%s` already defined' % option.option)
        if option.env in self._options:
            raise ConfigureError('Option `%s` already defined' % option.env)
        if option.name:
            self._options[option.name] = option
        if option.env:
            self._options[option.env] = option

        if self._help and (when is None or self._value_for(when)):
            self._help.add(option)

        return option

    def depends_impl(self, *args, **kwargs):
        '''Implementation of @depends()
        This function is a decorator. It returns a function that subsequently
        takes a function and returns a dummy function. The dummy function
        identifies the actual function for the sandbox, while preventing
        further function calls from within the sandbox.

        @depends() takes a variable number of option strings or dummy function
        references. The decorated function is called as soon as the decorator
        is called, and the arguments it receives are the OptionValue or
        function results corresponding to each of the arguments to @depends.
        As an exception, when a HelpFormatter is attached, only functions that
        have '--help' in their @depends argument list are called.

        The decorated function is altered to use a different global namespace
        for its execution. This different global namespace exposes a limited
        set of functions from os.path.
        '''
        for k in kwargs:
            if k != 'when':
                raise TypeError(
                    "depends_impl() got an unexpected keyword argument '%s'"
                    % k)

        when = self._normalize_when(kwargs.get('when'), '@depends')

        if not when and not args:
            raise ConfigureError('@depends needs at least one argument')

        dependencies = tuple(self._dependency(arg, '@depends') for arg in args)

        conditions = [
            self._conditions[d]
            for d in dependencies
            if d in self._conditions and isinstance(d, Option)
        ]
        for c in conditions:
            if c != when:
                raise ConfigureError('@depends function needs the same `when` '
                                     'as options it depends on')

        def decorator(func):
            if inspect.isgeneratorfunction(func):
                raise ConfigureError(
                    'Cannot decorate generator functions with @depends')
            func = self._prepare_function(func)
            depends = DependsFunction(self, func, dependencies, when=when)
            return depends.sandboxed

        return decorator

    def include_impl(self, what, when=None):
        '''Implementation of include().
        Allows to include external files for execution in the sandbox.
        It is possible to use a @depends function as argument, in which case
        the result of the function is the file name to include. This latter
        feature is only really meant for --enable-application/--enable-project.
        '''
        with self.only_when_impl(when):
            what = self._resolve(what)
            if what:
                if not isinstance(what, six.string_types):
                    raise TypeError("Unexpected type: '%s'" % type(what).__name__)
                self.include_file(what)

    def template_impl(self, func):
        '''Implementation of @template.
        This function is a decorator. Template functions are called
        immediately. They are altered so that their global namespace exposes
        a limited set of functions from os.path, as well as `depends` and
        `option`.
        Templates allow to simplify repetitive constructs, or to implement
        helper decorators and somesuch.
        '''
        def update_globals(glob):
            glob.update(
                (k[:-len('_impl')], getattr(self, k))
                for k in dir(self) if k.endswith('_impl') and k != 'template_impl'
            )
            glob.update((k, v) for k, v in six.iteritems(self) if k not in glob)

        template = self._prepare_function(func, update_globals)

        # Any function argument to the template must be prepared to be sandboxed.
        # If the template itself returns a function (in which case, it's very
        # likely a decorator), that function must be prepared to be sandboxed as
        # well.
        def wrap_template(template):
            isfunction = inspect.isfunction

            def maybe_prepare_function(obj):
                if isfunction(obj):
                    return self._prepare_function(obj)
                return obj

            # The following function may end up being prepared to be sandboxed,
            # so it mustn't depend on anything from the global scope in this
            # file. It can however depend on variables from the closure, thus
            # maybe_prepare_function and isfunction are declared above to be
            # available there.
            @self.wraps(template)
            def wrapper(*args, **kwargs):
                args = [maybe_prepare_function(arg) for arg in args]
                kwargs = {k: maybe_prepare_function(v)
                          for k, v in kwargs.items()}
                self._template_depth += 1
                ret = template(*args, **kwargs)
                self._template_depth -= 1
                if isfunction(ret):
                    # We can't expect the sandboxed code to think about all the
                    # details of implementing decorators, so do some of the
                    # work for them. If the function takes exactly one function
                    # as argument and returns a function, it must be a
                    # decorator, so mark the returned function as wrapping the
                    # function passed in.
                    if len(args) == 1 and not kwargs and isfunction(args[0]):
                        ret = self.wraps(args[0])(ret)
                    return wrap_template(ret)
                return ret
            return wrapper

        wrapper = wrap_template(template)
        self._templates.add(wrapper)
        return wrapper

    def wraps(self, func):
        return wraps(func)

    RE_MODULE = re.compile('^[a-zA-Z0-9_\.]+$')

    def imports_impl(self, _import, _from=None, _as=None):
        '''Implementation of @imports.
        This decorator imports the given _import from the given _from module
        optionally under a different _as name.
        The options correspond to the various forms for the import builtin.

            @imports('sys')
            @imports(_from='mozpack', _import='path', _as='mozpath')
        '''
        for value, required in (
                (_import, True), (_from, False), (_as, False)):

            if not isinstance(value, six.string_types) and (
                    required or value is not None):
                raise TypeError("Unexpected type: '%s'" % type(value).__name__)
            if value is not None and not self.RE_MODULE.match(value):
                raise ValueError("Invalid argument to @imports: '%s'" % value)
        if _as and '.' in _as:
            raise ValueError("Invalid argument to @imports: '%s'" % _as)

        def decorator(func):
            if func in self._templates:
                raise ConfigureError(
                    '@imports must appear after @template')
            if func in self._depends:
                raise ConfigureError(
                    '@imports must appear after @depends')
            # For the imports to apply in the order they appear in the
            # .configure file, we accumulate them in reverse order and apply
            # them later.
            imports = self._imports.setdefault(func, [])
            imports.insert(0, (_from, _import, _as))
            return func

        return decorator

    def _apply_imports(self, func, glob):
        for _from, _import, _as in self._imports.pop(func, ()):
            _from = '%s.' % _from if _from else ''
            if _as:
                glob[_as] = self._get_one_import('%s%s' % (_from, _import))
            else:
                what = _import.split('.')[0]
                glob[what] = self._get_one_import('%s%s' % (_from, what))

    @memoized_property
    def _wrapped_os(self):
        wrapped_os = {}
        exec_('from os import *', {}, wrapped_os)
        wrapped_os['environ'] = self._environ
        return ReadOnlyNamespace(**wrapped_os)

    @memoized_property
    def _wrapped_subprocess(self):
        wrapped_subprocess = {}
        exec_('from subprocess import *', {}, wrapped_subprocess)

        def wrap(function):
            def wrapper(*args, **kwargs):
                if 'env' not in kwargs:
                    kwargs['env'] = dict(self._environ)
                # Subprocess on older Pythons can't handle unicode keys or
                # values in environment dicts while subprocess on newer Pythons
                # needs text in the env. Normalize automagically so callers
                # don't have to deal with this.
                kwargs['env'] = ensure_subprocess_env(kwargs['env'], encoding=system_encoding)
                return function(*args, **kwargs)
            return wrapper

        for f in ('call', 'check_call', 'check_output', 'Popen'):
            wrapped_subprocess[f] = wrap(wrapped_subprocess[f])

        return ReadOnlyNamespace(**wrapped_subprocess)

    def _get_one_import(self, what):
        # The special `__sandbox__` module gives access to the sandbox
        # instance.
        if what == '__sandbox__':
            return self
        # Special case for the open() builtin, because otherwise, using it
        # fails with "IOError: file() constructor not accessible in
        # restricted mode". We also make open() look more like python 3's,
        # decoding to unicode strings unless the mode says otherwise.
        if what == '__builtin__.open' or what == 'builtins.open':
            if six.PY3:
                return open

            def wrapped_open(name, mode=None, buffering=None):
                args = (name,)
                kwargs = {}
                if buffering is not None:
                    kwargs['buffering'] = buffering
                if mode is not None:
                    args += (mode,)
                    if 'b' in mode:
                        return open(*args, **kwargs)
                kwargs['encoding'] = system_encoding
                return codecs.open(*args, **kwargs)
            return wrapped_open
        # Special case os and os.environ so that os.environ is our copy of
        # the environment.
        if what == 'os.environ':
            return self._environ
        if what == 'os':
            return self._wrapped_os
        # And subprocess, so that its functions use our os.environ
        if what == 'subprocess':
            return self._wrapped_subprocess
        if what in ('subprocess.call', 'subprocess.check_call',
                    'subprocess.check_output', 'subprocess.Popen'):
            return getattr(self._wrapped_subprocess, what[len('subprocess.'):])
        # Until this proves to be a performance problem, just construct an
        # import statement and execute it.
        import_line = ''
        if '.' in what:
            _from, what = what.rsplit('.', 1)
            if _from == '__builtin__' or _from.startswith('__builtin__.'):
                _from = _from.replace('__builtin__', 'six.moves.builtins')
            import_line += 'from %s ' % _from
        if what == '__builtin__':
            what = 'six.moves.builtins'
        import_line += 'import %s as imported' % what
        glob = {}
        exec_(import_line, {}, glob)
        return glob['imported']

    def _resolve_and_set(self, data, name, value, when=None):
        # Don't set anything when --help was on the command line
        if self._help:
            return
        if when and not self._value_for(when):
            return
        name = self._resolve(name)
        if name is None:
            return
        if not isinstance(name, six.string_types):
            raise TypeError("Unexpected type: '%s'" % type(name).__name__)
        if name in data:
            raise ConfigureError(
                "Cannot add '%s' to configuration: Key already "
                "exists" % name)
        value = self._resolve(value)
        if value is not None:
            if self._logger.isEnabledFor(TRACE):
                if data is self._config:
                    self._logger.log(TRACE, 'set_config(%s, %r)', name, value)
                elif data is self._config.get('DEFINES'):
                    self._logger.log(TRACE, 'set_define(%s, %r)', name, value)
            data[name] = value

    def set_config_impl(self, name, value, when=None):
        '''Implementation of set_config().
        Set the configuration items with the given name to the given value.
        Both `name` and `value` can be references to @depends functions,
        in which case the result from these functions is used. If the result
        of either function is None, the configuration item is not set.
        '''
        when = self._normalize_when(when, 'set_config')

        self._execution_queue.append((
            self._resolve_and_set, (self._config, name, value, when)))

    def set_define_impl(self, name, value, when=None):
        '''Implementation of set_define().
        Set the define with the given name to the given value. Both `name` and
        `value` can be references to @depends functions, in which case the
        result from these functions is used. If the result of either function
        is None, the define is not set. If the result is False, the define is
        explicitly undefined (-U).
        '''
        when = self._normalize_when(when, 'set_define')

        defines = self._config.setdefault('DEFINES', {})
        self._execution_queue.append((
            self._resolve_and_set, (defines, name, value, when)))

    def imply_option_impl(self, option, value, reason=None, when=None):
        '''Implementation of imply_option().
        Injects additional options as if they had been passed on the command
        line. The `option` argument is a string as in option()'s `name` or
        `env`. The option must be declared after `imply_option` references it.
        The `value` argument indicates the value to pass to the option.
        It can be:
        - True. In this case `imply_option` injects the positive option

          (--enable-foo/--with-foo).
              imply_option('--enable-foo', True)
              imply_option('--disable-foo', True)

          are both equivalent to `--enable-foo` on the command line.

        - False. In this case `imply_option` injects the negative option

          (--disable-foo/--without-foo).
              imply_option('--enable-foo', False)
              imply_option('--disable-foo', False)

          are both equivalent to `--disable-foo` on the command line.

        - None. In this case `imply_option` does nothing.
              imply_option('--enable-foo', None)
              imply_option('--disable-foo', None)

        are both equivalent to not passing any flag on the command line.

        - a string or a tuple. In this case `imply_option` injects the positive
          option with the given value(s).

              imply_option('--enable-foo', 'a')
              imply_option('--disable-foo', 'a')

          are both equivalent to `--enable-foo=a` on the command line.
              imply_option('--enable-foo', ('a', 'b'))
              imply_option('--disable-foo', ('a', 'b'))

          are both equivalent to `--enable-foo=a,b` on the command line.

        Because imply_option('--disable-foo', ...) can be misleading, it is
        recommended to use the positive form ('--enable' or '--with') for
        `option`.

        The `value` argument can also be (and usually is) a reference to a
        @depends function, in which case the result of that function will be
        used as per the descripted mapping above.

        The `reason` argument indicates what caused the option to be implied.
        It is necessary when it cannot be inferred from the `value`.
        '''

        when = self._normalize_when(when, 'imply_option')

        # Don't do anything when --help was on the command line
        if self._help:
            return
        if not reason and isinstance(value, SandboxDependsFunction):
            deps = self._depends[value].dependencies
            possible_reasons = [d for d in deps if d != self._help_option]
            if len(possible_reasons) == 1:
                if isinstance(possible_reasons[0], Option):
                    reason = possible_reasons[0]
        if not reason and (isinstance(value, (bool, tuple)) or
                           isinstance(value, six.string_types)):
            # A reason can be provided automatically when imply_option
            # is called with an immediate value.
            _, filename, line, _, _, _ = inspect.stack()[1]
            reason = "imply_option at %s:%s" % (filename, line)

        if not reason:
            raise ConfigureError(
                "Cannot infer what implies '%s'. Please add a `reason` to "
                "the `imply_option` call."
                % option)

        prefix, name, values = Option.split_option(option)
        if values != ():
            raise ConfigureError("Implied option must not contain an '='")

        self._implied_options.append(ReadOnlyNamespace(
            option=option,
            prefix=prefix,
            name=name,
            value=value,
            caller=inspect.stack()[1],
            reason=reason,
            when=when,
        ))

    def _prepare_function(self, func, update_globals=None):
        '''Alter the given function global namespace with the common ground
        for @depends, and @template.
        '''
        if not inspect.isfunction(func):
            raise TypeError("Unexpected type: '%s'" % type(func).__name__)
        if func in self._prepared_functions:
            return func

        glob = SandboxedGlobal(
            (k, v)
            for k, v in six.iteritems(func.__globals__)
            if (inspect.isfunction(v) and v not in self._templates) or (
                inspect.isclass(v) and issubclass(v, Exception))
        )
        glob.update(
            __builtins__=self.BUILTINS,
            __file__=self._paths[-1] if self._paths else '',
            __name__=self._paths[-1] if self._paths else '',
            os=self.OS,
            log=self.log_impl,
        )
        if update_globals:
            update_globals(glob)

        # The execution model in the sandbox doesn't guarantee the execution
        # order will always be the same for a given function, and if it uses
        # variables from a closure that are changed after the function is
        # declared, depending when the function is executed, the value of the
        # variable can differ. For consistency, we force the function to use
        # the value from the earliest it can be run, which is at declaration.
        # Note this is not entirely bullet proof (if the value is e.g. a list,
        # the list contents could have changed), but covers the bases.
        closure = None
        if func.__closure__:
            def makecell(content):
                def f():
                    content
                return f.__closure__[0]

            closure = tuple(makecell(cell.cell_contents)
                            for cell in func.__closure__)

        new_func = self.wraps(func)(types.FunctionType(
            func.__code__,
            glob,
            func.__name__,
            func.__defaults__,
            closure
        ))
        @self.wraps(new_func)
        def wrapped(*args, **kwargs):
            if func in self._imports:
                self._apply_imports(func, glob)
            return new_func(*args, **kwargs)

        self._prepared_functions.add(wrapped)
        return wrapped
コード例 #19
0
    def test_extra_args(self):
        foo = Option("--with-foo", env="FOO", nargs="*")
        helper = CommandLineHelper({}, ["cmd"])
        helper.add("FOO=a,b,c", "other-origin")
        value, option = helper.handle(foo)
        self.assertEquals(PositiveOptionValue(("a", "b", "c")), value)
        self.assertEquals("other-origin", value.origin)
        self.assertEquals("FOO=a,b,c", option)

        helper = CommandLineHelper({}, ["cmd"])
        helper.add("FOO=a,b,c", "other-origin")
        helper.add("--with-foo=a,b,c", "other-origin")
        value, option = helper.handle(foo)
        self.assertEquals(PositiveOptionValue(("a", "b", "c")), value)
        self.assertEquals("other-origin", value.origin)
        self.assertEquals("--with-foo=a,b,c", option)

        # Adding conflicting options is not allowed.
        helper = CommandLineHelper({}, ["cmd"])
        helper.add("FOO=a,b,c", "other-origin")
        with self.assertRaises(ConflictingOptionError) as cm:
            helper.add("FOO=", "other-origin")
        self.assertEqual("FOO=", cm.exception.arg)
        self.assertEqual("other-origin", cm.exception.origin)
        self.assertEqual("FOO=a,b,c", cm.exception.old_arg)
        self.assertEqual("other-origin", cm.exception.old_origin)
        with self.assertRaises(ConflictingOptionError) as cm:
            helper.add("FOO=a,b", "other-origin")
        self.assertEqual("FOO=a,b", cm.exception.arg)
        self.assertEqual("other-origin", cm.exception.origin)
        self.assertEqual("FOO=a,b,c", cm.exception.old_arg)
        self.assertEqual("other-origin", cm.exception.old_origin)
        # But adding the same is allowed.
        helper.add("FOO=a,b,c", "other-origin")
        value, option = helper.handle(foo)
        self.assertEquals(PositiveOptionValue(("a", "b", "c")), value)
        self.assertEquals("other-origin", value.origin)
        self.assertEquals("FOO=a,b,c", option)

        # The same rule as above applies when using the option form vs. the
        # variable form. But we can't detect it when .add is called.
        helper = CommandLineHelper({}, ["cmd"])
        helper.add("FOO=a,b,c", "other-origin")
        helper.add("--without-foo", "other-origin")
        with self.assertRaises(ConflictingOptionError) as cm:
            helper.handle(foo)
        self.assertEqual("--without-foo", cm.exception.arg)
        self.assertEqual("other-origin", cm.exception.origin)
        self.assertEqual("FOO=a,b,c", cm.exception.old_arg)
        self.assertEqual("other-origin", cm.exception.old_origin)
        helper = CommandLineHelper({}, ["cmd"])
        helper.add("FOO=a,b,c", "other-origin")
        helper.add("--with-foo=a,b", "other-origin")
        with self.assertRaises(ConflictingOptionError) as cm:
            helper.handle(foo)
        self.assertEqual("--with-foo=a,b", cm.exception.arg)
        self.assertEqual("other-origin", cm.exception.origin)
        self.assertEqual("FOO=a,b,c", cm.exception.old_arg)
        self.assertEqual("other-origin", cm.exception.old_origin)
        helper = CommandLineHelper({}, ["cmd"])
        helper.add("FOO=a,b,c", "other-origin")
        helper.add("--with-foo=a,b,c", "other-origin")
        value, option = helper.handle(foo)
        self.assertEquals(PositiveOptionValue(("a", "b", "c")), value)
        self.assertEquals("other-origin", value.origin)
        self.assertEquals("--with-foo=a,b,c", option)

        # Conflicts are also not allowed against what is in the
        # environment/on the command line.
        helper = CommandLineHelper({}, ["cmd", "--with-foo=a,b"])
        helper.add("FOO=a,b,c", "other-origin")
        with self.assertRaises(ConflictingOptionError) as cm:
            helper.handle(foo)
        self.assertEqual("FOO=a,b,c", cm.exception.arg)
        self.assertEqual("other-origin", cm.exception.origin)
        self.assertEqual("--with-foo=a,b", cm.exception.old_arg)
        self.assertEqual("command-line", cm.exception.old_origin)

        helper = CommandLineHelper({}, ["cmd", "--with-foo=a,b"])
        helper.add("--without-foo", "other-origin")
        with self.assertRaises(ConflictingOptionError) as cm:
            helper.handle(foo)
        self.assertEqual("--without-foo", cm.exception.arg)
        self.assertEqual("other-origin", cm.exception.origin)
        self.assertEqual("--with-foo=a,b", cm.exception.old_arg)
        self.assertEqual("command-line", cm.exception.old_origin)
コード例 #20
0
ファイル: __init__.py プロジェクト: lazyparser/gecko-dev
class ConfigureSandbox(dict):
    """Represents a sandbox for executing Python code for build configuration.
    This is a different kind of sandboxing than the one used for moz.build
    processing.

    The sandbox has 9 primitives:
    - option
    - depends
    - template
    - imports
    - include
    - set_config
    - set_define
    - imply_option
    - only_when

    `option`, `include`, `set_config`, `set_define` and `imply_option` are
    functions. `depends`, `template`, and `imports` are decorators. `only_when`
    is a context_manager.

    These primitives are declared as name_impl methods to this class and
    the mapping name -> name_impl is done automatically in __getitem__.

    Additional primitives should be frowned upon to keep the sandbox itself as
    simple as possible. Instead, helpers should be created within the sandbox
    with the existing primitives.

    The sandbox is given, at creation, a dict where the yielded configuration
    will be stored.

        config = {}
        sandbox = ConfigureSandbox(config)
        sandbox.run(path)
        do_stuff(config)
    """

    # The default set of builtins. We expose unicode as str to make sandboxed
    # files more python3-ready.
    BUILTINS = ReadOnlyDict({
        b: __builtins__[b]
        for b in ('None', 'False', 'True', 'int', 'bool', 'any', 'all', 'len',
                  'list', 'tuple', 'set', 'dict', 'isinstance', 'getattr',
                  'hasattr', 'enumerate', 'range', 'zip')
    }, __import__=forbidden_import, str=unicode)

    # Expose a limited set of functions from os.path
    OS = ReadOnlyNamespace(path=ReadOnlyNamespace(**{
        k: getattr(mozpath, k, getattr(os.path, k))
        for k in ('abspath', 'basename', 'dirname', 'isabs', 'join',
                  'normcase', 'normpath', 'realpath', 'relpath')
    }))

    def __init__(self, config, environ=os.environ, argv=sys.argv,
                 stdout=sys.stdout, stderr=sys.stderr, logger=None):
        dict.__setitem__(self, '__builtins__', self.BUILTINS)

        self._paths = []
        self._all_paths = set()
        self._templates = set()
        # Associate SandboxDependsFunctions to DependsFunctions.
        self._depends = OrderedDict()
        self._seen = set()
        # Store the @imports added to a given function.
        self._imports = {}

        self._options = OrderedDict()
        # Store raw option (as per command line or environment) for each Option
        self._raw_options = OrderedDict()

        # Store options added with `imply_option`, and the reason they were
        # added (which can either have been given to `imply_option`, or
        # inferred. Their order matters, so use a list.
        self._implied_options = []

        # Store all results from _prepare_function
        self._prepared_functions = set()

        # Queue of functions to execute, with their arguments
        self._execution_queue = []

        # Store the `when`s associated to some options.
        self._conditions = {}

        # A list of conditions to apply as a default `when` for every *_impl()
        self._default_conditions = []

        self._helper = CommandLineHelper(environ, argv)

        assert isinstance(config, dict)
        self._config = config

        if logger is None:
            logger = moz_logger = logging.getLogger('moz.configure')
            logger.setLevel(logging.DEBUG)
            formatter = logging.Formatter('%(levelname)s: %(message)s')
            handler = ConfigureOutputHandler(stdout, stderr)
            handler.setFormatter(formatter)
            queue_debug = handler.queue_debug
            logger.addHandler(handler)

        else:
            assert isinstance(logger, logging.Logger)
            moz_logger = None
            @contextmanager
            def queue_debug():
                yield

        # Some callers will manage to log a bytestring with characters in it
        # that can't be converted to ascii. Make our log methods robust to this
        # by detecting the encoding that a producer is likely to have used.
        encoding = getpreferredencoding()
        def wrapped_log_method(logger, key):
            method = getattr(logger, key)
            if not encoding:
                return method
            def wrapped(*args, **kwargs):
                out_args = [
                    arg.decode(encoding) if isinstance(arg, str) else arg
                    for arg in args
                ]
                return method(*out_args, **kwargs)
            return wrapped

        log_namespace = {
            k: wrapped_log_method(logger, k)
            for k in ('debug', 'info', 'warning', 'error')
        }
        log_namespace['queue_debug'] = queue_debug
        self.log_impl = ReadOnlyNamespace(**log_namespace)

        self._help = None
        self._help_option = self.option_impl('--help',
                                             help='print this message')
        self._seen.add(self._help_option)

        self._always = DependsFunction(self, lambda: True, [])
        self._never = DependsFunction(self, lambda: False, [])

        if self._value_for(self._help_option):
            self._help = HelpFormatter(argv[0])
            self._help.add(self._help_option)
        elif moz_logger:
            handler = logging.FileHandler('config.log', mode='w', delay=True)
            handler.setFormatter(formatter)
            logger.addHandler(handler)

    def include_file(self, path):
        '''Include one file in the sandbox. Users of this class probably want

        Note: this will execute all template invocations, as well as @depends
        functions that depend on '--help', but nothing else.
        '''

        if self._paths:
            path = mozpath.join(mozpath.dirname(self._paths[-1]), path)
            path = mozpath.normpath(path)
            if not mozpath.basedir(path, (mozpath.dirname(self._paths[0]),)):
                raise ConfigureError(
                    'Cannot include `%s` because it is not in a subdirectory '
                    'of `%s`' % (path, mozpath.dirname(self._paths[0])))
        else:
            path = mozpath.realpath(mozpath.abspath(path))
        if path in self._all_paths:
            raise ConfigureError(
                'Cannot include `%s` because it was included already.' % path)
        self._paths.append(path)
        self._all_paths.add(path)

        source = open(path, 'rb').read()

        code = compile(source, path, 'exec')

        exec_(code, self)

        self._paths.pop(-1)

    def run(self, path=None):
        '''Executes the given file within the sandbox, as well as everything
        pending from any other included file, and ensure the overall
        consistency of the executed script(s).'''
        if path:
            self.include_file(path)

        for option in self._options.itervalues():
            # All options must be referenced by some @depends function
            if option not in self._seen:
                raise ConfigureError(
                    'Option `%s` is not handled ; reference it with a @depends'
                    % option.option
                )

            self._value_for(option)

        # All implied options should exist.
        for implied_option in self._implied_options:
            value = self._resolve(implied_option.value,
                                  need_help_dependency=False)
            if value is not None:
                raise ConfigureError(
                    '`%s`, emitted from `%s` line %d, is unknown.'
                    % (implied_option.option, implied_option.caller[1],
                       implied_option.caller[2]))

        # All options should have been removed (handled) by now.
        for arg in self._helper:
            without_value = arg.split('=', 1)[0]
            raise InvalidOptionError('Unknown option: %s' % without_value)

        # Run the execution queue
        for func, args in self._execution_queue:
            func(*args)

        if self._help:
            with LineIO(self.log_impl.info) as out:
                self._help.usage(out)

    def __getitem__(self, key):
        impl = '%s_impl' % key
        func = getattr(self, impl, None)
        if func:
            return func

        return super(ConfigureSandbox, self).__getitem__(key)

    def __setitem__(self, key, value):
        if (key in self.BUILTINS or key == '__builtins__' or
                hasattr(self, '%s_impl' % key)):
            raise KeyError('Cannot reassign builtins')

        if inspect.isfunction(value) and value not in self._templates:
            value, _ = self._prepare_function(value)

        elif (not isinstance(value, SandboxDependsFunction) and
                value not in self._templates and
                not (inspect.isclass(value) and issubclass(value, Exception))):
            raise KeyError('Cannot assign `%s` because it is neither a '
                           '@depends nor a @template' % key)

        if isinstance(value, SandboxDependsFunction):
            self._depends[value].func.__name__ = key

        return super(ConfigureSandbox, self).__setitem__(key, value)

    def _resolve(self, arg, need_help_dependency=True):
        if isinstance(arg, SandboxDependsFunction):
            return self._value_for_depends(self._depends[arg],
                                           need_help_dependency)
        return arg

    def _value_for(self, obj, need_help_dependency=False):
        if isinstance(obj, SandboxDependsFunction):
            assert obj in self._depends
            return self._value_for_depends(self._depends[obj],
                                           need_help_dependency)

        elif isinstance(obj, DependsFunction):
            return self._value_for_depends(obj, need_help_dependency)

        elif isinstance(obj, Option):
            return self._value_for_option(obj)

        assert False

    @memoize
    def _value_for_depends(self, obj, need_help_dependency=False):
        assert not inspect.isgeneratorfunction(obj.func)
        return obj.result

    @memoize
    def _value_for_option(self, option):
        implied = {}
        for implied_option in self._implied_options[:]:
            if implied_option.name not in (option.name, option.env):
                continue
            self._implied_options.remove(implied_option)

            if (implied_option.when and
                not self._value_for(implied_option.when)):
                continue

            value = self._resolve(implied_option.value,
                                  need_help_dependency=False)

            if value is not None:
                if isinstance(value, OptionValue):
                    pass
                elif value is True:
                    value = PositiveOptionValue()
                elif value is False or value == ():
                    value = NegativeOptionValue()
                elif isinstance(value, types.StringTypes):
                    value = PositiveOptionValue((value,))
                elif isinstance(value, tuple):
                    value = PositiveOptionValue(value)
                else:
                    raise TypeError("Unexpected type: '%s'"
                                    % type(value).__name__)

                opt = value.format(implied_option.option)
                self._helper.add(opt, 'implied')
                implied[opt] = implied_option

        try:
            value, option_string = self._helper.handle(option)
        except ConflictingOptionError as e:
            reason = implied[e.arg].reason
            if isinstance(reason, Option):
                reason = self._raw_options.get(reason) or reason.option
                reason = reason.split('=', 1)[0]
            raise InvalidOptionError(
                "'%s' implied by '%s' conflicts with '%s' from the %s"
                % (e.arg, reason, e.old_arg, e.old_origin))

        if option_string:
            self._raw_options[option] = option_string

        when = self._conditions.get(option)
        if (when and not self._value_for(when, need_help_dependency=True) and
            value is not None and value.origin != 'default'):
            if value.origin == 'environment':
                # The value we return doesn't really matter, because of the
                # requirement for @depends to have the same when.
                return None
            raise InvalidOptionError(
                '%s is not available in this configuration'
                % option_string.split('=', 1)[0])

        return value

    def _dependency(self, arg, callee_name, arg_name=None):
        if isinstance(arg, types.StringTypes):
            prefix, name, values = Option.split_option(arg)
            if values != ():
                raise ConfigureError("Option must not contain an '='")
            if name not in self._options:
                raise ConfigureError("'%s' is not a known option. "
                                     "Maybe it's declared too late?"
                                     % arg)
            arg = self._options[name]
            self._seen.add(arg)
        elif isinstance(arg, SandboxDependsFunction):
            assert arg in self._depends
            arg = self._depends[arg]
        else:
            raise TypeError(
                "Cannot use object of type '%s' as %sargument to %s"
                % (type(arg).__name__, '`%s` ' % arg_name if arg_name else '',
                   callee_name))
        return arg

    def _normalize_when(self, when, callee_name):
        if when is True:
            when = self._always
        elif when is False:
            when = self._never
        elif when is not None:
            when = self._dependency(when, callee_name, 'when')

        if self._default_conditions:
            # Create a pseudo @depends function for the combination of all
            # default conditions and `when`.
            dependencies = [when] if when else []
            dependencies.extend(self._default_conditions)
            if len(dependencies) == 1:
                return dependencies[0]
            return CombinedDependsFunction(self, all, dependencies)
        return when

    @contextmanager
    def only_when_impl(self, when):
        '''Implementation of only_when()

        `only_when` is a context manager that essentially makes calls to
        other sandbox functions within the context block ignored.
        '''
        when = self._normalize_when(when, 'only_when')
        if when and self._default_conditions[-1:] != [when]:
            self._default_conditions.append(when)
            yield
            self._default_conditions.pop()
        else:
            yield

    def option_impl(self, *args, **kwargs):
        '''Implementation of option()
        This function creates and returns an Option() object, passing it the
        resolved arguments (uses the result of functions when functions are
        passed). In most cases, the result of this function is not expected to
        be used.
        Command line argument/environment variable parsing for this Option is
        handled here.
        '''
        when = self._normalize_when(kwargs.get('when'), 'option')
        args = [self._resolve(arg) for arg in args]
        kwargs = {k: self._resolve(v) for k, v in kwargs.iteritems()
                                      if k != 'when'}
        option = Option(*args, **kwargs)
        if when:
            self._conditions[option] = when
        if option.name in self._options:
            raise ConfigureError('Option `%s` already defined' % option.option)
        if option.env in self._options:
            raise ConfigureError('Option `%s` already defined' % option.env)
        if option.name:
            self._options[option.name] = option
        if option.env:
            self._options[option.env] = option

        if self._help and (when is None or
                           self._value_for(when, need_help_dependency=True)):
            self._help.add(option)

        return option

    def depends_impl(self, *args, **kwargs):
        '''Implementation of @depends()
        This function is a decorator. It returns a function that subsequently
        takes a function and returns a dummy function. The dummy function
        identifies the actual function for the sandbox, while preventing
        further function calls from within the sandbox.

        @depends() takes a variable number of option strings or dummy function
        references. The decorated function is called as soon as the decorator
        is called, and the arguments it receives are the OptionValue or
        function results corresponding to each of the arguments to @depends.
        As an exception, when a HelpFormatter is attached, only functions that
        have '--help' in their @depends argument list are called.

        The decorated function is altered to use a different global namespace
        for its execution. This different global namespace exposes a limited
        set of functions from os.path.
        '''
        for k in kwargs:
            if k != 'when':
                raise TypeError(
                    "depends_impl() got an unexpected keyword argument '%s'"
                    % k)

        when = self._normalize_when(kwargs.get('when'), '@depends')

        if not when and not args:
            raise ConfigureError('@depends needs at least one argument')

        dependencies = tuple(self._dependency(arg, '@depends') for arg in args)

        conditions = [
            self._conditions[d]
            for d in dependencies
            if d in self._conditions and isinstance(d, Option)
        ]
        for c in conditions:
            if c != when:
                raise ConfigureError('@depends function needs the same `when` '
                                     'as options it depends on')

        def decorator(func):
            if inspect.isgeneratorfunction(func):
                raise ConfigureError(
                    'Cannot decorate generator functions with @depends')
            func, glob = self._prepare_function(func)
            depends = DependsFunction(self, func, dependencies, when=when)
            return depends.sandboxed

        return decorator

    def include_impl(self, what, when=None):
        '''Implementation of include().
        Allows to include external files for execution in the sandbox.
        It is possible to use a @depends function as argument, in which case
        the result of the function is the file name to include. This latter
        feature is only really meant for --enable-application/--enable-project.
        '''
        with self.only_when_impl(when):
            what = self._resolve(what)
            if what:
                if not isinstance(what, types.StringTypes):
                    raise TypeError("Unexpected type: '%s'" % type(what).__name__)
                self.include_file(what)

    def template_impl(self, func):
        '''Implementation of @template.
        This function is a decorator. Template functions are called
        immediately. They are altered so that their global namespace exposes
        a limited set of functions from os.path, as well as `depends` and
        `option`.
        Templates allow to simplify repetitive constructs, or to implement
        helper decorators and somesuch.
        '''
        template, glob = self._prepare_function(func)
        glob.update(
            (k[:-len('_impl')], getattr(self, k))
            for k in dir(self) if k.endswith('_impl') and k != 'template_impl'
        )
        glob.update((k, v) for k, v in self.iteritems() if k not in glob)

        # Any function argument to the template must be prepared to be sandboxed.
        # If the template itself returns a function (in which case, it's very
        # likely a decorator), that function must be prepared to be sandboxed as
        # well.
        def wrap_template(template):
            isfunction = inspect.isfunction

            def maybe_prepare_function(obj):
                if isfunction(obj):
                    func, _ = self._prepare_function(obj)
                    return func
                return obj

            # The following function may end up being prepared to be sandboxed,
            # so it mustn't depend on anything from the global scope in this
            # file. It can however depend on variables from the closure, thus
            # maybe_prepare_function and isfunction are declared above to be
            # available there.
            @self.wraps(template)
            def wrapper(*args, **kwargs):
                args = [maybe_prepare_function(arg) for arg in args]
                kwargs = {k: maybe_prepare_function(v)
                          for k, v in kwargs.iteritems()}
                ret = template(*args, **kwargs)
                if isfunction(ret):
                    # We can't expect the sandboxed code to think about all the
                    # details of implementing decorators, so do some of the
                    # work for them. If the function takes exactly one function
                    # as argument and returns a function, it must be a
                    # decorator, so mark the returned function as wrapping the
                    # function passed in.
                    if len(args) == 1 and not kwargs and isfunction(args[0]):
                        ret = self.wraps(args[0])(ret)
                    return wrap_template(ret)
                return ret
            return wrapper

        wrapper = wrap_template(template)
        self._templates.add(wrapper)
        return wrapper

    def wraps(self, func):
        return wraps(func)

    RE_MODULE = re.compile('^[a-zA-Z0-9_\.]+$')

    def imports_impl(self, _import, _from=None, _as=None):
        '''Implementation of @imports.
        This decorator imports the given _import from the given _from module
        optionally under a different _as name.
        The options correspond to the various forms for the import builtin.
            @imports('sys')
            @imports(_from='mozpack', _import='path', _as='mozpath')
        '''
        for value, required in (
                (_import, True), (_from, False), (_as, False)):

            if not isinstance(value, types.StringTypes) and (
                    required or value is not None):
                raise TypeError("Unexpected type: '%s'" % type(value).__name__)
            if value is not None and not self.RE_MODULE.match(value):
                raise ValueError("Invalid argument to @imports: '%s'" % value)
        if _as and '.' in _as:
            raise ValueError("Invalid argument to @imports: '%s'" % _as)

        def decorator(func):
            if func in self._templates:
                raise ConfigureError(
                    '@imports must appear after @template')
            if func in self._depends:
                raise ConfigureError(
                    '@imports must appear after @depends')
            # For the imports to apply in the order they appear in the
            # .configure file, we accumulate them in reverse order and apply
            # them later.
            imports = self._imports.setdefault(func, [])
            imports.insert(0, (_from, _import, _as))
            return func

        return decorator

    def _apply_imports(self, func, glob):
        for _from, _import, _as in self._imports.get(func, ()):
            _from = '%s.' % _from if _from else ''
            if _as:
                glob[_as] = self._get_one_import('%s%s' % (_from, _import))
            else:
                what = _import.split('.')[0]
                glob[what] = self._get_one_import('%s%s' % (_from, what))

    def _get_one_import(self, what):
        # The special `__sandbox__` module gives access to the sandbox
        # instance.
        if what == '__sandbox__':
            return self
        # Special case for the open() builtin, because otherwise, using it
        # fails with "IOError: file() constructor not accessible in
        # restricted mode"
        if what == '__builtin__.open':
            return lambda *args, **kwargs: open(*args, **kwargs)
        # Until this proves to be a performance problem, just construct an
        # import statement and execute it.
        import_line = ''
        if '.' in what:
            _from, what = what.rsplit('.', 1)
            import_line += 'from %s ' % _from
        import_line += 'import %s as imported' % what
        glob = {}
        exec_(import_line, {}, glob)
        return glob['imported']

    def _resolve_and_set(self, data, name, value, when=None):
        # Don't set anything when --help was on the command line
        if self._help:
            return
        if when and not self._value_for(when):
            return
        name = self._resolve(name, need_help_dependency=False)
        if name is None:
            return
        if not isinstance(name, types.StringTypes):
            raise TypeError("Unexpected type: '%s'" % type(name).__name__)
        if name in data:
            raise ConfigureError(
                "Cannot add '%s' to configuration: Key already "
                "exists" % name)
        value = self._resolve(value, need_help_dependency=False)
        if value is not None:
            data[name] = value

    def set_config_impl(self, name, value, when=None):
        '''Implementation of set_config().
        Set the configuration items with the given name to the given value.
        Both `name` and `value` can be references to @depends functions,
        in which case the result from these functions is used. If the result
        of either function is None, the configuration item is not set.
        '''
        when = self._normalize_when(when, 'set_config')

        self._execution_queue.append((
            self._resolve_and_set, (self._config, name, value, when)))

    def set_define_impl(self, name, value, when=None):
        '''Implementation of set_define().
        Set the define with the given name to the given value. Both `name` and
        `value` can be references to @depends functions, in which case the
        result from these functions is used. If the result of either function
        is None, the define is not set. If the result is False, the define is
        explicitly undefined (-U).
        '''
        when = self._normalize_when(when, 'set_define')

        defines = self._config.setdefault('DEFINES', {})
        self._execution_queue.append((
            self._resolve_and_set, (defines, name, value, when)))

    def imply_option_impl(self, option, value, reason=None, when=None):
        '''Implementation of imply_option().
        Injects additional options as if they had been passed on the command
        line. The `option` argument is a string as in option()'s `name` or
        `env`. The option must be declared after `imply_option` references it.
        The `value` argument indicates the value to pass to the option.
        It can be:
        - True. In this case `imply_option` injects the positive option
          (--enable-foo/--with-foo).
              imply_option('--enable-foo', True)
              imply_option('--disable-foo', True)
          are both equivalent to `--enable-foo` on the command line.

        - False. In this case `imply_option` injects the negative option
          (--disable-foo/--without-foo).
              imply_option('--enable-foo', False)
              imply_option('--disable-foo', False)
          are both equivalent to `--disable-foo` on the command line.

        - None. In this case `imply_option` does nothing.
              imply_option('--enable-foo', None)
              imply_option('--disable-foo', None)
          are both equivalent to not passing any flag on the command line.

        - a string or a tuple. In this case `imply_option` injects the positive
          option with the given value(s).
              imply_option('--enable-foo', 'a')
              imply_option('--disable-foo', 'a')
          are both equivalent to `--enable-foo=a` on the command line.
              imply_option('--enable-foo', ('a', 'b'))
              imply_option('--disable-foo', ('a', 'b'))
          are both equivalent to `--enable-foo=a,b` on the command line.

        Because imply_option('--disable-foo', ...) can be misleading, it is
        recommended to use the positive form ('--enable' or '--with') for
        `option`.

        The `value` argument can also be (and usually is) a reference to a
        @depends function, in which case the result of that function will be
        used as per the descripted mapping above.

        The `reason` argument indicates what caused the option to be implied.
        It is necessary when it cannot be inferred from the `value`.
        '''
        # Don't do anything when --help was on the command line
        if self._help:
            return
        if not reason and isinstance(value, SandboxDependsFunction):
            deps = self._depends[value].dependencies
            possible_reasons = [d for d in deps if d != self._help_option]
            if len(possible_reasons) == 1:
                if isinstance(possible_reasons[0], Option):
                    reason = possible_reasons[0]
        if not reason and (isinstance(value, (bool, tuple)) or
                           isinstance(value, types.StringTypes)):
            # A reason can be provided automatically when imply_option
            # is called with an immediate value.
            _, filename, line, _, _, _ = inspect.stack()[1]
            reason = "imply_option at %s:%s" % (filename, line)

        if not reason:
            raise ConfigureError(
                "Cannot infer what implies '%s'. Please add a `reason` to "
                "the `imply_option` call."
                % option)

        when = self._normalize_when(when, 'imply_option')

        prefix, name, values = Option.split_option(option)
        if values != ():
            raise ConfigureError("Implied option must not contain an '='")

        self._implied_options.append(ReadOnlyNamespace(
            option=option,
            prefix=prefix,
            name=name,
            value=value,
            caller=inspect.stack()[1],
            reason=reason,
            when=when,
        ))

    def _prepare_function(self, func):
        '''Alter the given function global namespace with the common ground
        for @depends, and @template.
        '''
        if not inspect.isfunction(func):
            raise TypeError("Unexpected type: '%s'" % type(func).__name__)
        if func in self._prepared_functions:
            return func, func.func_globals

        glob = SandboxedGlobal(
            (k, v) for k, v in func.func_globals.iteritems()
            if (inspect.isfunction(v) and v not in self._templates) or (
                inspect.isclass(v) and issubclass(v, Exception))
        )
        glob.update(
            __builtins__=self.BUILTINS,
            __file__=self._paths[-1] if self._paths else '',
            __name__=self._paths[-1] if self._paths else '',
            os=self.OS,
            log=self.log_impl,
        )

        # The execution model in the sandbox doesn't guarantee the execution
        # order will always be the same for a given function, and if it uses
        # variables from a closure that are changed after the function is
        # declared, depending when the function is executed, the value of the
        # variable can differ. For consistency, we force the function to use
        # the value from the earliest it can be run, which is at declaration.
        # Note this is not entirely bullet proof (if the value is e.g. a list,
        # the list contents could have changed), but covers the bases.
        closure = None
        if func.func_closure:
            def makecell(content):
                def f():
                    content
                return f.func_closure[0]

            closure = tuple(makecell(cell.cell_contents)
                            for cell in func.func_closure)

        new_func = self.wraps(func)(types.FunctionType(
            func.func_code,
            glob,
            func.__name__,
            func.func_defaults,
            closure
        ))
        @self.wraps(new_func)
        def wrapped(*args, **kwargs):
            if func in self._imports:
                self._apply_imports(func, glob)
                del self._imports[func]
            return new_func(*args, **kwargs)

        self._prepared_functions.add(wrapped)
        return wrapped, glob
コード例 #21
0
    def __init__(self, config, environ=os.environ, argv=sys.argv,
                 stdout=sys.stdout, stderr=sys.stderr, logger=None):
        dict.__setitem__(self, '__builtins__', self.BUILTINS)

        self._paths = []
        self._all_paths = set()
        self._templates = set()
        # Store the real function and its dependencies, behind each
        # DependsFunction generated from @depends.
        self._depends = {}
        self._seen = set()
        # Store the @imports added to a given function.
        self._imports = {}

        self._options = OrderedDict()
        # Store raw option (as per command line or environment) for each Option
        self._raw_options = OrderedDict()

        # Store options added with `imply_option`, and the reason they were
        # added (which can either have been given to `imply_option`, or
        # inferred. Their order matters, so use a list.
        self._implied_options = []

        # Store all results from _prepare_function
        self._prepared_functions = set()

        # Queue of functions to execute, with their arguments
        self._execution_queue = []

        self._helper = CommandLineHelper(environ, argv)

        assert isinstance(config, dict)
        self._config = config

        if logger is None:
            logger = moz_logger = logging.getLogger('moz.configure')
            logger.setLevel(logging.DEBUG)
            formatter = logging.Formatter('%(levelname)s: %(message)s')
            handler = ConfigureOutputHandler(stdout, stderr)
            handler.setFormatter(formatter)
            queue_debug = handler.queue_debug
            logger.addHandler(handler)

        else:
            assert isinstance(logger, logging.Logger)
            moz_logger = None
            @contextmanager
            def queue_debug():
                yield

        # Some callers will manage to log a bytestring with characters in it
        # that can't be converted to ascii. Make our log methods robust to this
        # by detecting the encoding that a producer is likely to have used.
        encoding = getpreferredencoding()
        def wrapped_log_method(logger, key):
            method = getattr(logger, key)
            if not encoding:
                return method
            def wrapped(*args, **kwargs):
                out_args = [
                    arg.decode(encoding) if isinstance(arg, str) else arg
                    for arg in args
                ]
                return method(*out_args, **kwargs)
            return wrapped

        log_namespace = {
            k: wrapped_log_method(logger, k)
            for k in ('debug', 'info', 'warning', 'error')
        }
        log_namespace['queue_debug'] = queue_debug
        self.log_impl = ReadOnlyNamespace(**log_namespace)

        self._help = None
        self._help_option = self.option_impl('--help',
                                             help='print this message')
        self._seen.add(self._help_option)
        if self._value_for(self._help_option):
            self._help = HelpFormatter(argv[0])
            self._help.add(self._help_option)
        elif moz_logger:
            handler = logging.FileHandler('config.log', mode='w', delay=True)
            handler.setFormatter(formatter)
            logger.addHandler(handler)
コード例 #22
0
ファイル: __init__.py プロジェクト: Natim/gecko-dev
class ConfigureSandbox(dict):
    """Represents a sandbox for executing Python code for build configuration.
    This is a different kind of sandboxing than the one used for moz.build
    processing.

    The sandbox has 5 primitives:
    - option
    - depends
    - template
    - advanced
    - include

    `option` and `include` are functions. `depends`, `template` and `advanced`
    are decorators.

    These primitives are declared as name_impl methods to this class and
    the mapping name -> name_impl is done automatically in __getitem__.

    Additional primitives should be frowned upon to keep the sandbox itself as
    simple as possible. Instead, helpers should be created within the sandbox
    with the existing primitives.

    The sandbox is given, at creation, a dict where the yielded configuration
    will be stored.

        config = {}
        sandbox = ConfigureSandbox(config)
        sandbox.run(path)
        do_stuff(config)
    """

    # The default set of builtins.
    BUILTINS = ReadOnlyDict({
        b: __builtins__[b]
        for b in ('None', 'False', 'True', 'int', 'bool', 'any', 'all', 'len',
                  'list', 'tuple', 'set', 'dict', 'isinstance')
    }, __import__=forbidden_import)

    # Expose a limited set of functions from os.path
    OS = ReadOnlyNamespace(path=ReadOnlyNamespace(**{
        k: getattr(mozpath, k, getattr(os.path, k))
        for k in ('abspath', 'basename', 'dirname', 'exists', 'isabs', 'isdir',
                  'isfile', 'join', 'normpath', 'realpath', 'relpath')
    }))

    def __init__(self, config, environ=os.environ, argv=sys.argv,
                 stdout=sys.stdout, stderr=sys.stderr):
        dict.__setitem__(self, '__builtins__', self.BUILTINS)

        self._paths = []
        self._templates = set()
        # Store the real function and its dependencies, behind each
        # DummyFunction generated from @depends.
        self._depends = {}
        self._seen = set()

        self._options = OrderedDict()
        # Store the raw values returned by @depends functions
        self._results = {}
        # Store values for each Option, as per returned by Option.get_value
        self._option_values = {}
        # Store raw option (as per command line or environment) for each Option
        self._raw_options = {}

        # Store options added with `imply_option`, and the reason they were
        # added (which can either have been given to `imply_option`, or
        # inferred.
        self._implied_options = {}

        # Store all results from _prepare_function
        self._prepared_functions = set()

        self._helper = CommandLineHelper(environ, argv)

        assert isinstance(config, dict)
        self._config, self._stdout, self._stderr = config, stdout, stderr

        self._help = None
        self._help_option = self.option_impl('--help',
                                             help='print this message')
        self._seen.add(self._help_option)
        # self._option_impl('--help') will have set this if --help was on the
        # command line.
        if self._option_values[self._help_option]:
            self._help = HelpFormatter(argv[0])
            self._help.add(self._help_option)

    def exec_file(self, path):
        '''Execute one file within the sandbox. Users of this class probably
        want to use `run` instead.'''

        if self._paths:
            path = mozpath.join(mozpath.dirname(self._paths[-1]), path)
            if not mozpath.basedir(path, (mozpath.dirname(self._paths[0]),)):
                raise ConfigureError(
                    'Cannot include `%s` because it is not in a subdirectory '
                    'of `%s`' % (path, mozpath.dirname(self._paths[0])))
        else:
            path = mozpath.realpath(mozpath.abspath(path))
        if path in self._paths:
            raise ConfigureError(
                'Cannot include `%s` because it was included already.' % path)
        self._paths.append(path)

        source = open(path, 'rb').read()

        code = compile(source, path, 'exec')

        exec(code, self)

        self._paths.pop(-1)

    def run(self, path):
        '''Executes the given file within the sandbox, and ensure the overall
        consistency of the executed script.'''
        self.exec_file(path)

        # All command line arguments should have been removed (handled) by now.
        for arg in self._helper:
            without_value = arg.split('=', 1)[0]
            if arg in self._implied_options:
                frameinfo, reason = self._implied_options[arg]
                raise ConfigureError(
                    '`%s`, emitted from `%s` line `%d`, was not handled.'
                    % (without_value, frameinfo[1], frameinfo[2]))
            raise InvalidOptionError('Unknown option: %s' % without_value)

        # All options must be referenced by some @depends function
        for option in self._options.itervalues():
            if option not in self._seen:
                raise ConfigureError(
                    'Option `%s` is not handled ; reference it with a @depends'
                    % option.option
                )

        if self._help:
            self._help.usage(self._stdout)

    def __getitem__(self, key):
        impl = '%s_impl' % key
        func = getattr(self, impl, None)
        if func:
            return func

        return super(ConfigureSandbox, self).__getitem__(key)

    def __setitem__(self, key, value):
        if (key in self.BUILTINS or key == '__builtins__' or
                hasattr(self, '%s_impl' % key)):
            raise KeyError('Cannot reassign builtins')

        if (not isinstance(value, DummyFunction) and
                value not in self._templates):
            raise KeyError('Cannot assign `%s` because it is neither a '
                           '@depends nor a @template' % key)

        return super(ConfigureSandbox, self).__setitem__(key, value)

    def _resolve(self, arg, need_help_dependency=True):
        if isinstance(arg, DummyFunction):
            assert arg in self._depends
            func, deps = self._depends[arg]
            assert not inspect.isgeneratorfunction(func)
            assert func in self._results
            if need_help_dependency and self._help_option not in deps:
                raise ConfigureError("Missing @depends for `%s`: '--help'" %
                                     func.__name__)
            result = self._results[func]
            return result
        return arg

    def option_impl(self, *args, **kwargs):
        '''Implementation of option()
        This function creates and returns an Option() object, passing it the
        resolved arguments (uses the result of functions when functions are
        passed). In most cases, the result of this function is not expected to
        be used.
        Command line argument/environment variable parsing for this Option is
        handled here.
        '''
        args = [self._resolve(arg) for arg in args]
        kwargs = {k: self._resolve(v) for k, v in kwargs.iteritems()}
        option = Option(*args, **kwargs)
        if option.name in self._options:
            raise ConfigureError('Option `%s` already defined'
                                 % self._options[option.name].option)
        if option.env in self._options:
            raise ConfigureError('Option `%s` already defined'
                                 % self._options[option.env].option)
        if option.name:
            self._options[option.name] = option
        if option.env:
            self._options[option.env] = option

        try:
            value, option_string = self._helper.handle(option)
        except ConflictingOptionError as e:
            frameinfo, reason = self._implied_options[e.arg]
            raise InvalidOptionError(
                "'%s' implied by '%s' conflicts with '%s' from the %s"
                % (e.arg, reason, e.old_arg, e.old_origin))

        if self._help:
            self._help.add(option)

        self._option_values[option] = value
        self._raw_options[option] = (option_string.split('=', 1)[0]
                                     if option_string else option_string)
        return option

    def depends_impl(self, *args):
        '''Implementation of @depends()
        This function is a decorator. It returns a function that subsequently
        takes a function and returns a dummy function. The dummy function
        identifies the actual function for the sandbox, while preventing
        further function calls from within the sandbox.

        @depends() takes a variable number of option strings or dummy function
        references. The decorated function is called as soon as the decorator
        is called, and the arguments it receives are the OptionValue or
        function results corresponding to each of the arguments to @depends.
        As an exception, when a HelpFormatter is attached, only functions that
        have '--help' in their @depends argument list are called.

        The decorated function is altered to use a different global namespace
        for its execution. This different global namespace exposes a limited
        set of functions from os.path.
        '''
        if not args:
            raise ConfigureError('@depends needs at least one argument')

        resolved_args = []
        dependencies = []
        for arg in args:
            if isinstance(arg, types.StringTypes):
                prefix, name, values = Option.split_option(arg)
                if values != ():
                    raise ConfigureError("Option must not contain an '='")
                if name not in self._options:
                    raise ConfigureError("'%s' is not a known option. "
                                         "Maybe it's declared too late?"
                                         % arg)
                arg = self._options[name]
                self._seen.add(arg)
                dependencies.append(arg)
                assert arg in self._option_values or self._help
                resolved_arg = self._option_values.get(arg)
            elif isinstance(arg, DummyFunction):
                assert arg in self._depends
                dependencies.append(arg)
                arg, _ = self._depends[arg]
                resolved_arg = self._results.get(arg)
            else:
                raise TypeError(
                    "Cannot use object of type '%s' as argument to @depends"
                    % type(arg))
            resolved_args.append(resolved_arg)
        dependencies = tuple(dependencies)

        def decorator(func):
            if inspect.isgeneratorfunction(func):
                raise ConfigureError(
                    'Cannot decorate generator functions with @depends')
            func, glob = self._prepare_function(func)
            dummy = wraps(func)(DummyFunction())
            self._depends[dummy] = func, dependencies
            with_help = self._help_option in dependencies
            if with_help:
                for arg in args:
                    if isinstance(arg, DummyFunction):
                        _, deps = self._depends[arg]
                        if self._help_option not in deps:
                            raise ConfigureError(
                                "`%s` depends on '--help' and `%s`. "
                                "`%s` must depend on '--help'"
                                % (func.__name__, arg.__name__, arg.__name__))

            if not self._help or with_help:
                self._results[func] = func(*resolved_args)

            return dummy

        return decorator

    def include_impl(self, what):
        '''Implementation of include().
        Allows to include external files for execution in the sandbox.
        It is possible to use a @depends function as argument, in which case
        the result of the function is the file name to include. This latter
        feature is only really meant for --enable-application/--enable-project.
        '''
        what = self._resolve(what)
        if what:
            if not isinstance(what, types.StringTypes):
                raise TypeError("Unexpected type: '%s'" % type(what))
            self.exec_file(what)

    def template_impl(self, func):
        '''Implementation of @template.
        This function is a decorator. Template functions are called
        immediately. They are altered so that their global namespace exposes
        a limited set of functions from os.path, as well as `advanced`,
        `depends` and `option`.
        Templates allow to simplify repetitive constructs, or to implement
        helper decorators and somesuch.
        '''
        template, glob = self._prepare_function(func)
        glob.update(
            (k[:-len('_impl')], getattr(self, k))
            for k in dir(self) if k.endswith('_impl') and k != 'template_impl'
        )
        self._templates.add(template)
        return template

    def advanced_impl(self, func):
        '''Implementation of @advanced.
        This function gives the decorated function access to the complete set
        of builtins, allowing the import keyword as an expected side effect.
        '''
        func, glob = self._prepare_function(func)
        glob.update(__builtins__=__builtins__)
        return func

    def _resolve_and_set(self, data, name, value):
        # Don't set anything when --help was on the command line
        if self._help:
            return
        name = self._resolve(name, need_help_dependency=False)
        if name is None:
            return
        if not isinstance(name, types.StringTypes):
            raise TypeError("Unexpected type: '%s'" % type(name))
        if name in data:
            raise ConfigureError(
                "Cannot add '%s' to configuration: Key already "
                "exists" % name)
        value = self._resolve(value, need_help_dependency=False)
        if value is not None:
            data[name] = value

    def set_config_impl(self, name, value):
        '''Implementation of set_config().
        Set the configuration items with the given name to the given value.
        Both `name` and `value` can be references to @depends functions,
        in which case the result from these functions is used. If the result
        of either function is None, the configuration item is not set.
        '''
        self._resolve_and_set(self._config, name, value)

    def set_define_impl(self, name, value):
        '''Implementation of set_define().
        Set the define with the given name to the given value. Both `name` and
        `value` can be references to @depends functions, in which case the
        result from these functions is used. If the result of either function
        is None, the define is not set. If the result is False, the define is
        explicitly undefined (-U).
        '''
        defines = self._config.setdefault('DEFINES', {})
        self._resolve_and_set(defines, name, value)

    def imply_option_impl(self, option, value, reason=None):
        '''Implementation of imply_option().
        Injects additional options as if they had been passed on the command
        line. The `option` argument is a string as in option()'s `name` or
        `env`. The option must be declared after `imply_option` references it.
        The `value` argument indicates the value to pass to the option.
        It can be:
        - True. In this case `imply_option` injects the positive option
          (--enable-foo/--with-foo).
              imply_option('--enable-foo', True)
              imply_option('--disable-foo', True)
          are both equivalent to `--enable-foo` on the command line.

        - False. In this case `imply_option` injects the negative option
          (--disable-foo/--without-foo).
              imply_option('--enable-foo', False)
              imply_option('--disable-foo', False)
          are both equivalent to `--disable-foo` on the command line.

        - None. In this case `imply_option` does nothing.
              imply_option('--enable-foo', None)
              imply_option('--disable-foo', None)
          are both equivalent to not passing any flag on the command line.

        - a string or a tuple. In this case `imply_option` injects the positive
          option with the given value(s).
              imply_option('--enable-foo', 'a')
              imply_option('--disable-foo', 'a')
          are both equivalent to `--enable-foo=a` on the command line.
              imply_option('--enable-foo', ('a', 'b'))
              imply_option('--disable-foo', ('a', 'b'))
          are both equivalent to `--enable-foo=a,b` on the command line.

        Because imply_option('--disable-foo', ...) can be misleading, it is
        recommended to use the positive form ('--enable' or '--with') for
        `option`.

        The `value` argument can also be (and usually is) a reference to a
        @depends function, in which case the result of that function will be
        used as per the descripted mapping above.

        The `reason` argument indicates what caused the option to be implied.
        It is necessary when it cannot be inferred from the `value`.
        '''
        # Don't do anything when --help was on the command line
        if self._help:
            return
        if not reason and isinstance(value, DummyFunction):
            deps = self._depends[value][1]
            possible_reasons = [d for d in deps if d != self._help_option]
            if len(possible_reasons) == 1:
                if isinstance(possible_reasons[0], Option):
                    reason = (self._raw_options.get(possible_reasons[0]) or
                              possible_reasons[0].option)

        if not reason or not isinstance(value, DummyFunction):
            raise ConfigureError(
                "Cannot infer what implies '%s'. Please add a `reason` to "
                "the `imply_option` call."
                % option)

        value = self._resolve(value, need_help_dependency=False)
        if value is not None:
            if isinstance(value, OptionValue):
                pass
            elif value is True:
                value = PositiveOptionValue()
            elif value is False or value == ():
                value = NegativeOptionValue()
            elif isinstance(value, types.StringTypes):
                value = PositiveOptionValue((value,))
            elif isinstance(value, tuple):
                value = PositiveOptionValue(value)
            else:
                raise TypeError("Unexpected type: '%s'" % type(value))

            option = value.format(option)
            self._helper.add(option, 'implied')
            self._implied_options[option] = inspect.stack()[1], reason

    def _prepare_function(self, func):
        '''Alter the given function global namespace with the common ground
        for @depends, @template and @advanced.
        '''
        if not inspect.isfunction(func):
            raise TypeError("Unexpected type: '%s'" % type(func))
        if func in self._prepared_functions:
            return func, func.func_globals

        glob = SandboxedGlobal(func.func_globals)
        glob.update(
            __builtins__=self.BUILTINS,
            __file__=self._paths[-1],
            os=self.OS,
        )
        func = wraps(func)(types.FunctionType(
            func.func_code,
            glob,
            func.__name__,
            func.func_defaults,
            func.func_closure
        ))
        self._prepared_functions.add(func)
        return func, glob
コード例 #23
0
ファイル: __init__.py プロジェクト: lazyparser/gecko-dev
    def __init__(self, config, environ=os.environ, argv=sys.argv,
                 stdout=sys.stdout, stderr=sys.stderr, logger=None):
        dict.__setitem__(self, '__builtins__', self.BUILTINS)

        self._paths = []
        self._all_paths = set()
        self._templates = set()
        # Associate SandboxDependsFunctions to DependsFunctions.
        self._depends = OrderedDict()
        self._seen = set()
        # Store the @imports added to a given function.
        self._imports = {}

        self._options = OrderedDict()
        # Store raw option (as per command line or environment) for each Option
        self._raw_options = OrderedDict()

        # Store options added with `imply_option`, and the reason they were
        # added (which can either have been given to `imply_option`, or
        # inferred. Their order matters, so use a list.
        self._implied_options = []

        # Store all results from _prepare_function
        self._prepared_functions = set()

        # Queue of functions to execute, with their arguments
        self._execution_queue = []

        # Store the `when`s associated to some options.
        self._conditions = {}

        # A list of conditions to apply as a default `when` for every *_impl()
        self._default_conditions = []

        self._helper = CommandLineHelper(environ, argv)

        assert isinstance(config, dict)
        self._config = config

        if logger is None:
            logger = moz_logger = logging.getLogger('moz.configure')
            logger.setLevel(logging.DEBUG)
            formatter = logging.Formatter('%(levelname)s: %(message)s')
            handler = ConfigureOutputHandler(stdout, stderr)
            handler.setFormatter(formatter)
            queue_debug = handler.queue_debug
            logger.addHandler(handler)

        else:
            assert isinstance(logger, logging.Logger)
            moz_logger = None
            @contextmanager
            def queue_debug():
                yield

        # Some callers will manage to log a bytestring with characters in it
        # that can't be converted to ascii. Make our log methods robust to this
        # by detecting the encoding that a producer is likely to have used.
        encoding = getpreferredencoding()
        def wrapped_log_method(logger, key):
            method = getattr(logger, key)
            if not encoding:
                return method
            def wrapped(*args, **kwargs):
                out_args = [
                    arg.decode(encoding) if isinstance(arg, str) else arg
                    for arg in args
                ]
                return method(*out_args, **kwargs)
            return wrapped

        log_namespace = {
            k: wrapped_log_method(logger, k)
            for k in ('debug', 'info', 'warning', 'error')
        }
        log_namespace['queue_debug'] = queue_debug
        self.log_impl = ReadOnlyNamespace(**log_namespace)

        self._help = None
        self._help_option = self.option_impl('--help',
                                             help='print this message')
        self._seen.add(self._help_option)

        self._always = DependsFunction(self, lambda: True, [])
        self._never = DependsFunction(self, lambda: False, [])

        if self._value_for(self._help_option):
            self._help = HelpFormatter(argv[0])
            self._help.add(self._help_option)
        elif moz_logger:
            handler = logging.FileHandler('config.log', mode='w', delay=True)
            handler.setFormatter(formatter)
            logger.addHandler(handler)
コード例 #24
0
    def test_precedence(self):
        foo = Option('--with-foo', nargs='*')
        helper = CommandLineHelper({}, ['cmd', '--with-foo=a,b'])
        value, option = helper.handle(foo)
        self.assertEquals(PositiveOptionValue(('a', 'b')), value)
        self.assertEquals('command-line', value.origin)
        self.assertEquals('--with-foo=a,b', option)

        helper = CommandLineHelper({}, ['cmd', '--with-foo=a,b',
                                        '--without-foo'])
        value, option = helper.handle(foo)
        self.assertEquals(NegativeOptionValue(), value)
        self.assertEquals('command-line', value.origin)
        self.assertEquals('--without-foo', option)

        helper = CommandLineHelper({}, ['cmd', '--without-foo',
                                        '--with-foo=a,b'])
        value, option = helper.handle(foo)
        self.assertEquals(PositiveOptionValue(('a', 'b')), value)
        self.assertEquals('command-line', value.origin)
        self.assertEquals('--with-foo=a,b', option)

        foo = Option('--with-foo', env='FOO', nargs='*')
        helper = CommandLineHelper({'FOO': ''}, ['cmd', '--with-foo=a,b'])
        value, option = helper.handle(foo)
        self.assertEquals(PositiveOptionValue(('a', 'b')), value)
        self.assertEquals('command-line', value.origin)
        self.assertEquals('--with-foo=a,b', option)

        helper = CommandLineHelper({'FOO': 'a,b'}, ['cmd', '--without-foo'])
        value, option = helper.handle(foo)
        self.assertEquals(NegativeOptionValue(), value)
        self.assertEquals('command-line', value.origin)
        self.assertEquals('--without-foo', option)

        helper = CommandLineHelper({'FOO': ''}, ['cmd', '--with-bar=a,b'])
        value, option = helper.handle(foo)
        self.assertEquals(NegativeOptionValue(), value)
        self.assertEquals('environment', value.origin)
        self.assertEquals('FOO=', option)

        helper = CommandLineHelper({'FOO': 'a,b'}, ['cmd', '--without-bar'])
        value, option = helper.handle(foo)
        self.assertEquals(PositiveOptionValue(('a', 'b')), value)
        self.assertEquals('environment', value.origin)
        self.assertEquals('FOO=a,b', option)

        helper = CommandLineHelper({}, ['cmd', '--with-foo=a,b', 'FOO='])
        value, option = helper.handle(foo)
        self.assertEquals(NegativeOptionValue(), value)
        self.assertEquals('command-line', value.origin)
        self.assertEquals('FOO=', option)

        helper = CommandLineHelper({}, ['cmd', '--without-foo', 'FOO=a,b'])
        value, option = helper.handle(foo)
        self.assertEquals(PositiveOptionValue(('a', 'b')), value)
        self.assertEquals('command-line', value.origin)
        self.assertEquals('FOO=a,b', option)

        helper = CommandLineHelper({}, ['cmd', 'FOO=', '--with-foo=a,b'])
        value, option = helper.handle(foo)
        self.assertEquals(PositiveOptionValue(('a', 'b')), value)
        self.assertEquals('command-line', value.origin)
        self.assertEquals('--with-foo=a,b', option)

        helper = CommandLineHelper({}, ['cmd', 'FOO=a,b', '--without-foo'])
        value, option = helper.handle(foo)
        self.assertEquals(NegativeOptionValue(), value)
        self.assertEquals('command-line', value.origin)
        self.assertEquals('--without-foo', option)
コード例 #25
0
ファイル: __init__.py プロジェクト: linclark/gecko-dev
class ConfigureSandbox(dict):
    """Represents a sandbox for executing Python code for build configuration.
    This is a different kind of sandboxing than the one used for moz.build
    processing.

    The sandbox has 5 primitives:
    - option
    - depends
    - template
    - advanced
    - include

    `option` and `include` are functions. `depends`, `template` and `advanced`
    are decorators.

    These primitives are declared as name_impl methods to this class and
    the mapping name -> name_impl is done automatically in __getitem__.

    Additional primitives should be frowned upon to keep the sandbox itself as
    simple as possible. Instead, helpers should be created within the sandbox
    with the existing primitives.

    The sandbox is given, at creation, a dict where the yielded configuration
    will be stored.

        config = {}
        sandbox = ConfigureSandbox(config)
        sandbox.run(path)
        do_stuff(config)
    """

    # The default set of builtins.
    BUILTINS = ReadOnlyDict({
        b: __builtins__[b]
        for b in ('None', 'False', 'True', 'int', 'bool', 'any', 'all', 'len',
                  'list', 'tuple', 'set', 'dict', 'isinstance')
    }, __import__=forbidden_import)

    # Expose a limited set of functions from os.path
    OS = ReadOnlyNamespace(path=ReadOnlyNamespace(
        abspath=mozpath.abspath,
        basename=mozpath.basename,
        dirname=mozpath.dirname,
        exists=os.path.exists,
        isabs=os.path.isabs,
        isdir=os.path.isdir,
        isfile=os.path.isfile,
        join=mozpath.join,
        normpath=mozpath.normpath,
        realpath=mozpath.realpath,
        relpath=mozpath.relpath,
    ))

    def __init__(self, config, environ=os.environ, argv=sys.argv,
                 stdout=sys.stdout, stderr=sys.stderr):
        dict.__setitem__(self, '__builtins__', self.BUILTINS)

        self._paths = []
        self._templates = set()
        self._depends = {}
        self._seen = set()

        self._options = OrderedDict()
        # Store the raw values returned by @depends functions
        self._results = {}
        # Store several kind of information:
        # - value for each Option, as per returned by Option.get_value
        # - raw option (as per command line or environment) for each value
        # - config set by each @depends function
        self._db = {}

        # Store options added with `imply_option`, and the reason they were
        # added (which can either have been given to `imply_option`, or
        # infered.
        self._implied_options = {}

        self._helper = CommandLineHelper(environ, argv)

        self._config, self._stdout, self._stderr = config, stdout, stderr

        self._help = None
        self._help_option = self.option_impl('--help',
                                             help='print this message')
        self._seen.add(self._help_option)
        # self._option_impl('--help') will have set this if --help was on the
        # command line.
        if self._db[self._help_option]:
            self._help = HelpFormatter(argv[0])
            self._help.add(self._help_option)

    def exec_file(self, path):
        '''Execute one file within the sandbox. Users of this class probably
        want to use `run` instead.'''

        if self._paths:
            path = mozpath.join(mozpath.dirname(self._paths[-1]), path)
            if not mozpath.basedir(path, (mozpath.dirname(self._paths[0]),)):
                raise ConfigureError(
                    'Cannot include `%s` because it is not in a subdirectory '
                    'of `%s`' % (path, mozpath.dirname(self._paths[0])))
        else:
            path = mozpath.realpath(mozpath.abspath(path))
        if path in self._paths:
            raise ConfigureError(
                'Cannot include `%s` because it was included already.' % path)
        self._paths.append(path)

        source = open(path, 'rb').read()

        code = compile(source, path, 'exec')

        exec(code, self)

        self._paths.pop(-1)

    def run(self, path):
        '''Executes the given file within the sandbox, and ensure the overall
        consistency of the executed script.'''
        self.exec_file(path)

        # All command line arguments should have been removed (handled) by now.
        for arg in self._helper:
            without_value = arg.split('=', 1)[0]
            if arg in self._implied_options:
                func, reason = self._implied_options[arg]
                raise ConfigureError(
                    '`%s`, emitted by `%s` in `%s`, was not handled.'
                    % (without_value, func.__name__,
                       func.func_code.co_filename))
            raise InvalidOptionError('Unknown option: %s' % without_value)

        # All options must be referenced by some @depends function
        for option in self._options.itervalues():
            if option not in self._seen:
                raise ConfigureError(
                    'Option `%s` is not handled ; reference it with a @depends'
                    % option.option
                )

        if self._help:
            self._help.usage(self._stdout)

    def __getitem__(self, key):
        impl = '%s_impl' % key
        func = getattr(self, impl, None)
        if func:
            return func

        return super(ConfigureSandbox, self).__getitem__(key)

    def __setitem__(self, key, value):
        if (key in self.BUILTINS or key == '__builtins__' or
                hasattr(self, '%s_impl' % key)):
            raise KeyError('Cannot reassign builtins')

        if (not isinstance(value, DummyFunction) and
                value not in self._templates):
            raise KeyError('Cannot assign `%s` because it is neither a '
                           '@depends nor a @template' % key)

        return super(ConfigureSandbox, self).__setitem__(key, value)

    def _resolve(self, arg):
        if isinstance(arg, DummyFunction):
            assert arg in self._depends
            func = self._depends[arg]
            assert not inspect.isgeneratorfunction(func)
            assert func in self._results
            if not func.with_help:
                raise ConfigureError("Missing @depends for `%s`: '--help'" %
                                     func.__name__)
            self._seen.add(func)
            result = self._results[func]
            return result
        return arg

    def option_impl(self, *args, **kwargs):
        '''Implementation of option()
        This function creates and returns an Option() object, passing it the
        resolved arguments (uses the result of functions when functions are
        passed). In most cases, the result of this function is not expected to
        be used.
        Command line argument/environment variable parsing for this Option is
        handled here.
        '''
        args = [self._resolve(arg) for arg in args]
        kwargs = {k: self._resolve(v) for k, v in kwargs.iteritems()}
        option = Option(*args, **kwargs)
        if option.name in self._options:
            raise ConfigureError('Option `%s` already defined'
                                 % self._options[option.name].option)
        if option.env in self._options:
            raise ConfigureError('Option `%s` already defined'
                                 % self._options[option.env].option)
        if option.name:
            self._options[option.name] = option
        if option.env:
            self._options[option.env] = option

        try:
            value, option_string = self._helper.handle(option)
        except ConflictingOptionError as e:
            func, reason = self._implied_options[e.arg]
            raise InvalidOptionError(
                "'%s' implied by '%s' conflicts with '%s' from the %s"
                % (e.arg, reason, e.old_arg, e.old_origin))

        if self._help:
            self._help.add(option)

        self._db[option] = value
        self._db[value] = (option_string.split('=', 1)[0]
                           if option_string else option_string)
        return option

    def depends_impl(self, *args):
        '''Implementation of @depends()
        This function is a decorator. It returns a function that subsequently
        takes a function and returns a dummy function. The dummy function
        identifies the actual function for the sandbox, while preventing
        further function calls from within the sandbox.

        @depends() takes a variable number of option strings or dummy function
        references. The decorated function is called as soon as the decorator
        is called, and the arguments it receives are the OptionValue or
        function results corresponding to each of the arguments to @depends.
        As an exception, when a HelpFormatter is attached, only functions that
        have '--help' in their @depends argument list are called.

        The decorated function is altered to use a different global namespace
        for its execution. This different global namespace exposes a limited
        set of functions from os.path, and two additional functions:
        `imply_option` and `set_config`. The former allows to inject additional
        options as if they had been passed on the command line. The latter
        declares new configuration items for consumption by moz.build.
        '''
        if not args:
            raise ConfigureError('@depends needs at least one argument')

        with_help = False
        resolved_args = []
        for arg in args:
            if isinstance(arg, types.StringTypes):
                prefix, name, values = Option.split_option(arg)
                if values != ():
                    raise ConfigureError("Option must not contain an '='")
                if name not in self._options:
                    raise ConfigureError("'%s' is not a known option. "
                                         "Maybe it's declared too late?"
                                         % arg)
                arg = self._options[name]
                if arg == self._help_option:
                    with_help = True
            elif isinstance(arg, DummyFunction):
                assert arg in self._depends
                arg = self._depends[arg]
            else:
                raise TypeError(
                    "Cannot use object of type '%s' as argument to @depends"
                    % type(arg))
            self._seen.add(arg)
            resolved_arg = self._results.get(arg)
            if resolved_arg is None:
                assert arg in self._db or self._help
                resolved_arg = self._db.get(arg)
            resolved_args.append(resolved_arg)

        def decorator(func):
            if inspect.isgeneratorfunction(func):
                raise ConfigureError(
                    'Cannot decorate generator functions with @depends')
            func, glob = self._prepare_function(func)
            result = DependsOutput()
            glob.update(
                imply_option=result.imply_option,
                set_config=result.__setitem__,
            )
            dummy = wraps(func)(DummyFunction())
            self._depends[dummy] = func
            func.with_help = with_help
            if with_help:
                for arg in args:
                    if (isinstance(arg, DummyFunction) and
                            not self._depends[arg].with_help):
                        raise ConfigureError(
                            "`%s` depends on '--help' and `%s`. "
                            "`%s` must depend on '--help'"
                            % (func.__name__, arg.__name__, arg.__name__))

            if self._help and not with_help:
                return dummy

            self._results[func] = func(*resolved_args)
            self._db[func] = ReadOnlyDict(result)

            for option, reason in result.implied_options:
                self._helper.add(option, 'implied')
                if not reason:
                    deps = []
                    for name, value in zip(args, resolved_args):
                        if not isinstance(value, OptionValue):
                            raise ConfigureError(
                                "Cannot infer what implied '%s'" % option)
                        if name == '--help':
                            continue
                        deps.append(value.format(self._db.get(value) or name))
                    if len(deps) != 1:
                        raise ConfigureError(
                            "Cannot infer what implied '%s'" % option)
                    reason = deps[0]

                self._implied_options[option] = func, reason

            if not self._help:
                for k, v in result.iteritems():
                    if k in self._config:
                        raise ConfigureError(
                            "Cannot add '%s' to configuration: Key already "
                            "exists" % k)
                    self._config[k] = v

            return dummy

        return decorator

    def include_impl(self, what):
        '''Implementation of include().
        Allows to include external files for execution in the sandbox.
        It is possible to use a @depends function as argument, in which case
        the result of the function is the file name to include. This latter
        feature is only really meant for --enable-application/--enable-project.
        '''
        what = self._resolve(what)
        if what:
            if not isinstance(what, types.StringTypes):
                raise TypeError("Unexpected type: '%s'" % type(what))
            self.exec_file(what)

    def template_impl(self, func):
        '''Implementation of @template.
        This function is a decorator. Template functions are called
        immediately. They are altered so that their global namespace exposes
        a limited set of functions from os.path, as well as `advanced`,
        `depends` and `option`.
        Templates allow to simplify repetitive constructs, or to implement
        helper decorators and somesuch.
        '''
        template, glob = self._prepare_function(func)
        glob.update(
            advanced=self.advanced_impl,
            depends=self.depends_impl,
            option=self.option_impl,
        )
        self._templates.add(template)
        return template

    def advanced_impl(self, func):
        '''Implementation of @advanced.
        This function gives the decorated function access to the complete set
        of builtins, allowing the import keyword as an expected side effect.
        '''
        func, glob = self._prepare_function(func)
        glob.update(__builtins__=__builtins__)
        return func

    def _prepare_function(self, func):
        '''Alter the given function global namespace with the common ground
        for @depends, @template and @advanced.
        '''
        if not inspect.isfunction(func):
            raise TypeError("Unexpected type: '%s'" % type(func))
        if isinstance(func.func_globals, SandboxedGlobal):
            return func, func.func_globals

        glob = SandboxedGlobal(func.func_globals)
        glob.update(
            __builtins__=self.BUILTINS,
            __file__=self._paths[-1],
            os=self.OS,
        )
        func = wraps(func)(types.FunctionType(
            func.func_code,
            glob,
            func.__name__,
            func.func_defaults,
            func.func_closure
        ))
        return func, glob
コード例 #26
0
    def test_extra_args(self):
        foo = Option('--with-foo', env='FOO', nargs='*')
        helper = CommandLineHelper({}, ['cmd'])
        helper.add('FOO=a,b,c', 'other-origin')
        value, option = helper.handle(foo)
        self.assertEquals(PositiveOptionValue(('a', 'b', 'c')), value)
        self.assertEquals('other-origin', value.origin)
        self.assertEquals('FOO=a,b,c', option)

        helper = CommandLineHelper({}, ['cmd'])
        helper.add('FOO=a,b,c', 'other-origin')
        helper.add('--with-foo=a,b,c', 'other-origin')
        value, option = helper.handle(foo)
        self.assertEquals(PositiveOptionValue(('a', 'b', 'c')), value)
        self.assertEquals('other-origin', value.origin)
        self.assertEquals('--with-foo=a,b,c', option)

        # Adding conflicting options is not allowed.
        helper = CommandLineHelper({}, ['cmd'])
        helper.add('FOO=a,b,c', 'other-origin')
        with self.assertRaises(ConflictingOptionError) as cm:
            helper.add('FOO=', 'other-origin')
        self.assertEqual('FOO=', cm.exception.arg)
        self.assertEqual('other-origin', cm.exception.origin)
        self.assertEqual('FOO=a,b,c', cm.exception.old_arg)
        self.assertEqual('other-origin', cm.exception.old_origin)
        with self.assertRaises(ConflictingOptionError) as cm:
            helper.add('FOO=a,b', 'other-origin')
        self.assertEqual('FOO=a,b', cm.exception.arg)
        self.assertEqual('other-origin', cm.exception.origin)
        self.assertEqual('FOO=a,b,c', cm.exception.old_arg)
        self.assertEqual('other-origin', cm.exception.old_origin)
        # But adding the same is allowed.
        helper.add('FOO=a,b,c', 'other-origin')
        value, option = helper.handle(foo)
        self.assertEquals(PositiveOptionValue(('a', 'b', 'c')), value)
        self.assertEquals('other-origin', value.origin)
        self.assertEquals('FOO=a,b,c', option)

        # The same rule as above applies when using the option form vs. the
        # variable form. But we can't detect it when .add is called.
        helper = CommandLineHelper({}, ['cmd'])
        helper.add('FOO=a,b,c', 'other-origin')
        helper.add('--without-foo', 'other-origin')
        with self.assertRaises(ConflictingOptionError) as cm:
            helper.handle(foo)
        self.assertEqual('--without-foo', cm.exception.arg)
        self.assertEqual('other-origin', cm.exception.origin)
        self.assertEqual('FOO=a,b,c', cm.exception.old_arg)
        self.assertEqual('other-origin', cm.exception.old_origin)
        helper = CommandLineHelper({}, ['cmd'])
        helper.add('FOO=a,b,c', 'other-origin')
        helper.add('--with-foo=a,b', 'other-origin')
        with self.assertRaises(ConflictingOptionError) as cm:
            helper.handle(foo)
        self.assertEqual('--with-foo=a,b', cm.exception.arg)
        self.assertEqual('other-origin', cm.exception.origin)
        self.assertEqual('FOO=a,b,c', cm.exception.old_arg)
        self.assertEqual('other-origin', cm.exception.old_origin)
        helper = CommandLineHelper({}, ['cmd'])
        helper.add('FOO=a,b,c', 'other-origin')
        helper.add('--with-foo=a,b,c', 'other-origin')
        value, option = helper.handle(foo)
        self.assertEquals(PositiveOptionValue(('a', 'b', 'c')), value)
        self.assertEquals('other-origin', value.origin)
        self.assertEquals('--with-foo=a,b,c', option)

        # Conflicts are also not allowed against what is in the
        # environment/on the command line.
        helper = CommandLineHelper({}, ['cmd', '--with-foo=a,b'])
        helper.add('FOO=a,b,c', 'other-origin')
        with self.assertRaises(ConflictingOptionError) as cm:
            helper.handle(foo)
        self.assertEqual('FOO=a,b,c', cm.exception.arg)
        self.assertEqual('other-origin', cm.exception.origin)
        self.assertEqual('--with-foo=a,b', cm.exception.old_arg)
        self.assertEqual('command-line', cm.exception.old_origin)

        helper = CommandLineHelper({}, ['cmd', '--with-foo=a,b'])
        helper.add('--without-foo', 'other-origin')
        with self.assertRaises(ConflictingOptionError) as cm:
            helper.handle(foo)
        self.assertEqual('--without-foo', cm.exception.arg)
        self.assertEqual('other-origin', cm.exception.origin)
        self.assertEqual('--with-foo=a,b', cm.exception.old_arg)
        self.assertEqual('command-line', cm.exception.old_origin)
コード例 #27
0
ファイル: __init__.py プロジェクト: ciwei100000/mozjs-debian
    def __init__(self, config, environ=os.environ, argv=sys.argv,
                 stdout=sys.stdout, stderr=sys.stderr, logger=None):
        dict.__setitem__(self, '__builtins__', self.BUILTINS)

        self._environ = dict(environ)

        self._paths = []
        self._all_paths = set()
        self._templates = set()
        # Associate SandboxDependsFunctions to DependsFunctions.
        self._depends = OrderedDict()
        self._seen = set()
        # Store the @imports added to a given function.
        self._imports = {}

        self._options = OrderedDict()
        # Store raw option (as per command line or environment) for each Option
        self._raw_options = OrderedDict()

        # Store options added with `imply_option`, and the reason they were
        # added (which can either have been given to `imply_option`, or
        # inferred. Their order matters, so use a list.
        self._implied_options = []

        # Store all results from _prepare_function
        self._prepared_functions = set()

        # Queue of functions to execute, with their arguments
        self._execution_queue = []

        # Store the `when`s associated to some options.
        self._conditions = {}

        # A list of conditions to apply as a default `when` for every *_impl()
        self._default_conditions = []

        self._helper = CommandLineHelper(environ, argv)

        assert isinstance(config, dict)
        self._config = config

        # Tracks how many templates "deep" we are in the stack.
        self._template_depth = 0

        logging.addLevelName(TRACE, 'TRACE')
        if logger is None:
            logger = moz_logger = logging.getLogger('moz.configure')
            logger.setLevel(logging.DEBUG)
            formatter = logging.Formatter('%(levelname)s: %(message)s')
            handler = ConfigureOutputHandler(stdout, stderr)
            handler.setFormatter(formatter)
            queue_debug = handler.queue_debug
            logger.addHandler(handler)

        else:
            assert isinstance(logger, logging.Logger)
            moz_logger = None
            @contextmanager
            def queue_debug():
                yield

        self._logger = logger

        # Some callers will manage to log a bytestring with characters in it
        # that can't be converted to ascii. Make our log methods robust to this
        # by detecting the encoding that a producer is likely to have used.
        encoding = getpreferredencoding()

        def wrapped_log_method(logger, key):
            method = getattr(logger, key)

            def wrapped(*args, **kwargs):
                out_args = [
                    six.ensure_text(arg, encoding=encoding or 'utf-8')
                    if isinstance(arg, six.binary_type) else arg for arg in args
                ]
                return method(*out_args, **kwargs)
            return wrapped

        log_namespace = {
            k: wrapped_log_method(logger, k)
            for k in ('debug', 'info', 'warning', 'error')
        }
        log_namespace['queue_debug'] = queue_debug
        self.log_impl = ReadOnlyNamespace(**log_namespace)

        self._help = None
        self._help_option = self.option_impl(
            '--help', help='print this message', category=HELP_OPTIONS_CATEGORY)
        self._seen.add(self._help_option)

        self._always = DependsFunction(self, lambda: True, [])
        self._never = DependsFunction(self, lambda: False, [])

        if self._value_for(self._help_option):
            self._help = HelpFormatter(argv[0])
            self._help.add(self._help_option)
        elif moz_logger:
            handler = logging.FileHandler('config.log', mode='w', delay=True,
                                          encoding='utf-8')
            handler.setFormatter(formatter)
            logger.addHandler(handler)
コード例 #28
0
class ConfigureSandbox(dict):
    """Represents a sandbox for executing Python code for build configuration.
    This is a different kind of sandboxing than the one used for moz.build
    processing.

    The sandbox has 5 primitives:
    - option
    - depends
    - template
    - advanced
    - include

    `option` and `include` are functions. `depends`, `template` and `advanced`
    are decorators.

    These primitives are declared as name_impl methods to this class and
    the mapping name -> name_impl is done automatically in __getitem__.

    Additional primitives should be frowned upon to keep the sandbox itself as
    simple as possible. Instead, helpers should be created within the sandbox
    with the existing primitives.

    The sandbox is given, at creation, a dict where the yielded configuration
    will be stored.

        config = {}
        sandbox = ConfigureSandbox(config)
        sandbox.run(path)
        do_stuff(config)
    """

    # The default set of builtins.
    BUILTINS = ReadOnlyDict(
        {
            b: __builtins__[b]
            for b in ('None', 'False', 'True', 'int', 'bool', 'any', 'all',
                      'len', 'list', 'tuple', 'set', 'dict', 'isinstance')
        },
        __import__=forbidden_import)

    # Expose a limited set of functions from os.path
    OS = ReadOnlyNamespace(path=ReadOnlyNamespace(
        abspath=mozpath.abspath,
        basename=mozpath.basename,
        dirname=mozpath.dirname,
        exists=os.path.exists,
        isabs=os.path.isabs,
        isdir=os.path.isdir,
        isfile=os.path.isfile,
        join=mozpath.join,
        normpath=mozpath.normpath,
        realpath=mozpath.realpath,
        relpath=mozpath.relpath,
    ))

    def __init__(self,
                 config,
                 environ=os.environ,
                 argv=sys.argv,
                 stdout=sys.stdout,
                 stderr=sys.stderr):
        dict.__setitem__(self, '__builtins__', self.BUILTINS)

        self._paths = []
        self._templates = set()
        self._depends = {}
        self._seen = set()

        self._options = OrderedDict()
        # Store the raw values returned by @depends functions
        self._results = {}
        # Store several kind of information:
        # - value for each Option, as per returned by Option.get_value
        # - raw option (as per command line or environment) for each value
        self._db = {}

        # Store options added with `imply_option`, and the reason they were
        # added (which can either have been given to `imply_option`, or
        # infered.
        self._implied_options = {}

        # Store all results from _prepare_function
        self._prepared_functions = set()

        self._helper = CommandLineHelper(environ, argv)

        self._config, self._stdout, self._stderr = config, stdout, stderr

        self._help = None
        self._help_option = self.option_impl('--help',
                                             help='print this message')
        self._seen.add(self._help_option)
        # self._option_impl('--help') will have set this if --help was on the
        # command line.
        if self._db[self._help_option]:
            self._help = HelpFormatter(argv[0])
            self._help.add(self._help_option)

    def exec_file(self, path):
        '''Execute one file within the sandbox. Users of this class probably
        want to use `run` instead.'''

        if self._paths:
            path = mozpath.join(mozpath.dirname(self._paths[-1]), path)
            if not mozpath.basedir(path, (mozpath.dirname(self._paths[0]), )):
                raise ConfigureError(
                    'Cannot include `%s` because it is not in a subdirectory '
                    'of `%s`' % (path, mozpath.dirname(self._paths[0])))
        else:
            path = mozpath.realpath(mozpath.abspath(path))
        if path in self._paths:
            raise ConfigureError(
                'Cannot include `%s` because it was included already.' % path)
        self._paths.append(path)

        source = open(path, 'rb').read()

        code = compile(source, path, 'exec')

        exec(code, self)

        self._paths.pop(-1)

    def run(self, path):
        '''Executes the given file within the sandbox, and ensure the overall
        consistency of the executed script.'''
        self.exec_file(path)

        # All command line arguments should have been removed (handled) by now.
        for arg in self._helper:
            without_value = arg.split('=', 1)[0]
            if arg in self._implied_options:
                func, reason = self._implied_options[arg]
                raise ConfigureError(
                    '`%s`, emitted by `%s` in `%s`, was not handled.' %
                    (without_value, func.__name__, func.func_code.co_filename))
            raise InvalidOptionError('Unknown option: %s' % without_value)

        # All options must be referenced by some @depends function
        for option in self._options.itervalues():
            if option not in self._seen:
                raise ConfigureError(
                    'Option `%s` is not handled ; reference it with a @depends'
                    % option.option)

        if self._help:
            self._help.usage(self._stdout)

    def __getitem__(self, key):
        impl = '%s_impl' % key
        func = getattr(self, impl, None)
        if func:
            return func

        return super(ConfigureSandbox, self).__getitem__(key)

    def __setitem__(self, key, value):
        if (key in self.BUILTINS or key == '__builtins__'
                or hasattr(self, '%s_impl' % key)):
            raise KeyError('Cannot reassign builtins')

        if (not isinstance(value, DummyFunction)
                and value not in self._templates):
            raise KeyError('Cannot assign `%s` because it is neither a '
                           '@depends nor a @template' % key)

        return super(ConfigureSandbox, self).__setitem__(key, value)

    def _resolve(self, arg):
        if isinstance(arg, DummyFunction):
            assert arg in self._depends
            func = self._depends[arg]
            assert not inspect.isgeneratorfunction(func)
            assert func in self._results
            if not func.with_help:
                raise ConfigureError("Missing @depends for `%s`: '--help'" %
                                     func.__name__)
            result = self._results[func]
            return result
        return arg

    def option_impl(self, *args, **kwargs):
        '''Implementation of option()
        This function creates and returns an Option() object, passing it the
        resolved arguments (uses the result of functions when functions are
        passed). In most cases, the result of this function is not expected to
        be used.
        Command line argument/environment variable parsing for this Option is
        handled here.
        '''
        args = [self._resolve(arg) for arg in args]
        kwargs = {k: self._resolve(v) for k, v in kwargs.iteritems()}
        option = Option(*args, **kwargs)
        if option.name in self._options:
            raise ConfigureError('Option `%s` already defined' %
                                 self._options[option.name].option)
        if option.env in self._options:
            raise ConfigureError('Option `%s` already defined' %
                                 self._options[option.env].option)
        if option.name:
            self._options[option.name] = option
        if option.env:
            self._options[option.env] = option

        try:
            value, option_string = self._helper.handle(option)
        except ConflictingOptionError as e:
            func, reason = self._implied_options[e.arg]
            raise InvalidOptionError(
                "'%s' implied by '%s' conflicts with '%s' from the %s" %
                (e.arg, reason, e.old_arg, e.old_origin))

        if self._help:
            self._help.add(option)

        self._db[option] = value
        self._db[value] = (option_string.split('=', 1)[0]
                           if option_string else option_string)
        return option

    def depends_impl(self, *args):
        '''Implementation of @depends()
        This function is a decorator. It returns a function that subsequently
        takes a function and returns a dummy function. The dummy function
        identifies the actual function for the sandbox, while preventing
        further function calls from within the sandbox.

        @depends() takes a variable number of option strings or dummy function
        references. The decorated function is called as soon as the decorator
        is called, and the arguments it receives are the OptionValue or
        function results corresponding to each of the arguments to @depends.
        As an exception, when a HelpFormatter is attached, only functions that
        have '--help' in their @depends argument list are called.

        The decorated function is altered to use a different global namespace
        for its execution. This different global namespace exposes a limited
        set of functions from os.path, and two additional functions:
        `imply_option` and `set_config`. The former allows to inject additional
        options as if they had been passed on the command line. The latter
        declares new configuration items for consumption by moz.build.
        '''
        if not args:
            raise ConfigureError('@depends needs at least one argument')

        with_help = False
        resolved_args = []
        for arg in args:
            if isinstance(arg, types.StringTypes):
                prefix, name, values = Option.split_option(arg)
                if values != ():
                    raise ConfigureError("Option must not contain an '='")
                if name not in self._options:
                    raise ConfigureError("'%s' is not a known option. "
                                         "Maybe it's declared too late?" % arg)
                arg = self._options[name]
                if arg == self._help_option:
                    with_help = True
                self._seen.add(arg)
                assert arg in self._db or self._help
                resolved_arg = self._db.get(arg)
            elif isinstance(arg, DummyFunction):
                assert arg in self._depends
                arg = self._depends[arg]
                resolved_arg = self._results.get(arg)
            else:
                raise TypeError(
                    "Cannot use object of type '%s' as argument to @depends" %
                    type(arg))
            resolved_args.append(resolved_arg)

        def decorator(func):
            if inspect.isgeneratorfunction(func):
                raise ConfigureError(
                    'Cannot decorate generator functions with @depends')
            func, glob = self._prepare_function(func)
            result = DependsOutput()
            glob.update(
                imply_option=result.imply_option,
                set_config=result.__setitem__,
            )
            dummy = wraps(func)(DummyFunction())
            self._depends[dummy] = func
            func.with_help = with_help
            if with_help:
                for arg in args:
                    if (isinstance(arg, DummyFunction)
                            and not self._depends[arg].with_help):
                        raise ConfigureError(
                            "`%s` depends on '--help' and `%s`. "
                            "`%s` must depend on '--help'" %
                            (func.__name__, arg.__name__, arg.__name__))

            if self._help and not with_help:
                return dummy

            self._results[func] = func(*resolved_args)

            for option, reason in result.implied_options:
                self._helper.add(option, 'implied')
                if not reason:
                    deps = []
                    for name, value in zip(args, resolved_args):
                        if not isinstance(value, OptionValue):
                            raise ConfigureError(
                                "Cannot infer what implied '%s'" % option)
                        if name == '--help':
                            continue
                        deps.append(value.format(self._db.get(value) or name))
                    if len(deps) != 1:
                        raise ConfigureError("Cannot infer what implied '%s'" %
                                             option)
                    reason = deps[0]

                self._implied_options[option] = func, reason

            if not self._help:
                for k, v in result.iteritems():
                    if k in self._config:
                        raise ConfigureError(
                            "Cannot add '%s' to configuration: Key already "
                            "exists" % k)
                    self._config[k] = v

            return dummy

        return decorator

    def include_impl(self, what):
        '''Implementation of include().
        Allows to include external files for execution in the sandbox.
        It is possible to use a @depends function as argument, in which case
        the result of the function is the file name to include. This latter
        feature is only really meant for --enable-application/--enable-project.
        '''
        what = self._resolve(what)
        if what:
            if not isinstance(what, types.StringTypes):
                raise TypeError("Unexpected type: '%s'" % type(what))
            self.exec_file(what)

    def template_impl(self, func):
        '''Implementation of @template.
        This function is a decorator. Template functions are called
        immediately. They are altered so that their global namespace exposes
        a limited set of functions from os.path, as well as `advanced`,
        `depends` and `option`.
        Templates allow to simplify repetitive constructs, or to implement
        helper decorators and somesuch.
        '''
        template, glob = self._prepare_function(func)
        glob.update(
            advanced=self.advanced_impl,
            depends=self.depends_impl,
            option=self.option_impl,
        )
        self._templates.add(template)
        return template

    def advanced_impl(self, func):
        '''Implementation of @advanced.
        This function gives the decorated function access to the complete set
        of builtins, allowing the import keyword as an expected side effect.
        '''
        func, glob = self._prepare_function(func)
        glob.update(__builtins__=__builtins__)
        return func

    def _prepare_function(self, func):
        '''Alter the given function global namespace with the common ground
        for @depends, @template and @advanced.
        '''
        if not inspect.isfunction(func):
            raise TypeError("Unexpected type: '%s'" % type(func))
        if func in self._prepared_functions:
            return func, func.func_globals

        glob = SandboxedGlobal(func.func_globals)
        glob.update(
            __builtins__=self.BUILTINS,
            __file__=self._paths[-1],
            os=self.OS,
        )
        func = wraps(func)(types.FunctionType(func.func_code, glob,
                                              func.__name__,
                                              func.func_defaults,
                                              func.func_closure))
        self._prepared_functions.add(func)
        return func, glob