Example #1
0
 def __init__(self, name=None, type=None, multiple=None, default=None,
              help=None):
     self.name = name
     self.type = convert_type(type, default)
     self.multiple = multiple
     self.default = default
     self.help = help
Example #2
0
def option(*param_decls: Any, **attrs: Any) -> Callable[..., Any]:
    option_attrs = attrs.copy()
    option_attrs.setdefault("cls", Option)
    typ = convert_type(attrs.get("type"), attrs.get("default"))
    autocompletion = getattr(typ, "complete", None)
    option_attrs.setdefault("autocompletion", autocompletion)
    return click.option(*param_decls, **option_attrs)
Example #3
0
def env(key, default="", type=None):
    "Extract an environment variable for use in configuration"

    key = "STRUT_" + key

    # First check an internal cache, so we can `pop` multiple times
    # without actually losing the value.
    try:
        rv = env._cache[key]
    except KeyError:
        # We don't want/can't pop off env variables when
        # uwsgi is in autoreload mode, otherwise it'll have an empty
        # env on reload
        if uwsgi_options.get("py-autoreload") == b"1":
            fn = os.environ.__getitem__
        else:
            fn = os.environ.pop

        try:
            rv = fn(key)
            env._cache[key] = rv
        except KeyError:
            rv = default

    if type is None:
        type = types.convert_type(_type(default))

    return type(rv)
Example #4
0
def prompt_email(prompt='Email', default=None, confirm=False):
    conv = convert_type(None)

    def _proc_email(val):
        val = conv(val).strip()
        if not validate_email(val):
            raise click.UsageError('invalid email')
        return val

    return click.prompt(prompt, default=default, confirmation_prompt=confirm, value_proc=_proc_email)
Example #5
0
def prompt_email(prompt=u'Email', default=None, confirm=False):
    conv = convert_type(None)

    def _proc_email(val):
        val = conv(val).strip()
        if not is_valid_mail(val, multi=False):
            raise click.UsageError(u'invalid email')
        return val

    return click.prompt(prompt, default=default, confirmation_prompt=confirm, value_proc=_proc_email)
Example #6
0
def prompt(
    text,
    default=None,
    hide_input=False,
    confirmation_prompt=False,
    type=None,
    value_proc=None,
    prompt_suffix=": ",
    show_default=True,
    err=False,
    show_choices=True,
) -> None:
    """Prompts a user for input.  This is a convenience function that can \
    be used to prompt a user for input later.

    If the user aborts the input by sending a interrupt signal, this
    function will catch it and raise a :exc:`Abort` exception.

    .. versionadded:: 7.0
       Added the show_choices parameter.

    .. versionadded:: 6.0
       Added unicode support for cmd.exe on Windows.

    .. versionadded:: 4.0
       Added the `err` parameter.

    :param text: the text to show for the prompt.
    :param default: the default value to use if no input happens.  If this
                    is not given it will prompt until it's aborted.
    :param hide_input: if this is set to true then the input value will
                       be hidden.
    :param confirmation_prompt: asks for confirmation for the value.
    :param type: the type to use to check the value against.
    :param value_proc: if this parameter is provided it's a function that
                       is invoked instead of the type conversion to
                       convert a value.
    :param prompt_suffix: a suffix that should be added to the prompt.
    :param show_default: shows or hides the default value in the prompt.
    :param err: if set to true the file defaults to ``stderr`` instead of
                ``stdout``, the same as with echo.
    :param show_choices: Show or hide choices if the passed type is a Choice.
                         For example if type is a Choice of either day or week,
                         show_choices is true and text is "Group by" then the
                         prompt will be "Group by (day, week): ".
    :return: None
    """
    result = None

    def prompt_func(text):
        f = hidden_prompt_func if hide_input else visible_prompt_func
        try:
            # Write the prompt separately so that we get nice
            # coloring through colorama on Windows
            echo(f"{text}{_ansi_reset_all}", nl=False, err=err)
            return f("")
        except (KeyboardInterrupt, EOFError):
            # getpass doesn't print a newline if the user aborts input with ^C.
            # Allegedly this behavior is inherited from getpass(3).
            # A doc bug has been filed at https://bugs.python.org/issue24711
            if hide_input:
                echo(None, err=err)
            raise Abort()

    if value_proc is None:
        value_proc = convert_type(type, default)

    prompt_ = _build_prompt(text, prompt_suffix, show_default, default,
                            show_choices, type)

    while 1:
        while 1:
            value = prompt_func(prompt_)
            if value:
                break
            elif default is not None:
                value = default
                break
        try:
            result = value_proc(value)
        except UsageError as e:
            if hide_input:
                echo("Error: the value you entered was invalid", err=err)
            else:
                echo(f"Error: {e.message}", err=err)  # noqa: B306
            continue
        if not confirmation_prompt:
            return result
        while 1:
            value2 = prompt_func("Repeat for confirmation: ")
            if value2:
                break
        if value == value2:
            return result
        echo("Error: the two entered values do not match", err=err)
Example #7
0
def argument(*param_decls: Any, **attrs: Any) -> Callable[..., Any]:
    arg_attrs = attrs.copy()
    typ = convert_type(attrs.get("type"), attrs.get("default"))
    autocompletion = getattr(typ, "complete", None)
    arg_attrs.setdefault("shell_complete", autocompletion)
    return click.argument(*param_decls, **arg_attrs)
Example #8
0
def prompt(
    text: str,
    default: Optional[str] = None,
    hide_input: bool = False,
    confirmation_prompt: Union[bool, str] = False,
    type: Optional[_ConvertibleType] = None,  # noqa: A002  # pylint: disable=redefined-builtin
    value_proc: Optional[Callable[[Optional[str]], Any]] = None,
    prompt_suffix: str = ": ",
    show_default: bool = True,
    err: bool = False,
    show_choices: bool = True,
):
    """
	Prompts a user for input.

	If the user aborts the input by sending an interrupt signal,
	this function will catch it and raise a :exc:`click.Abort` exception.

	:param text: The text to show for the prompt.
	:param default: The default value to use if no input happens.
		If this is not given it will prompt until it is aborted.
	:param hide_input: If :py:obj:`True` then the input value will be hidden.
	:param confirmation_prompt: Asks for confirmation for the value.
		Can be set to a string instead of :py:obj:`True` to customize the message.
	:param type: The type to check the value against.
	:param value_proc: If this parameter is provided it must be a function that
		is invoked instead of the type conversion to convert a value.
	:param prompt_suffix: A suffix that should be added to the prompt.
	:param show_default: Shows or hides the default value in the prompt.
	:param err: If :py:obj:`True` the file defaults to ``stderr`` instead of
		``stdout``, the same as with :func:`click.echo`.
	:param show_choices: Show or hide choices if the passed type is a :class:`click.Choice`.
		For example, if the choice is either ``day`` or ``week``,
		``show_choices`` is :py:obj:`True` and ``text`` is ``'Group by'`` then the
		prompt will be ``'Group by (day, week): '``.
	"""

    result = None  # noqa

    def prompt_func(text):
        try:
            return _prompt(text, err=err, hide_input=hide_input)
        except (KeyboardInterrupt, EOFError):
            if hide_input:
                click.echo(None, err=err)
            raise click.Abort()

    if value_proc is None:
        value_proc = convert_type(type, default)

    prompt = _build_prompt(text, prompt_suffix, show_default, default,
                           show_choices, type)  # type: ignore

    while True:
        while True:
            value = prompt_func(prompt)

            if value:
                break
            elif default is not None:
                if isinstance(value_proc, Path):
                    # validate Path default value (exists, dir_okay etc.)
                    value = default
                    break
                return default

        try:
            result = value_proc(value)
        except click.UsageError as e:
            click.echo(f"Error: {e.message}", err=err)  # noqa: B306
            continue

        if not confirmation_prompt:
            return result

        if confirmation_prompt:
            if confirmation_prompt is True:
                confirmation_prompt = "Repeat for confirmation: "

        while True:
            value2 = prompt_func(confirmation_prompt)
            if value2:
                break

        if value == value2:
            return result

        click.echo("Error: the two entered values do not match", err=err)