Example #1
0
def make_flag(source,
              names,
              default=False,
              type=None,
              help='',
              takes_argument=0):
    """Compatibility with clize<3.0 releases. Creates a parameter instance.
    See :ref:`porting-2`."""
    warnings.warn(
        'clize.legacy.make_flag is deprecated. See '
        'http://clize.readthedocs.io/en/3.1/'
        'porting.html#porting-make-flag',
        DeprecationWarning,
        stacklevel=2)
    kwargs = {}
    kwargs['aliases'] = [util.name_py2cli(alias, kw=True) for alias in names]
    if callable(source):
        return MakeflagFuncParameter(source,
                                     takes_argument=takes_argument,
                                     **kwargs)
    cls = MakeflagOptionParameter
    kwargs['argument_name'] = source
    kwargs['conv'] = type or parser.is_true
    if not takes_argument:
        return parser.FlagParameter(value=True, **kwargs)
    kwargs['default'] = default
    kwargs['takes_argument'] = takes_argument
    if takes_argument == 1 and type is int:
        cls = MakeflagIntOptionParameter
    return cls(**kwargs)
Example #2
0
 def __init__(self,
              fn,
              owner=None,
              alt=(),
              extra=(),
              help_names=('help', 'h'),
              helper_class=None,
              hide_help=False):
     """
     :param sequence alt: Alternate actions the CLI will handle.
     :param help_names: Names to use to trigger the help.
     :type help_names: sequence of strings
     :param helper_class: A callable to produce a helper object to be
         used when the help is triggered. If unset, uses `.ClizeHelp`.
     :type helper_class: a type like `.ClizeHelp`
     :param bool hide_help: Mark the parameters used to trigger the help
         as undocumented.
     """
     update_wrapper(self, fn)
     self.func = fn
     self.owner = owner
     self.alt = util.maybe_iter(alt)
     self.extra = extra
     self.help_names = help_names
     self.help_aliases = [util.name_py2cli(s, kw=True) for s in help_names]
     self.helper_class = helper_class
     self.hide_help = hide_help
Example #3
0
    def _process_alt(self, alt):
        if self.help_names:
            p = parser.FallbackCommandParameter(
                func=self.helper.cli, undocumented=self.hide_help,
                aliases=self.help_aliases)
            yield p

        for name, func in util.dict_from_names(alt).items():
            func = self.get_cli(func)
            param = parser.AlternateCommandParameter(
                undocumented=False, func=func,
                aliases=[util.name_py2cli(name, kw=True)])
            yield param
Example #4
0
    def _process_alt(self, alt):
        if self.help_names:
            p = parser.FallbackCommandParameter(
                func=self.helper.cli, undocumented=self.hide_help,
                aliases=self.help_aliases)
            yield p

        for name, func in util.dict_from_names(alt).items():
            func = self.get_cli(func)
            param = parser.AlternateCommandParameter(
                undocumented=False, func=func,
                aliases=[util.name_py2cli(name, kw=True)])
            yield param
Example #5
0
 def __init__(self, fn, owner=None, alt=(), extra=(),
              help_names=('help', 'h'), helper_class=None, hide_help=False):
     """
     :param sequence alt: Alternate actions the CLI will handle.
     :param help_names: Names to use to trigger the help.
     :type help_names: sequence of strings
     :param helper_class: A callable to produce a helper object to be
         used when the help is triggered. If unset, uses `.ClizeHelp`.
     :type helper_class: a type like `.ClizeHelp`
     :param bool hide_help: Mark the parameters used to trigger the help
         as undocumented.
     """
     update_wrapper(self, fn)
     self.func = fn
     self.owner = owner
     self.alt = util.maybe_iter(alt)
     self.extra = extra
     self.help_names = help_names
     self.help_aliases = [util.name_py2cli(s, kw=True) for s in help_names]
     self.helper_class = helper_class
     self.hide_help = hide_help
Example #6
0
def make_flag(source, names, default=False, type=bool,
              help='', takes_argument=0):
    """Compatibility with clize<3.0 releases. Creates a parameter instance.
    See :ref:`porting-2`."""
    warnings.warn('Compatibility with clize<3.0 releases. Helper function to '
                  'create alternate actions. See :ref:`porting-2`.',
                  DeprecationWarning, stacklevel=1)
    kwargs = {}
    kwargs['aliases'] = [util.name_py2cli(alias, kw=True)
                         for alias in names]
    if callable(source):
        return MakeflagParameter(source, **kwargs)
    cls = parser.OptionParameter
    kwargs['argument_name'] = source
    kwargs['default'] = default
    if not takes_argument:
        return parser.FlagParameter(value=True, **kwargs)
    kwargs['typ'] = type
    if type is int:
        cls = parser.IntOptionParameter
    return cls(**kwargs)
Example #7
0
def make_flag(source, names, default=False, type=None,
              help='', takes_argument=0):
    """Compatibility with clize<3.0 releases. Creates a parameter instance.
    See :ref:`porting-2`."""
    warnings.warn('clize.legacy.make_flag is deprecated. See '
                  'http://clize.readthedocs.org/en/3.0.x/'
                  'porting.html#porting-make-flag',
                  DeprecationWarning, stacklevel=2)
    kwargs = {}
    kwargs['aliases'] = [util.name_py2cli(alias, kw=True)
                         for alias in names]
    if callable(source):
        return MakeflagFuncParameter(source, takes_argument=takes_argument,
                                     **kwargs)
    cls = MakeflagOptionParameter
    kwargs['argument_name'] = source
    kwargs['conv'] = type or parser.is_true
    if not takes_argument:
        return parser.FlagParameter(value=True, **kwargs)
    kwargs['default'] = default
    kwargs['takes_argument'] = takes_argument
    if takes_argument == 1 and type is int:
        cls = MakeflagIntOptionParameter
    return cls(**kwargs)
Example #8
0
def _use_class(pos_cls, varargs_cls, named_cls, varkwargs_cls, kwargs, param,
               annotations):
    named = param.kind in (param.KEYWORD_ONLY, param.VAR_KEYWORD)
    aliases = [util.name_py2cli(param.name, named)]
    default = util.UNSET
    conv = identity

    kwargs = dict(
        kwargs,
        argument_name=param.name,
        undocumented=Parameter.UNDOCUMENTED in annotations,
    )

    if param.default is not param.empty:
        default = param.default

    if Parameter.REQUIRED in annotations:
        kwargs['required'] = True

    if Parameter.LAST_OPTION in annotations:
        kwargs['last_option'] = True

    prev_conv = None
    for thing in annotations:
        if isinstance(thing, Parameter):
            return thing
        if callable(thing):
            if is_parameter_converter(thing):
                raise ValueError(
                    "Parameter converter {!r} must be the first element "
                    "of a parameter's annotation".format(
                        getattr(thing, '__name__', thing)))
            try:
                conv = get_value_converter(thing)
            except ValueError:
                pass
            else:
                if prev_conv is not None:
                    raise ValueError(
                        "Value converter specified twice in annotation: "
                        "{0.__name__} {1.__name__}".format(prev_conv, thing))
                prev_conv = thing
                continue
        if isinstance(thing, six.string_types):
            if not named:
                raise ValueError("Cannot give aliases for a positional "
                                 "parameter.")
            if len(thing.split()) > 1:
                raise ValueError("Cannot have whitespace in aliases.")
            alias = util.name_py2cli(thing, named, fixcase=False)
            if alias in aliases:
                raise ValueError("Duplicate alias " + repr(thing))
            aliases.append(alias)
            continue
        if isinstance(thing, ParameterFlag):
            continue
        raise ValueError(
            "Unknown annotation {!r}\n"
            "If you intended for it to be a value or parameter converter, "
            "make sure the appropriate decorator was applied.".format(thing))

    kwargs['default'] = default if not kwargs.get('required') else util.UNSET
    kwargs['conv'] = conv
    if prev_conv is None and default is not util.UNSET and default is not None:
        try:
            kwargs['conv'] = get_value_converter(type(default))
        except ValueError:
            raise ValueError(
                "Cannot find value converter for default value {!r}. "
                "Please specify one as an annotation.\n"
                "If the default value's type should be used to "
                "convert the value, make sure it is decorated "
                "with clize.parser.value_converter()".format(default))

    if named:
        kwargs['aliases'] = aliases
        if param.kind == param.VAR_KEYWORD:
            return varkwargs_cls(**kwargs)
        return named_cls(**kwargs)
    else:
        kwargs['display_name'] = util.name_py2cli(param.name)
        if param.kind == param.VAR_POSITIONAL:
            return varargs_cls(**kwargs)
        return pos_cls(**kwargs)
Example #9
0
def _use_class(pos_cls, varargs_cls, named_cls, varkwargs_cls, kwargs,
               param, annotations):
    named = param.kind in (param.KEYWORD_ONLY, param.VAR_KEYWORD)
    aliases = [param.name]
    default = util.UNSET
    conv = identity

    kwargs = dict(
        kwargs,
        argument_name=param.name,
        undocumented=Parameter.UNDOCUMENTED in annotations,
        )

    if param.default is not param.empty:
        default = param.default

    if Parameter.REQUIRED in annotations:
        kwargs['required'] = True

    if Parameter.LAST_OPTION in annotations:
        kwargs['last_option'] = True

    set_coerce = False
    for thing in annotations:
        if isinstance(thing, Parameter):
            return thing
        if callable(thing):
            if is_parameter_converter(thing):
                raise ValueError(
                    "A custom parameter converter must be the first element "
                    "of a parameter's annotation")
            try:
                conv = get_value_converter(thing)
            except ValueError:
                pass
            else:
                if set_coerce:
                    raise ValueError(
                        "Coercion function specified twice in annotation: "
                        "{0.__name__} {1.__name__}".format(conv, thing))
                conv = conv
                set_coerce = True
                continue
        if isinstance(thing, six.string_types):
            if not named:
                raise ValueError("Cannot give aliases for a positional "
                                 "parameter.")
            if len(thing.split()) > 1:
                raise ValueError("Cannot have whitespace in aliases.")
            if thing in aliases:
                raise ValueError("Duplicate alias " + repr(thing))
            aliases.append(thing)
            continue
        if isinstance(thing, ParameterFlag):
            continue
        raise ValueError(thing)

    kwargs['default'] = default if not kwargs.get('required') else util.UNSET
    kwargs['conv'] = conv
    if not set_coerce and default is not util.UNSET and default is not None:
        kwargs['conv'] = get_value_converter(type(default))

    if named:
        kwargs['aliases'] = [
            util.name_py2cli(alias, named)
            for alias in aliases]
        if param.kind == param.VAR_KEYWORD:
            return varkwargs_cls(**kwargs)
        return named_cls(**kwargs)
    else:
        kwargs['display_name'] = util.name_py2cli(param.name)
        if param.kind == param.VAR_POSITIONAL:
            return varargs_cls(**kwargs)
        return pos_cls(**kwargs)
Example #10
0
File: parser.py Project: epsy/clize
def _use_class(pos_cls, varargs_cls, named_cls, varkwargs_cls, kwargs,
               param, annotations):
    named = param.kind in (param.KEYWORD_ONLY, param.VAR_KEYWORD)
    aliases = [util.name_py2cli(param.name, named)]
    default = util.UNSET
    conv = identity

    kwargs = dict(
        kwargs,
        argument_name=param.name,
        undocumented=Parameter.UNDOCUMENTED in annotations,
        )

    if param.default is not param.empty:
        default = param.default

    if Parameter.REQUIRED in annotations:
        kwargs['required'] = True

    if Parameter.LAST_OPTION in annotations:
        kwargs['last_option'] = True

    prev_conv = None
    for thing in annotations:
        if isinstance(thing, Parameter):
            return thing
        if callable(thing):
            if is_parameter_converter(thing):
                raise ValueError(
                    "Parameter converter {!r} must be the first element "
                    "of a parameter's annotation"
                    .format(getattr(thing, '__name__', thing)))
            try:
                conv = get_value_converter(thing)
            except ValueError:
                pass
            else:
                if prev_conv is not None:
                    raise ValueError(
                        "Value converter specified twice in annotation: "
                        "{0.__name__} {1.__name__}".format(prev_conv, thing))
                prev_conv = thing
                continue
        if isinstance(thing, six.string_types):
            if not named:
                raise ValueError("Cannot give aliases for a positional "
                                 "parameter.")
            if len(thing.split()) > 1:
                raise ValueError("Cannot have whitespace in aliases.")
            alias = util.name_py2cli(thing, named, fixcase=False)
            if alias in aliases:
                raise ValueError("Duplicate alias " + repr(thing))
            aliases.append(alias)
            continue
        if isinstance(thing, ParameterFlag):
            continue
        raise ValueError(
            "Unknown annotation {!r}\n"
            "If you intended for it to be a value or parameter converter, "
            "make sure the appropriate decorator was applied."
            .format(thing))

    kwargs['default'] = default if not kwargs.get('required') else util.UNSET
    kwargs['conv'] = conv
    if prev_conv is None and default is not util.UNSET and default is not None:
        try:
            kwargs['conv'] = get_value_converter(type(default))
        except ValueError:
            raise ValueError(
                "Cannot find value converter for default value {!r}. "
                "Please specify one as an annotation.\n"
                "If the default value's type should be used to "
                "convert the value, make sure it is decorated "
                "with clize.parser.value_converter()"
                .format(default))

    if named:
        kwargs['aliases'] = aliases
        if param.kind == param.VAR_KEYWORD:
            return varkwargs_cls(**kwargs)
        return named_cls(**kwargs)
    else:
        kwargs['display_name'] = util.name_py2cli(param.name)
        if param.kind == param.VAR_POSITIONAL:
            return varargs_cls(**kwargs)
        return pos_cls(**kwargs)
Example #11
0
def default_converter(param, annotations):
    named = param.kind in (param.KEYWORD_ONLY, param.VAR_KEYWORD)
    aliases = [param.name]
    default = util.UNSET
    typ = util.identity

    kwargs = {
        'argument_name': param.name,
        'undocumented': Parameter.UNDOCUMENTED in annotations,
        }

    if param.default is not param.empty:
        if Parameter.REQUIRED not in annotations:
            default = param.default
        if default is not None:
            typ = type(param.default)

    if Parameter.LAST_OPTION in annotations:
        kwargs['last_option'] = True

    set_coerce = False
    for thing in annotations:
        if isinstance(thing, Parameter):
            return thing
        elif callable(thing):
            if set_coerce:
                raise ValueError(
                    "Coercion function specified twice in annotation: "
                    "{0.__name__} {1.__name__}".format(typ, thing))
            typ = thing
            set_coerce = True
        elif isinstance(thing, six.string_types):
            if not named:
                raise ValueError("Cannot give aliases for a positional "
                                 "parameter.")
            if len(thing.split()) > 1:
                raise ValueError("Cannot have whitespace in aliases.")
            aliases.append(thing)
        elif isinstance(thing, ParameterFlag):
            pass
        else:
            raise ValueError(thing)

    if named:
        kwargs['aliases'] = [
            util.name_py2cli(alias, named)
            for alias in aliases]
        if default is False and typ is bool:
            return FlagParameter(value=True, false_value=False, **kwargs)
        else:
            kwargs['default'] = default
            kwargs['typ'] = typ
            if typ is int:
                return IntOptionParameter(**kwargs)
            else:
                return OptionParameter(**kwargs)
    else:
        kwargs['display_name'] = util.name_py2cli(param.name)
        if param.kind == param.VAR_POSITIONAL:
            return ExtraPosArgsParameter(
                required=Parameter.REQUIRED in annotations,
                typ=typ, **kwargs)
        else:
            return PositionalParameter(default=default, typ=typ, **kwargs)
Example #12
0
def _use_class(pos_cls, varargs_cls, named_cls, varkwargs_cls, kwargs, param,
               annotations):
    named = param.kind in (param.KEYWORD_ONLY, param.VAR_KEYWORD)
    aliases = [param.name]
    default = util.UNSET
    conv = identity

    kwargs = dict(
        kwargs,
        argument_name=param.name,
        undocumented=Parameter.UNDOCUMENTED in annotations,
    )

    if param.default is not param.empty:
        default = param.default

    if Parameter.REQUIRED in annotations:
        kwargs['required'] = True

    if Parameter.LAST_OPTION in annotations:
        kwargs['last_option'] = True

    set_coerce = False
    for thing in annotations:
        if isinstance(thing, Parameter):
            return thing
        if callable(thing):
            if is_parameter_converter(thing):
                raise ValueError(
                    "A custom parameter converter must be the first element "
                    "of a parameter's annotation")
            try:
                conv = get_value_converter(thing)
            except ValueError:
                pass
            else:
                if set_coerce:
                    raise ValueError(
                        "Coercion function specified twice in annotation: "
                        "{0.__name__} {1.__name__}".format(conv, thing))
                conv = conv
                set_coerce = True
                continue
        if isinstance(thing, six.string_types):
            if not named:
                raise ValueError("Cannot give aliases for a positional "
                                 "parameter.")
            if len(thing.split()) > 1:
                raise ValueError("Cannot have whitespace in aliases.")
            if thing in aliases:
                raise ValueError("Duplicate alias " + repr(thing))
            aliases.append(thing)
            continue
        if isinstance(thing, ParameterFlag):
            continue
        raise ValueError(thing)

    kwargs['default'] = default if not kwargs.get('required') else util.UNSET
    kwargs['conv'] = conv
    if not set_coerce and default is not util.UNSET and default is not None:
        kwargs['conv'] = get_value_converter(type(default))

    if named:
        kwargs['aliases'] = [
            util.name_py2cli(alias, named) for alias in aliases
        ]
        if param.kind == param.VAR_KEYWORD:
            return varkwargs_cls(**kwargs)
        return named_cls(**kwargs)
    else:
        kwargs['display_name'] = util.name_py2cli(param.name)
        if param.kind == param.VAR_POSITIONAL:
            return varargs_cls(**kwargs)
        return pos_cls(**kwargs)
Example #13
0
 def _test(self, name, exp_converted_name):
     self.assertEqual(exp_converted_name, util.name_py2cli(name, kw=True))