Python click.Option() Examples

The following are 30 code examples of click.Option(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module click , or try the search function .
Example #1
Source File: __main__.py    From catalyst with Apache License 2.0 6 votes vote down vote up
def extract_option_object(option):
    """Convert a click.option call into a click.Option object.

    Parameters
    ----------
    option : decorator
        A click.option decorator.

    Returns
    -------
    option_object : click.Option
        The option object that this decorator will create.
    """

    @option
    def opt():
        pass

    return opt.__click_params__[0] 
Example #2
Source File: generate_event_action.py    From scfcli with Apache License 2.0 6 votes vote down vote up
def get_command(self, ctx, cmd):

        if cmd not in self.srv_info:
            return None

        params = []
        for param in self.srv_info[cmd][self.PARAMS].keys():
            default = self.srv_info[cmd][self.PARAMS][param]["default"]
            params.append(click.Option(
                ["--{}".format(param)],
                default=default,
                help="Specify the {}, default is {}".format(param, default)
            ))

        cbfun = click.pass_context(self.action)
        cmd = click.Command(name=cmd,
                            short_help=self.srv_info[cmd]["help"],
                            params=params, callback=cbfun)

        return cmd 
Example #3
Source File: _compat.py    From click-shell with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_choices(cli, prog_name, args, incomplete):
        """
        This is identical to click._bashcomplete:get_choices in click 6.4+
        """
        ctx = resolve_ctx(cli, prog_name, args)

        if ctx is None:
            return

        choices = []
        if incomplete and not incomplete[:1].isalnum():
            for param in ctx.command.params:
                if not isinstance(param, click.Option):
                    continue
                choices.extend(param.opts)
                choices.extend(param.secondary_opts)
        elif isinstance(ctx.command, click.MultiCommand):
            choices.extend(ctx.command.list_commands(ctx))

        for item in choices:
            if item.startswith(incomplete):
                yield item 
Example #4
Source File: commands.py    From q2cli with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, plugin, name, *args, **kwargs):
        import q2cli.util

        # the cli currently doesn't differentiate between methods
        # and visualizers, it treats them generically as Actions
        self._plugin = plugin
        self._action_lookup = {q2cli.util.to_cli_name(id): a for id, a in
                               plugin['actions'].items()}

        support = 'Getting user support: %s' % plugin['user_support_text']
        website = 'Plugin website: %s' % plugin['website']
        description = 'Description: %s' % plugin['description']
        help_ = '\n\n'.join([description, website, support])

        params = [
            click.Option(('--version',), is_flag=True, expose_value=False,
                         is_eager=True, callback=self._get_version,
                         help='Show the version and exit.'),
            q2cli.util.citations_option(self._get_citation_records)
        ]

        super().__init__(name, *args, short_help=plugin['short_description'],
                         help=help_, params=params, **kwargs) 
Example #5
Source File: util.py    From q2cli with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def usage_example_option(action):
    import click
    from q2cli.core.usage import examples

    def callback(ctx, param, value):
        if not value or ctx.resilient_parsing:
            return

        action = ctx.command._get_action()

        for line in examples(action):
            click.secho(line)

        ctx.exit()

    return click.Option(['--examples'], is_flag=True, expose_value=False,
                        is_eager=True, callback=callback,
                        help='Show usage examples and exit.') 
Example #6
Source File: core.py    From click-man with MIT License 6 votes vote down vote up
def generate_man_page(ctx, version=None):
    """
    Generate documentation for the given command.

    :param click.Context ctx: the click context for the
                              cli application.

    :rtype: str
    :returns: the generate man page from the given click Context.
    """
    # Create man page with the details from the given context
    man_page = ManPage(ctx.command_path)
    man_page.version = version
    man_page.short_help = ctx.command.get_short_help_str()
    man_page.description = ctx.command.help
    man_page.synopsis = ' '.join(ctx.command.collect_usage_pieces(ctx))
    man_page.options = [x.get_help_record(ctx) for x in ctx.command.params if isinstance(x, click.Option)]
    commands = getattr(ctx.command, 'commands', None)
    if commands:
        man_page.commands = [
            (k, v.get_short_help_str()) for k, v in commands.items()
        ]

    return str(man_page) 
Example #7
Source File: runs_push.py    From guildai with Apache License 2.0 6 votes vote down vote up
def push_params(fn):
    click_util.append_params(
        fn,
        [
            remote_support.remote_arg,
            runs_support.runs_arg,
            runs_support.all_filters,
            click.Option(
                ("-n", "--delete",),
                help="Delete remote files missing locally.",
                is_flag=True,
            ),
            click.Option(
                ("-y", "--yes"), help="Do not prompt before copying.", is_flag=True
            ),
        ],
    )
    return fn 
Example #8
Source File: server_support.py    From guildai with Apache License 2.0 6 votes vote down vote up
def host_and_port_options(fn):
    click_util.append_params(
        fn,
        [
            click.Option(
                ("-h", "--host",),
                metavar="HOST",
                help="Name of host interface to listen on.",
            ),
            click.Option(
                ("-p", "--port",),
                metavar="PORT",
                help="Port to listen on.",
                type=click.IntRange(0, 65535),
            ),
        ],
    )
    return fn 
Example #9
Source File: update_urls.py    From runway with Apache License 2.0 6 votes vote down vote up
def sanitize_version(_ctx: Optional[click.Context],
                     _param: Optional[Union[click.Option, click.Parameter]],
                     value: str
                     ) -> str:
    """Sanitize a version number by stripping git tag ref and leading "v".

    To be used as the callback of a click option or parameter.

    Args:
        ctx: Click context object.
        param: The click option or parameter the callback is being used with.
        value: Value passed to the option or parameter from the CLI.

    Returns:
        str: The SemVer version number.

    """
    version = value.replace('refs/tags/', '')  # strip git ref
    if version.startswith('v'):  # strip leading "v"
        version = version[1:]
    if VersionInfo.isvalid(version):  # valid SemVer
        return version
    raise ValueError(f'version of "{version}" does not follow SemVer') 
Example #10
Source File: runs_pull.py    From guildai with Apache License 2.0 6 votes vote down vote up
def pull_params(fn):
    click_util.append_params(
        fn,
        [
            remote_support.remote_arg,
            runs_support.runs_arg,
            runs_support.all_filters,
            click.Option(
                ("-d", "--delete",),
                help="Delete local files missing on remote.",
                is_flag=True,
            ),
            click.Option(
                ("-y", "--yes"), help="Do not prompt before copying.", is_flag=True
            ),
        ],
    )
    return fn 
Example #11
Source File: params.py    From gandi.cli with GNU General Public License v3.0 6 votes vote down vote up
def handle_parse_result(self, ctx, opts, args):
        """ Save value for this option in configuration
        if key/value pair doesn't already exist.
        Or old value in config was deprecated
        it needs to be updated to the new value format
        but the value keeps the same "meaning"
        """
        gandi = ctx.obj
        needs_update = False
        value, args = click.Option.handle_parse_result(self, ctx, opts, args)

        if value is not None:
            previous_value = gandi.get(global_=True, key=self.name)
            if isinstance(self.type, GandiChoice):
                if value == previous_value:
                    needs_update = True
                value = self.type.convert_deprecated_value(value)
            if not previous_value or needs_update:
                gandi.configure(global_=True, key=self.name, val=value)
        opts[self.name] = value
        value, args = click.Option.handle_parse_result(self, ctx, opts, args)
        return value, args 
Example #12
Source File: remote_support.py    From guildai with Apache License 2.0 5 votes vote down vote up
def remote_option(help):
    """`REMOTE` is the name of a configured remote. Use ``guild remotes``
    to list available remotes.

    For information on configuring remotes, see ``guild remotes
    --help``.

    """
    assert isinstance(help, str), "@remote_option must be called with help"

    def wrapper(fn):
        click_util.append_params(
            fn, [click.Option(("-r", "--remote"), metavar="REMOTE", help=help),]
        )
        return fn

    return wrapper 
Example #13
Source File: parameters.py    From metaflow with Apache License 2.0 5 votes vote down vote up
def add_custom_parameters(cmd):
    for arg in parameters:
        cmd.params.insert(0, click.Option(('--' + arg.name,), **arg.kwargs))
    return cmd 
Example #14
Source File: cli.py    From gandi.cli with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, help=None):
        """ Initialize CLI command line."""
        @compatcallback
        def set_debug(ctx, param, value):
            ctx.obj['verbose'] = value

        @compatcallback
        def get_version(ctx, param, value):
            if value:
                print(('Gandi CLI %s\n\n'
                       'Copyright: © 2014-2018 Gandi S.A.S.\n'
                       'License: GPL-3' % __version__))
                ctx.exit()

        if help is None:
            help = inspect.getdoc(self)

        click.Group.__init__(self, help=help, params=[
            click.Option(['-v'],
                         help='Enable or disable verbose mode. Use multiple '
                              'time for higher level of verbosity: -v, -vv',
                         count=True, metavar='',
                         default=0, callback=set_debug),
            click.Option(['--version'],
                         help='Display version.',
                         is_flag=True,
                         default=False, callback=get_version)

        ]) 
Example #15
Source File: params.py    From gandi.cli with GNU General Public License v3.0 5 votes vote down vote up
def option(*param_decls, **attrs):
    """Attach an option to the command.

    All positional arguments are passed as parameter declarations
    to :class:`Option`, all keyword arguments are forwarded unchanged.
    This is equivalent to creating an :class:`Option` instance manually and
    attaching it to the :attr:`Command.params` list.
    """
    def decorator(f):
        _param_memo(f, GandiOption(param_decls, **attrs))
        return f
    return decorator


# create a decorator to pass the Gandi object as context to click calls 
Example #16
Source File: params.py    From gandi.cli with GNU General Public License v3.0 5 votes vote down vote up
def consume_value(self, ctx, opts):
        """ Retrieve default value and display it when prompt is disabled. """
        value = click.Option.consume_value(self, ctx, opts)
        if not value:
            # value not found by click on command line
            # now check using our context helper in order into
            # local configuration
            # global configuration
            gandi = ctx.obj
            value = gandi.get(self.name)
            if value is not None:
                # value found in configuration display it
                self.display_value(ctx, value)
            else:
                if self.default is None and self.required:
                    metavar = ''
                    if self.type.name not in ['integer', 'text']:
                        metavar = self.make_metavar()
                    prompt = '%s %s' % (self.help, metavar)
                    gandi.echo(prompt)
        return value 
Example #17
Source File: params.py    From gandi.cli with GNU General Public License v3.0 5 votes vote down vote up
def get_default(self, ctx):
        """ Retrieve default value and display it when prompt disabled. """
        value = click.Option.get_default(self, ctx)
        if not self.prompt:
            # value found in default display it
            self.display_value(ctx, value)
        return value 
Example #18
Source File: runs_list.py    From guildai with Apache License 2.0 5 votes vote down vote up
def runs_list_options(fn):
    click_util.append_params(
        fn,
        [
            click.Option(
                ("-a", "--all"),
                help="Show all runs (by default only the last 20 runs are shown).",
                is_flag=True,
            ),
            click.Option(
                ("-m", "--more"),
                help=("Show 20 more runs. Maybe used multiple times."),
                count=True,
            ),
            click.Option(
                ("-n", "--limit"),
                metavar="N",
                type=click.IntRange(min=1),
                help="Limit number of runs shown.",
            ),
            click.Option(("-d", "--deleted"), help="Show deleted runs.", is_flag=True),
            click.Option(
                ("-A", "--archive",), metavar="DIR", help="Show archived runs in DIR."
            ),
            runs_support.all_filters,
            click.Option(("--json",), help="Format runs as JSON.", is_flag=True),
            click.Option(("-v", "--verbose"), help="Show run details.", is_flag=True),
            click.Option(
                ("-r", "--remote",),
                metavar="REMOTE",
                help="List runs on REMOTE rather than local runs.",
            ),
        ],
    )
    return fn 
Example #19
Source File: packages_delete.py    From guildai with Apache License 2.0 5 votes vote down vote up
def delete_params(fn):
    click_util.append_params(
        fn,
        [
            click.Argument(
                ("packages",), metavar="PACKAGE...", nargs=-1, required=True
            ),
            click.Option(
                ("-y", "--yes",),
                help="Do not prompt before uninstalling.",
                is_flag=True,
            ),
        ],
    )
    return fn 
Example #20
Source File: one_use_option.py    From globus-cli with Apache License 2.0 5 votes vote down vote up
def one_use_option(*args, **kwargs):
    """
    Wrapper of the click.option decorator that replaces any instances of
    the Option class with the custom OneUseOption class
    """
    # cannot force a multiple or count option to be single use
    if "multiple" in kwargs or "count" in kwargs:
        raise ValueError(
            "Internal error, one_use_option cannot be used with multiple or count."
        )

    # cannot force a non Option Paramater (argument) to be a OneUseOption
    if kwargs.get("cls"):
        raise TypeError(
            "Internal error, one_use_option cannot overwrite "
            "cls {}.".format(kwargs.get("cls"))
        )

    # use our OneUseOption class instead of a normal Option
    kwargs["cls"] = OneUseOption

    # if dealing with a flag, switch to a counting option,
    # and then assert if the count is not greater than 1 and cast to a bool
    if kwargs.get("is_flag"):
        kwargs["is_flag"] = False  # mutually exclusive with count
        kwargs["count"] = True

    # if not a flag, this option takes an argument(s), switch to a multiple
    # option, assert the len is 1, and treat the first element as the value
    else:
        kwargs["multiple"] = True

    # decorate with the click.option decorator, but with our custom kwargs
    def decorator(f):
        return click.option(*args, **kwargs)(f)

    return decorator 
Example #21
Source File: test_config.py    From tartufo with GNU General Public License v2.0 5 votes vote down vote up
def setUp(self):
        self.ctx = click.Context(click.Command("foo"))
        self.param = click.Option(["--config"])
        return super(ConfigFileTests, self).setUp() 
Example #22
Source File: runs_stop.py    From guildai with Apache License 2.0 5 votes vote down vote up
def runs_stop_params(fn):
    click_util.append_params(
        fn,
        [
            runs_support.runs_arg,
            runs_support.op_and_label_filters,
            runs_support.time_filters,
            runs_support.sourcecode_digest_filters,
            remote_support.remote_option("Stop remote runs."),
            click.Option(
                ("-y", "--yes"), help="Do not prompt before stopping.", is_flag=True
            ),
            click.Option(
                ("-n", "--no-wait"),
                help="Don't wait for remote runs to stop.",
                is_flag=True,
            ),
        ],
    )
    return fn 
Example #23
Source File: runs_support.py    From guildai with Apache License 2.0 5 votes vote down vote up
def sourcecode_digest_filters(fn):
    """### Filter by Source Code Digest

    To show runs for a specific source code digest, use `-g` or
    `--digest` with a complete or partial digest value.

    """
    click_util.append_params(
        fn,
        [
            click.Option(
                ("-D", "--digest",),
                metavar="VAL",
                help=("Filter only runs with a matching source code digest."),
            )
        ],
    )
    return fn 
Example #24
Source File: one_use_option.py    From globus-cli with Apache License 2.0 5 votes vote down vote up
def type_cast_value(self, ctx, value):

        # get the result of a normal type_cast
        converted_val = super(OneUseOption, self).type_cast_value(ctx, value)

        # if the option takes arguments (multiple was set to true)
        # assert no more than one argument was gotten, and if an argument
        # was gotten, take it out of the tuple and return it
        if self.multiple:
            if len(converted_val) > 1:
                raise click.BadParameter("Option used multiple times.", ctx=ctx)
            if len(converted_val):
                return converted_val[0]
            else:
                return None

        # if the option was a flag (converted to a count) assert that the flag
        # count is no more than one, and type cast back to a bool
        elif self.count:
            if converted_val > 1:
                raise click.BadParameter("Option used multiple times.", ctx=ctx)
            return bool(converted_val)

        else:
            raise ValueError(
                (
                    "Internal error, OneUseOption expected either "
                    "multiple or count, but got neither."
                )
            ) 
Example #25
Source File: runs_export.py    From guildai with Apache License 2.0 5 votes vote down vote up
def export_params(fn):
    click_util.append_params(
        fn,
        [
            runs_support.runs_arg,
            click.Argument(("location",)),
            click.Option(
                ("-m", "--move"),
                help="Move exported runs rather than copy.",
                is_flag=True,
            ),
            click.Option(
                ("-r", "--copy-resources",),
                help="Copy resources for each exported run.",
                is_flag=True,
            ),
            runs_support.all_filters,
            click.Option(
                ("-y", "--yes"), help="Do not prompt before exporting.", is_flag=True
            ),
        ],
    )
    return fn 
Example #26
Source File: common.py    From xcube with MIT License 5 votes vote down vote up
def cli_option_traceback(func):
    """Decorator for adding a pre-defined, reusable CLI option `--traceback`."""

    # noinspection PyUnusedLocal
    def _callback(ctx: click.Context, param: click.Option, value: bool):
        ctx_obj = ctx.ensure_object(dict)
        if ctx_obj is not None:
            ctx_obj["traceback"] = value
        return value

    return click.option(
        '--traceback',
        is_flag=True,
        help="Enable tracing back errors by dumping the Python call stack. "
             "Pass as very first option to also trace back error during command-line validation.",
        callback=_callback)(func) 
Example #27
Source File: main.py    From typer with MIT License 5 votes vote down vote up
def get_params_convertors_ctx_param_name_from_function(
    callback: Optional[Callable[..., Any]]
) -> Tuple[List[Union[click.Argument, click.Option]], Dict[str, Any], Optional[str]]:
    params = []
    convertors = {}
    context_param_name = None
    if callback:
        parameters = get_params_from_function(callback)
        for param_name, param in parameters.items():
            if lenient_issubclass(param.annotation, click.Context):
                context_param_name = param_name
                continue
            click_param, convertor = get_click_param(param)
            if convertor:
                convertors[param_name] = convertor
            params.append(click_param)
    return params, convertors, context_param_name 
Example #28
Source File: runs_label.py    From guildai with Apache License 2.0 5 votes vote down vote up
def label_params(fn):
    click_util.append_params(
        fn,
        [
            runs_support.runs_arg,
            click.Option(("-s", "--set"), metavar="VAL", help="Set VAL as label."),
            click.Option(
                ("-p", "-t", "--prepend", "--tag"),
                metavar="VAL",
                help="Prepend VAL to existing label.",
            ),
            click.Option(
                ("-a", "--append"), metavar="VAL", help="Append VAL to existing label.",
            ),
            click.Option(
                ("-rm", "-u", "--remove", "--untag"),
                metavar="VAL",
                multiple=True,
                help="Remove VAL from existing label. Maybe used multiple times.",
            ),
            click.Option(
                ("-c", "--clear"), help="Clear the entire run label.", is_flag=True
            ),
            runs_support.all_filters,
            remote_support.remote_option("Label remote runs."),
            click.Option(
                ("-y", "--yes"),
                help="Do not prompt before modifying labels.",
                is_flag=True,
            ),
        ],
    )
    return fn 
Example #29
Source File: click_flags.py    From guildai with Apache License 2.0 5 votes vote down vote up
def _maybe_apply_flag(param, flags):
    arg_name = _param_arg_name(param)
    if not arg_name or not isinstance(param, click.Option):
        log.debug("skipping %s - not a flag option", param.name)
        return
    flag_name = param.name
    flags[flag_name] = attrs = {}
    if arg_name != flag_name:
        attrs["arg-name"] = arg_name
    if param.help:
        attrs["description"] = param.help
    if param.default is not None:
        attrs["default"] = _ensure_json_encodable(param.default, flag_name)
    if isinstance(param.type, click.Choice):
        attrs["choices"] = _ensure_json_encodable(param.type.choices, flag_name)
    if param.required:
        attrs["required"] = True
    if param.is_flag:
        attrs["arg-switch"] = param.default
    log.debug("added flag %r: %r", flag_name, attrs) 
Example #30
Source File: core.py    From diffy with Apache License 2.0 5 votes vote down vote up
def plugin_command_factory():
    """Dynamically generate plugin groups for all plugins, and add all basic command to it"""
    for p in plugins.all():
        plugin_name = p.slug
        help = f"Options for '{plugin_name}'"
        group = click.Group(name=plugin_name, help=help)
        for name, description in CORE_COMMANDS.items():
            callback = func_factory(p, name)
            pretty_opt = click.Option(
                ["--pretty/--not-pretty"], help="Output a pretty version of the JSON"
            )
            params = [pretty_opt]
            command = click.Command(
                name,
                callback=callback,
                help=description.format(plugin_name),
                params=params,
            )
            group.add_command(command)

        plugins_group.add_command(group)