Beispiel #1
0
def make_template_command(name):
    return click.Command(name)
Beispiel #2
0
def test_suggest_possible_options(runner, value, expect):
    cli = click.Command(
        "cli", params=[click.Option(["--bound"]),
                       click.Option(["--count"])])
    result = runner.invoke(cli, [value])
    assert expect in result.output
    'swap', 'miqqe_patch_applied'
]


def fn(method, *args, **kwargs):
    """Helper to access the right properties"""
    from cfme.utils.appliance import IPAppliance
    appliance_ip = kwargs.get('appliance_ip', None)
    app = get_appliance(appliance_ip)
    descriptor = getattr(IPAppliance, method)
    if isinstance(descriptor, (cached_property, property)):
        out = getattr(app, method)
    else:
        out = getattr(app, method)(*args, **kwargs)
    if out is not None:
        print(out)


for method in methods_to_install:
    command = click.Command(
        method.replace('_', '-'),
        short_help='Returns the {} property'.format(method),
        callback=partial(fn, method),
        params=[
            click.Argument(['appliance_ip'], default=None, required=False)
        ])
    main.add_command(command)

if __name__ == "__main__":
    main()
Beispiel #4
0
 def __init__(self, name=None, commands=None, **attrs):
     click.Group.__init__(self, name, commands, **attrs)
     self._commands = {}
     self._ordered = []
     self._dummy_command = click.Command('')
Beispiel #5
0
def test_show_default_string(runner):
    """When show_default is a string show that value as default."""
    opt = click.Option(["--limit"], show_default="unlimited")
    ctx = click.Context(click.Command("cli"))
    message = opt.get_help_record(ctx)[1]
    assert "[default: (unlimited)]" in message
Beispiel #6
0
 def set_context_level(self, level):
     self.context_level = level
     back = click.Command('back', help='go back', callback=self.do_back)
     self.ctx.command.commands[level].commands['back'] = back
Beispiel #7
0
    def _get_command(self, ctx, lp, cmd_name):
        """
        This function returns the function that click will actually use to execute a specific launch plan.  It also
        stores the launch plan python object and the command name in the closure.

        :param ctx:
        :param flytekit.common.launch_plan.SdkLaunchPlan lp:
        :param Text cmd_name: The name of the launch plan, as passed in from the abstract class
        """
        def _execute_lp(**kwargs):
            for input_name in _six.iterkeys(kwargs):
                if isinstance(kwargs[input_name], tuple):
                    kwargs[input_name] = list(kwargs[input_name])

            inputs = _construct_literal_map_from_parameter_map(
                lp.default_inputs, kwargs)
            execution = lp.execute_with_literals(
                ctx.obj[_constants.CTX_PROJECT],
                ctx.obj[_constants.CTX_DOMAIN],
                literal_inputs=inputs,
                notification_overrides=ctx.obj.get(
                    _constants.CTX_NOTIFICATIONS, None))
            click.echo(
                click.style("Workflow scheduled, execution_id={}".format(
                    _six.text_type(execution.id)),
                            fg='blue'))

        command = click.Command(name=cmd_name, callback=_execute_lp)

        # Iterate through the workflow's inputs
        for var_name in sorted(lp.default_inputs.parameters):
            param = lp.default_inputs.parameters[var_name]
            # TODO: Figure out how to better handle the fact that we want strings to parse,
            # but we probably shouldn't have click say that that's the type on the CLI.
            help_msg = '{} Type: {}'.format(
                _six.text_type(param.var.description),
                _six.text_type(param.var.type)).strip()

            if param.required:
                # If it's a required input, add the required flag
                wrapper = click.option('--{}'.format(var_name),
                                       required=True,
                                       type=_six.text_type,
                                       help=help_msg)
            else:
                # If it's not a required input, it should have a default
                # Use to_python_std so that the text of the default ends up being parseable, if not, the click
                # arg would look something like 'Integer(10)'. If the user specified '11' on the cli, then
                # we'd get '11' and then we'd need annoying logic to differentiate between the default text
                # and user text.
                default = param.default.to_python_std()
                wrapper = click.option(
                    '--{}'.format(var_name),
                    default='{}'.format(_six.text_type(default)),
                    type=_six.text_type,
                    help='{}. Default: {}'.format(help_msg,
                                                  _six.text_type(default)))

            command = wrapper(command)

        return command
Beispiel #8
0
        key = keyfmt.format(inputfn=csvfile, name=basestem, basestem=basestem, dirname=dirname)
        if not quiet:
            print(f"Writing CSV data to table '{key}' in file: {outputfn}")
        df.to_hdf(outputfn, key=key, mode=mode)
        outputfiles.append(outputfn)
    return outputfiles


# Click CLI:
csv_to_hdf5_cli = click.Command(
    callback=csv_to_hdf5,
    name=csv_to_hdf5.__name__,
    help=inspect.getdoc(csv_to_hdf5),
    params=[
        click.Option(['--outputfnfmt', '-f'], default="{inputfn}.hdf5"),
        click.Option(['--keyfmt'], default="/locs"),  # remember: param_decls is a list, *decls.
        click.Option(['--mode'], default="a"),
        click.Option(['--append/--no-append'], default=True),
        click.Option(['--quiet/--no-quiet']),
        # click.Option(['--verbose', '-v'], count=True),
        click.Argument(['csvfiles'])
])


def hdf5_to_csv(
        hdffiles, outputfnfmt="{inputfn}_{key}.csv", keys=None, convert_slash='_',
        sep=",", header=True, index=True, quotechar='"', line_terminator="\n",
        doublequote=True, escapechar=None, decimal=".", dateformat=None,
        chunksize=None, tupleize_cols=None,
        quiet=False
):
        print(df if print_cols == 'all' else df[print_cols])


find_duplicate_files_cli = click.Command(
    callback=find_duplicate_files,
    name=find_duplicate_files.__name__,
    help=inspect.getdoc(find_duplicate_files),
    params=[
        click.Option(['--grouping-scheme',
                      '-g']),  # remember: param_decls is a list, *decls.
        click.Option(['--fsize-min']),
        click.Option(['--exclude'], multiple=True),
        click.Option(['--follow-links/--no-follow-links'], default=False),
        click.Option(['--exclude-links/--no-exclude-links'], default=False),
        click.Option(['--abspaths/--no-abspaths'], default=False),
        click.Option(['--realpaths/--no-realpaths'], default=False),
        click.Option(['--remove-realpath-dups/--no-remove-realpath-dups'],
                     default=False),
        click.Option(['--save-fnpat']),
        click.Option(['--save-cols']),
        click.Option(['--print-cols']),
        click.Option(['--verbose', '-v'], count=True),
        click.Option(['--quiet/--no-quiet']),
        click.Argument(['start-points'],
                       required=True,
                       nargs=-1,
                       type=click.Path(dir_okay=True,
                                       file_okay=False,
                                       exists=True))
    ])
Beispiel #10
0
def test_count_default_type_help():
    """A count option with the default type should not show >=0 in help."""
    option = click.Option(["--count"], count=True, help="some words")
    context = click.Context(click.Command("test"))
    result = option.get_help_record(context)[1]
    assert result == "some words"
Beispiel #11
0
def test_show_default_precedence(ctx_value, opt_value, expect):
    ctx = click.Context(click.Command("test"), show_default=ctx_value)
    opt = click.Option("-a", default=1, help="value", show_default=opt_value)
    help = opt.get_help_record(ctx)[1]
    assert ("default:" in help) is expect
def test_metadata():
    ctx = click.Context(click.Command('edit-metadata'), obj=mocked_obj)
    with ctx:
        runner = click.testing.CliRunner()
        runner.invoke(metadata)
def test_config():
    ctx = click.Context(click.Command('edit-config'), obj=mocked_obj)
    with ctx:
        runner = click.testing.CliRunner()
        runner.invoke(config)
Beispiel #14
0
# Copyright 2018 Rasmus Scholer Sorensen, <*****@*****.**>

import inspect
import click

from zepto_eln.eln_utils.eln_md_pico import print_document_yfm_issues
from zepto_eln.eln_utils.eln_exp_filters import print_started_exps, print_unfinished_exps

print_started_exps_cli = click.Command(
    callback=print_started_exps,
    name=print_started_exps.__name__,
    help=inspect.getdoc(print_started_exps),
    params=[
        # remember: param_decls is a list, *decls.
        click.Option(['--rowfmt'],
                     default='{status:^10}: {expid:<10} {titledesc}'),
        click.Argument(['basedir'],
                       default='.',
                       nargs=1,
                       type=click.Path(dir_okay=True,
                                       file_okay=False,
                                       exists=True))
    ])

print_unfinished_exps_cli = click.Command(
    callback=print_unfinished_exps,
    name=print_unfinished_exps.__name__,
    help=inspect.getdoc(print_unfinished_exps),
    params=[
        click.Option(
            ['--rowfmt'],
Beispiel #15
0
        app.Dependent(d["repository"], d["toxenv_regex"]) for d in dependents_
    ]


dependents = [
    click.Command(
        "dependents-from-librariesio",
        params=[
            click.Argument(["pypi-name"]),
            click.Option(
                ["--api-key"],
                required=True,
                envvar="CHECKON_LIBRARIESIO_API_KEY",
                help="libraries.io API key",
            ),
            click.Option(
                ["--limit"],
                type=int,
                help="Maximum number of dependents to find.",
                default=5,
                show_default=True,
            ),
        ],
        callback=app.get_dependents,
        help="Get dependent projects on PyPI, via https://libraries.io API",
    ),
    click.Command(
        "dependents-from-file",
        params=[click.Argument(["file"], type=click.File())],
        help="List dependent project urls in a toml file.",
        callback=read_from_file,
Beispiel #16
0
 def setUp(self):
     self.ctx = click.Context(click.Command("foo"))
     self.param = click.Option(["--config"])
     return super(ConfigFileTests, self).setUp()
Beispiel #17
0
def get_dummy_context() -> click.Context:
    """Return a dummy click context to allow using eg click.echo when not running an actual click command"""
    ctx = click.Context(click.Command("dummy"))
    ctx.params["verbose"] = True
    return ctx
Beispiel #18
0
 def test_get_config_path(self):
     ctx = click.Context(click.Command('cli'))
     ctx.obj = {'project_dir': 'foo/bar/baz/'}
     path = _get_config_path(ctx)
     self.assertEqual(path, 'foo/bar/baz/.pipetree/config.json')
Beispiel #19
0
 def setUp(self):
     self.data_dir = pathlib.Path(__file__).parent / "data"
     self.ctx = click.Context(click.Command("foo"))
     self.param = click.Option(["--config"])
     return super().setUp()
Beispiel #20
0
        keep_history=keep_history,
        dbname=db,
        experiment_name=experiment_name,
        cuda=cuda,
        debug=debug,
        base_integrand_params=base_integrand_params)

    benchmarker.run(integrand=SineIntegrand,
                    sql_dtypes=dtypes,
                    **benchmark_config)


cli = click.Command("cli",
                    callback=benchmark_camel,
                    params=[
                        PythonLiteralOption(["--dimensions"], default=None),
                        click.Option(["--debug/--no-debug"],
                                     default=None,
                                     type=bool),
                        click.Option(["--cuda"], default=None, type=int),
                        click.Option(["--db"], default=None, type=str),
                        click.Option(["--experiment_name"],
                                     default=None,
                                     type=str),
                        click.Option(["--config"], default=None, type=str),
                        click.Option(["--n_search"], default=10, type=int)
                    ])

if __name__ == '__main__':
    cli()
Beispiel #21
0
)
async def chain(items, exit_stack):
    return await exit_stack.enter_async_context(traversals.sync_chain(items))


@registry.add_traversal(
    "async-chain",
    calculate_more_params=lambda x: calculate_function(
        x, howcall=interpret.HowCall.NONE),
)
async def async_chain(items, exit_stack):
    return await exit_stack.enter_async_context(traversals.async_chain(items))


subcommands = [
    click.Command("map", short_help="Call <code> on each line of input."),
    click.Command("async-map",
                  short_help="Call <code> on each line of input."),
    click.Command("apply", short_help="Call <code> on input as a sequence."),
    click.Command(
        "async-apply",
        short_help="Call <code> asynchronously on input as a sequence."),
    click.Command(
        "filter",
        short_help=
        "Call <code> on each line of input and exclude false values.",
    ),
    click.Command(
        "async-filter",
        short_help=
        "Async call <code> on each line of input and exclude false values.",
Beispiel #22
0
Module with all click CLIs.

"""

import inspect
import click
from .video_io import convert_imagestack_file_to_video

# CLI for convert_stack_to_video_ffmpeg:
convert_imagestack_file_to_video_cli = click.Command(
    callback=convert_imagestack_file_to_video,
    name=convert_imagestack_file_to_video.__name__,
    help=inspect.getdoc(convert_imagestack_file_to_video),
    params=[
        click.Option(['--frame-range'], type=int, nargs=2),
        click.Option(['--framerate'], type=click.types.FLOAT),
        click.Option(['--vmin'], type=click.types.FLOAT, default=0),
        click.Option(['--vmax'], type=click.types.FLOAT),
        click.Option(['--o-pix-fmt'], default='yuv420p'),
        click.Option(['--normalization_dtype'], default='uint8'),
        click.Option(['--normalization_batching'], default=1, type=int),
        click.Option(['--verbose', '-v'], count=True),
        click.Option(['--quiet/--no-quiet']),
        click.Argument(['inputfn'],
                       required=True,
                       type=click.Path(dir_okay=False,
                                       file_okay=True,
                                       exists=True)),
        click.Argument(['outputfn'], required=False)
    ])
Beispiel #23
0
def build_command(name,
                  description,
                  version,
                  command_group,
                  project_name=None,
                  app_name=None):
    """Build a click command with subcommands

    :param name: command name
    :description: command description
    :version: command version
    :command_group: the entry point group for the subcommand extensions
    :project_name: project that contains the primary command
    :app_name: the app name used for config files
    """

    if not project_name:
        project_name = name

    if not app_name:
        app_name = name

    subcommands = get_plugins(command_group)

    class MyGroup(click.Group):

        # override to set the project and app name
        def get_command(self, ctx, cmd_name):
            ctx.meta['qwcore.project_name'] = project_name
            ctx.meta['qwcore.app_name'] = app_name
            return super(MyGroup, self).get_command(ctx, cmd_name)

    def show_version(ctx, param, value):
        if value:
            click.echo(version)
            ctx.exit()

    def set_debug(ctx, param, value):
        if value:
            log = logging.getLogger(name)
            log.setLevel(getattr(logging, 'DEBUG'))

    version_flag = click.Option(['--version'],
                                is_flag=True,
                                expose_value=False,
                                callback=show_version,
                                is_eager=True,
                                help='Show the version and exit.')
    debug_flag = click.Option(['--debug'],
                              is_flag=True,
                              callback=set_debug,
                              expose_value=False,
                              help='Turn on debug logging.')

    description = "{description}".format(description=description)
    command = MyGroup(command_group,
                      help=description,
                      params=[version_flag, debug_flag])
    for plugin_name, cls in six.iteritems(subcommands):
        subcommand = click.Command(cls.name,
                                   short_help=cls.help,
                                   help=textwrap.dedent(' ' * 4 + cls.__doc__),
                                   params=cls.params,
                                   callback=cls().run)
        command.add_command(subcommand)

    return command
Beispiel #24
0
        base_integrator_config["n_epochs"] = 1
        base_integrator_config["n_iter"] = 1

    run_benchmark_grid_known_integrand(
        dimensions=dimensions,
        integrand=RegulatedHyperSphericalCamel,
        base_integrand_params=base_integrand_params,
        base_integrator_config=base_integrator_config,
        integrand_params_grid=integrands_params_grid,
        integrator_config_grid=None,
        n_batch=100000,
        debug=debug,
        cuda=cuda,
        sql_dtypes=dtypes,
        dbname="benchmarks-debug.db",
        experiment_name="hypercamel")


cli = click.Command("cli",
                    callback=hypercamel_benchmark,
                    params=[
                        PythonLiteralOption(["--dimensions"], default=[2]),
                        PythonLiteralOption(["--fracs"],
                                            default=[0.3, 0.5, 0.7]),
                        click.Option(["--debug/--no-debug"], default=True),
                        click.Option(["--cuda"], default=0, type=int)
                    ])

if __name__ == '__main__':
    cli()
Beispiel #25
0
def test_do_not_show_no_default(runner):
    """When show_default is True and no default is set do not show None."""
    opt = click.Option(["--limit"], show_default=True)
    ctx = click.Context(click.Command("cli"))
    message = opt.get_help_record(ctx)[1]
    assert "[default: None]" not in message
Beispiel #26
0
    # Integrand specific defaults
    base_integrand_params = {
        "s": 0.3,
        "norm": 1.
    }

    benchmarker = VegasSequentialBenchmarker()

    benchmark_config = benchmarker.set_benchmark_grid_config(config=config,
                                                             keep_history=keep_history,
                                                             dbname=db, experiment_name=experiment_name, cuda=cuda,
                                                             debug=debug,
                                                             base_integrand_params=base_integrand_params)

    # Integrand specific CLI argument mapped to standard API

    benchmarker.run(integrand=SymmetricCamelIntegrand, sql_dtypes=dtypes,
                    **benchmark_config)


cli = click.Command("cli", callback=benchmark_camel, params=[
    click.Option(["--debug/--no-debug"], default=None, type=bool),
    click.Option(["--cuda"], default=None, type=int),
    click.Option(["--db"], default=None, type=str),
    click.Option(["--experiment_name"], default=None, type=str),
    click.Option(["--config"], default=None, type=str)
])

if __name__ == '__main__':
    cli()
Beispiel #27
0
def test_formatting_with_options_metavar_empty(runner):
    cli = click.Command("cli", options_metavar="", params=[click.Argument(["var"])])
    result = runner.invoke(cli, ["--help"])
    assert "Usage: cli VAR\n" in result.output
Beispiel #28
0
def ctx():
    """Return an empty `click.Context` instance."""
    return click.Context(click.Command(name='dummy'))
Beispiel #29
0
def test_intrange_default_help_text(runner, type, expect):
    option = click.Option(["--count"], type=type, show_default=True, default=2)
    context = click.Context(click.Command("test"))
    result = option.get_help_record(context)[1]
    assert expect in result
Beispiel #30
0
    click.Option(["--mem_capacity"], default=128, type=click.INT),
    click.Option(["--mem_update_size"], default=16, type=click.INT),
    click.Option(["--mem_update_prob"], default=0.7, type=click.FLOAT),
    click.Option(["--learning_rate_g"], default=3.e-5, type=click.FLOAT),
    click.Option(["--learning_rate_d"], default=6.e-5, type=click.FLOAT),
    click.Option(["--noise_level"], default=0.2, type=click.FLOAT),
    click.Option(["--noise_damping"], default=1.5, type=click.FLOAT),
    click.Option(["--noise_damping_period"], default=5, type=click.INT),
    click.Option(["--data_root"], default="celebA/unlabelled_centered", type=click.STRING),
    click.Option(["--num_workers"], default=1, type=click.INT),
    click.Option(["--torch_seed"], default=None, type=click.INT),
    click.Option(["--checkpoint_period"], default=10, type=click.INT),
]

train_dcgan32_cli = click.Command(name="train",
                                  callback=train_dcgan32,
                                  help="Train DCGAN32",
                                  params=train_dcgan32_options)

dcgan32.add_command(train_dcgan32_cli)


@click.group()
def dcgan32_inversion():
    """Commands related to the inversion model"""


@dcgan32_inversion.command("prepare-dataset",
                           help="Load a checkpoint for the DCGAN32 generator and generate an hdf5 inversion dataset")
@click.option("--dataset_root", default="data/processed/dcgan32_inversion", type=click.Path())
@click.option("--dataset_size", default=100000, type=click.INT)
@click.option("--val_size", default=10000, type=click.INT)