예제 #1
0
    def __init__(self, route, function):
        super().__init__(route, function)
        if not self.outputs:
            self.outputs = self.api.cli.output_format

        self.interface.cli = self
        self.reaffirm_types = {}
        use_parameters = list(self.interface.parameters)
        self.additional_options = getattr(
            self.interface, "arg", getattr(self.interface, "kwarg", False)
        )
        if self.additional_options:
            use_parameters.append(self.additional_options)

        used_options = {"h", "help"}
        nargs_set = self.interface.takes_args or self.interface.takes_kwargs

        class CustomArgumentParser(argparse.ArgumentParser):
            exit_callback = None

            def exit(self, status=0, message=None):
                if self.exit_callback:
                    self.exit_callback(message)
                super().exit(status, message)

        self.parser = CustomArgumentParser(
            description=route.get("doc", self.interface.spec.__doc__)
        )
        if "version" in route:
            self.parser.add_argument(
                "-v",
                "--version",
                action="version",
                version="{0} {1}".format(
                    route.get("name", self.interface.spec.__name__), route["version"]
                ),
            )
            used_options.update(("v", "version"))

        self.context_tranforms = []
        for option in use_parameters:

            if option in self.directives:
                continue

            if option in self.interface.required or option == self.additional_options:
                args = (option,)
            else:
                short_option = option[0]
                while short_option in used_options and len(short_option) < len(option):
                    short_option = option[: len(short_option) + 1]

                used_options.add(short_option)
                used_options.add(option)
                if short_option != option:
                    args = ("-{0}".format(short_option), "--{0}".format(option))
                else:
                    args = ("--{0}".format(option),)

            kwargs = {}
            if option in self.defaults:
                kwargs["default"] = self.defaults[option]
            if option in self.interface.input_transformations:
                transform = self.interface.input_transformations[option]
                kwargs["type"] = transform
                kwargs["help"] = transform.__doc__
                if transform in (list, tuple) or isinstance(transform, types.Multiple):
                    kwargs["action"] = "append"
                    kwargs["type"] = Text()
                    self.reaffirm_types[option] = transform
                elif transform == bool or isinstance(transform, type(types.boolean)):
                    kwargs["action"] = "store_true"
                    self.reaffirm_types[option] = transform
                elif isinstance(transform, types.OneOf):
                    kwargs["choices"] = transform.values
            elif (
                option in self.interface.spec.__annotations__
                and type(self.interface.spec.__annotations__[option]) == str
            ):
                kwargs["help"] = option
            if (
                kwargs.get("type", None) == bool or kwargs.get("action", None) == "store_true"
            ) and not kwargs["default"]:
                kwargs["action"] = "store_true"
                kwargs.pop("type", None)
            elif kwargs.get("action", None) == "store_true":
                kwargs.pop("action", None) == "store_true"

            if option == self.additional_options:
                kwargs["nargs"] = "*"
            elif (
                not nargs_set
                and kwargs.get("action", None) == "append"
                and not option in self.interface.defaults
            ):
                kwargs["nargs"] = "*"
                kwargs.pop("action", "")
                nargs_set = True

            self.parser.add_argument(*args, **kwargs)

        self.api.cli.commands[route.get("name", self.interface.spec.__name__)] = self
예제 #2
0
파일: interface.py 프로젝트: byo-ai/hug
    def __init__(self, route, function):
        super().__init__(route, function)
        if not self.outputs:
            self.outputs = self.api.cli.output_format

        self.interface.cli = self
        self.reaffirm_types = {}
        use_parameters = list(self.interface.parameters)
        self.additional_options = getattr(
            self.interface, 'arg', getattr(self.interface, 'kwarg', False))
        if self.additional_options:
            use_parameters.append(self.additional_options)

        used_options = {'h', 'help'}
        nargs_set = self.interface.takes_args or self.interface.takes_kwargs

        class CustomArgumentParser(argparse.ArgumentParser):
            exit_callback = None

            def exit(self, status=0, message=None):
                if self.exit_callback:
                    self.exit_callback(message)
                super().exit(status, message)

        self.parser = CustomArgumentParser(
            description=route.get('doc', self.interface.spec.__doc__))
        if 'version' in route:
            self.parser.add_argument('-v',
                                     '--version',
                                     action='version',
                                     version="{0} {1}".format(
                                         route.get(
                                             'name',
                                             self.interface.spec.__name__),
                                         route['version']))
            used_options.update(('v', 'version'))

        self.context_tranforms = []
        for option in use_parameters:

            if option in self.directives:
                continue

            if option in self.interface.required or option == self.additional_options:
                args = (option, )
            else:
                short_option = option[0]
                while short_option in used_options and len(short_option) < len(
                        option):
                    short_option = option[:len(short_option) + 1]

                used_options.add(short_option)
                used_options.add(option)
                if short_option != option:
                    args = ('-{0}'.format(short_option),
                            '--{0}'.format(option))
                else:
                    args = ('--{0}'.format(option), )

            kwargs = {}
            if option in self.defaults:
                kwargs['default'] = self.defaults[option]
            if option in self.interface.input_transformations:
                transform = self.interface.input_transformations[option]
                kwargs['type'] = transform
                kwargs['help'] = transform.__doc__
                if transform in (list, tuple) or isinstance(
                        transform, types.Multiple):
                    kwargs['action'] = 'append'
                    kwargs['type'] = Text()
                    self.reaffirm_types[option] = transform
                elif transform == bool or isinstance(transform,
                                                     type(types.boolean)):
                    kwargs['action'] = 'store_true'
                    self.reaffirm_types[option] = transform
                elif isinstance(transform, types.OneOf):
                    kwargs['choices'] = transform.values
            elif (option in self.interface.spec.__annotations__ and type(
                    self.interface.spec.__annotations__[option]) == str):
                kwargs['help'] = option
            if ((kwargs.get('type', None) == bool
                 or kwargs.get('action', None) == 'store_true')
                    and not kwargs['default']):
                kwargs['action'] = 'store_true'
                kwargs.pop('type', None)
            elif kwargs.get('action', None) == 'store_true':
                kwargs.pop('action', None) == 'store_true'

            if option == self.additional_options:
                kwargs['nargs'] = '*'
            elif not nargs_set and kwargs.get(
                    'action', None
            ) == 'append' and not option in self.interface.defaults:
                kwargs['nargs'] = '*'
                kwargs.pop('action', '')
                nargs_set = True

            self.parser.add_argument(*args, **kwargs)

        self.api.cli.commands[route.get('name',
                                        self.interface.spec.__name__)] = self
예제 #3
0
    def __init__(self, route, function):
        super().__init__(route, function)
        self.interface.cli = self
        self.outputs = route.get('output', hug.output_format.text)

        used_options = {'h', 'help'}
        nargs_set = self.interface.takes_kargs
        self.parser = argparse.ArgumentParser(
            description=route.get('doc', self.interface.spec.__doc__))
        if 'version' in route:
            self.parser.add_argument('-v',
                                     '--version',
                                     action='version',
                                     version="{0} {1}".format(
                                         route.get(
                                             'name',
                                             self.interface.spec.__name__),
                                         route['version']))
            used_options.update(('v', 'version'))

        for option in self.interface.parameters:
            if option in self.directives:
                continue

            if option in self.interface.required:
                args = (option, )
            else:
                short_option = option[0]
                while short_option in used_options and len(short_option) < len(
                        option):
                    short_option = option[:len(short_option) + 1]

                used_options.add(short_option)
                used_options.add(option)
                if short_option != option:
                    args = ('-{0}'.format(short_option),
                            '--{0}'.format(option))
                else:
                    args = ('--{0}'.format(option), )

            kwargs = {}
            if option in self.defaults:
                kwargs['default'] = self.defaults[option]
            if option in self.interface.input_transformations:
                transform = self.interface.input_transformations[option]
                kwargs['type'] = transform
                kwargs['help'] = transform.__doc__
                if transform in (list, tuple) or isinstance(
                        transform, types.Multiple):
                    kwargs['action'] = 'append'
                    kwargs['type'] = Text()
                elif transform == bool or isinstance(transform,
                                                     type(types.boolean)):
                    kwargs['action'] = 'store_true'
                elif isinstance(transform, types.OneOf):
                    kwargs['choices'] = transform.values
            elif (option in self.interface.spec.__annotations__ and type(
                    self.interface.spec.__annotations__[option]) == str):
                kwargs['help'] = option
            if ((kwargs.get('type', None) == bool
                 or kwargs.get('action', None) == 'store_true')
                    and not kwargs['default']):
                kwargs['action'] = 'store_true'
                kwargs.pop('type', None)
            elif kwargs.get('action', None) == 'store_true':
                kwargs.pop('action', None) == 'store_true'

            if option == getattr(self.interface, 'karg', None) or ():
                kwargs['nargs'] = '*'
            elif not nargs_set and kwargs.get(
                    'action', None
            ) == 'append' and not option in self.interface.defaults:
                kwargs['nargs'] = '*'
                kwargs.pop('action', '')
                nargs_set = True

            self.parser.add_argument(*args, **kwargs)

        self.api.cli.commands[route.get('name',
                                        self.interface.spec.__name__)] = self