def test_group_add_command_name(runner): cli = click.Group("cli") cmd = click.Command("a", params=[click.Option(["-x"], required=True)]) cli.add_command(cmd, "b") # Check that the command is accessed through the registered name, # not the original name. result = runner.invoke(cli, ["b"], default_map={"b": {"x": 3}}) assert result.exit_code == 0
def create_pipeline_cli_group(): group = click.Group(name="pipeline") group.add_command(pipeline_list_command) group.add_command(pipeline_print_command) group.add_command(pipeline_graphviz_command) group.add_command(pipeline_execute_command) group.add_command(pipeline_scaffold_command) return group
def create_schedule_cli_group(): group = click.Group(name="schedule") group.add_command(schedule_list_command) group.add_command(schedule_up_command) group.add_command(schedule_preview_command) group.add_command(schedule_start_command) group.add_command(schedule_stop_command) return group
def test_with_group(self): command = click.Group() ctx = click.Context(command) shell = make_click_shell(ctx) assert isinstance(shell, ClickCmd)
def __init__(self, import_name, root_path=None, url_prefix=None, template_folder='templates', config_folder='config'): self.import_name = import_name #: init debug var self.debug = os.environ.get('EMMETT_RUN_ENV') == "true" #: set paths for the application if root_path is None: root_path = get_root_path(self.import_name) self.root_path = root_path self.static_path = os.path.join(self.root_path, "static") self.template_path = os.path.join(self.root_path, template_folder) self.config_path = os.path.join(self.root_path, config_folder) #: the click command line context for this application self.cli = click.Group(self) #: init the configuration self.config = Config(self) #: try to create needed folders create_missing_app_folders(self) #: init languages self._languages = [] self._languages_set = set() self._language_default = None self._language_force_on_url = False self.translator = Translator(os.path.join(self.root_path, 'languages'), default_language=self.language_default or 'en', watch_changes=self.debug, str_class=Tstr) #: init routing self._pipeline = [] self._router_http = HTTPRouter(self, url_prefix=url_prefix) self._router_ws = WebsocketRouter(self, url_prefix=url_prefix) self._asgi_handlers = { 'http': HTTPHandler(self), 'lifespan': LifeSpanHandler(self), 'websocket': WSHandler(self) } self.error_handlers = {} self.template_default_extension = '.html' #: init logger self._logger = None self.logger_name = self.import_name #: init extensions self.ext = sdict() self._extensions_env = sdict() self._extensions_listeners = {key: [] for key in Extension._signals_} #: init templater self.templater = Templater(path=self.template_path, encoding=self.config.templates_encoding, escape=self.config.templates_escape, prettify=self.config.templates_prettify, reload=self.config.templates_auto_reload) #: store app in current current.app = self
def main(): """ :meta private: """ cli = click.Group() cli.add_command(new_project_cli) cli.add_command(new_model_cli) cli()
def valid_command_test(args, callback=identity_callback, config=DEFAULT_TEST_CONFIG): root_command = click.Group('root') generate_commands(root_command, config, callback) result = click_run(root_command, args) assert result.exit_code is 0 return result
def test_group_commands_dict(runner): """A Group can be built with a dict of commands.""" @click.command() def sub(): click.echo("sub", nl=False) cli = click.Group(commands={"other": sub}) result = runner.invoke(cli, ["other"]) assert result.output == "sub"
def test_group_from_list(runner): """A Group can be built with a list of commands.""" @click.command() def sub(): click.echo("sub", nl=False) cli = click.Group(commands=[sub]) result = runner.invoke(cli, ["sub"]) assert result.output == "sub"
def run_cli(self) -> None: """Run command line application.""" self.bootstrap() app = click.Group() for command in self.commands: app.add_command(command) with self.scoped(ResolveContext()): app()
def __init__(self, import_name, root_path=None, url_prefix=None, template_folder='templates', config_folder='config'): self.import_name = import_name #: set paths for the application if root_path is None: root_path = get_root_path(self.import_name) self.root_path = root_path self.static_path = os.path.join(self.root_path, "static") self.template_path = os.path.join(self.root_path, template_folder) self.config_path = os.path.join(self.root_path, config_folder) #: the click command line context for this application self.cli = click.Group(self) #: init the configuration self.config = ConfigData() self.config.modules_class = AppModule self.config.hostname_default = None self.config.static_version = None self.config.static_version_urls = None self.config.handle_static = True self.config.url_default_namespace = None self.config.templates_auto_reload = False self.config.templates_escape = 'common' self.config.templates_prettify = False self.config.templates_encoding = 'utf8' #: try to create needed folders create_missing_app_folders(self) #: init expose module Expose._bind_app_(self, url_prefix) self._wsgi_pre_handler = (_pre_handler_prefix if Expose._prefix_main else _pre_handler) # Expose.application = self self.error_handlers = {} self.template_default_extension = '.html' #: init logger self._logger = None self.logger_name = self.import_name #: init languages self.languages = [] self.language_default = None self.language_force_on_url = False self.language_write = False #: init extensions self.ext = sdict() self._extensions_env = sdict() self._extensions_listeners = {key: [] for key in Extension._signals_} self.template_extensions = [] self.template_preloaders = {} self.template_lexers = {} #: init templater self.templater = Templater(self) #: init debug var self.debug = os.environ.get('WEPPY_RUN_ENV') == "true"
def create_pipeline_cli_group(): group = click.Group(name="pipeline") group.add_command(pipeline_list_command) group.add_command(pipeline_print_command) group.add_command(pipeline_execute_command) group.add_command(pipeline_backfill_command) group.add_command(pipeline_scaffold_command) group.add_command(pipeline_launch_command) group.add_command(pipeline_list_versions_command) return group
def add_otto_cmd(self, uid, task): task.name = task.get('name', uid) cmd = click.Group( task.name, chain=True, add_help_option=False, invoke_without_command=True, callback=self.callback(task), ) cmd.params = self.add_params(task.params) return cmd
def recursive_cmd(group_or_cmd): name = group_or_cmd[0] help_msg = group_or_cmd[1] msg_or_cmds = group_or_cmd[2] if isinstance(msg_or_cmds, (list, tuple)): group = click.Group(name=name, help=help_msg) for cmd in msg_or_cmds: group.add_command(recursive_cmd(cmd)) return group else: return PrintCommand(msg_or_cmds, name=name, help=help_msg)
def cli(cls, singleton=False): group = click.Group(name='metadata', short_help="Commands on metadata.") resource_type = cls._resource_type() def _fetch_resource(client, id, **kwargs): if singleton: resource = cls.singleton(client) else: mac = kwargs.pop('mac', None) resource = cls.lookup(client, id, mac=mac) return resource def _id_argument(): def wrapper(func): if not singleton: return click.argument('id', metavar=resource_type)(func) return func return wrapper @group.command('list') @_id_argument() @pass_client def _list(client, id=None, **kwargs): """Get metadata.""" resource = _fetch_resource(client, id, **kwargs) metadata = resource.metadata() Metadata.display(client, [metadata], **kwargs) @group.command('update') @_id_argument() @click.argument('value', type=JSONParamType()) @pass_client def _update(client, value, id=None, **kwargs): """Update metadata.""" resource = _fetch_resource(client, id, **kwargs) metadata = resource.metadata() if value is not None: metadata = metadata.update(value) Metadata.display(client, [metadata], **kwargs) @group.command('replace') @_id_argument() @click.argument('value', type=JSONParamType()) @pass_client def _replace(client, value, id=None, **kwargs): """Replace metadata.""" resource = _fetch_resource(client, id, **kwargs) metadata = resource.metadata() if value is not None: metadata = metadata.replace(value) Metadata.display(client, [metadata], **kwargs) return group
def create_clean_cli(cli): clean = click.Group('clean', help="Clean up generated data") @click.option("-c", "--category", "categories", default=get_image_category_names(), multiple=True, type=click.Choice(get_image_category_names())) @click.option("-t", "--transformation", "transformations", default=get_transformation_names(), multiple=True, type=click.Choice(get_transformation_names())) @click.option("--dryrun/--no-dryrun", default=False) @click.option("--verbose/--silent", default=True) @clean.command('transform') def transform_clean(categories, transformations, dryrun, verbose): """ clean transformed images """ for category in categories: # remove the reference output image output_path = os.path.join(ROOT_DIR, *image_dir, category, "output.jpg") if os.path.isfile(output_path): rm(output_path, dryrun=dryrun, verbose=verbose) # remove images under each transformation for transformation in transformations: transformation_path = os.path.join(ROOT_DIR, *image_dir, category, transformation) if os.path.isdir(transformation_path): rm(transformation_path, dryrun=dryrun, verbose=verbose) @click.option("--dryrun/--no-dryrun", default=False) @click.option("--verbose/--silent", default=True) @clean.command('sort') def sort_clean(dryrun, verbose): """ clean sort data generated with the metrics. """ path = os.path.join(ROOT_DIR, *metric_sorted_data_dir) if os.path.isdir(path): rm(path, dryrun=dryrun, verbose=verbose) @click.option("--dryrun/--no-dryrun", default=False) @click.option("--verbose/--silent", default=True) @clean.command('printable') def printable_clean(dryrun, verbose): """ clean generated printable files """ path = os.path.join(ROOT_DIR, *printable_dir) if os.path.isdir(path): rm(path, dryrun=dryrun, verbose=verbose) cli.add_command(clean)
def test_propagate_show_default_setting(runner): """A context's ``show_default`` setting defaults to the value from the parent context. """ group = click.Group( commands={ "sub": click.Command("sub", params=[click.Option(["-a"], default="a")]), }, context_settings={"show_default": True}, ) result = runner.invoke(group, ["sub", "--help"]) assert "[default: a]" in result.output
def main(): logging.debug('Welcome to cqcli.') os.makedirs(config.CONFIG_DIR, exist_ok=True) cmds = command.get_all_commands() if len(sys.argv) == 1: print('Nothing to do...') exit(0) else: cli = click.Group() for cmd in cmds: cli.add_command(cmd.click_command()) logging.debug("Add command %s" % cmd.name) cli()
def get_cli(self): """ Get Click command for each individual stdio command """ commands = [] for command in COMMANDS: commands.append( to_cli_command(command, click.pass_context( wrap_command(command)(self)))) return click.Group(commands=commands)
def create_info_cli(cli): info = click.Group('info', help="Show information related to various modules") @info.command('all') def info_all(): click.echo("Image categories:") plist(get_image_category_names(), indent="\t") click.echo("Transformations:") plist(get_transformation_names(), indent="\t") click.echo("Analyses:") plist(get_metric_names(), indent="\t") cli.add_command(info)
def run(*args, **kwargs) -> None: """Primary app entry point.""" dogs = Dogs() cats = Cats() cli = click.Group( help="Demonstration of a nested CLI app using Click!", commands={ dogs.name: dogs, cats.name: cats } ) cli(*args, **kwargs)
def create_api_cli_group(): group = click.Group( name="api", help= ("[INTERNAL] These commands are intended to support internal use cases. Users should " "generally not invoke these commands interactively."), ) group.add_command(execute_run_with_structured_logs_command) group.add_command(execute_step_with_structured_logs_command) group.add_command(launch_scheduled_execution) group.add_command(grpc_command) group.add_command(grpc_health_check_command) return group
def cli(self): cli = click.Group(self.name) command_names = filter( lambda n: hasattr(getattr(self, n), "cli_command"), dir(self)) for name in command_names: params = getattr(getattr(self, name), "__click_params__", None) cli.add_command( click.Command(name, callback=getattr(self, name), params=params)) if self.shell_command: cli.add_command(click.Command("shell", callback=self.shell)) return cli
def provider_group_factory(): """Dynamically generate provider groups for all providers, and add all basic command to it""" for provider in all_providers(): p = get_notifier(provider) provider_name = p.name help = f"Options for '{provider_name}'" group = click.Group(name=provider_name, help=help) # Notify command notify = partial(_notify, p=p) group.add_command( schema_to_command(p, "notify", notify, add_message=True)) # Resources command resources_callback = partial(_resources, p=p) resources_cmd = click.Command( "resources", callback=resources_callback, help="Show provider resources list", ) group.add_command(resources_cmd) pretty_opt = click.Option(["--pretty/--not-pretty"], help="Output a pretty version of the JSON") # Add any provider resources for resource in p.resources: rsc = getattr(p, resource) rsrc_callback = partial(_resource, rsc) rsrc_command = schema_to_command(rsc, resource, rsrc_callback, add_message=False) rsrc_command.params.append(pretty_opt) group.add_command(rsrc_command) for name, description in CORE_COMMANDS.items(): callback = func_factory(p, name) params = [pretty_opt] command = click.Command( name, callback=callback, help=description.format(provider_name), params=params, ) group.add_command(command) notifiers_cli.add_command(group)
def create_api_cli_group(): group = click.Group( name='api', help= ('[INTERNAL] These commands are intended to support internal use cases. Users should ' 'generally not invoke these commands interactively.'), ) group.add_command(execute_run_command) group.add_command(repository_snapshot_command) group.add_command(pipeline_subset_snapshot_command) group.add_command(execution_plan_snapshot_command) group.add_command(list_repositories_command) group.add_command(partition_data_command) group.add_command(schedule_execution_data_command) group.add_command(launch_scheduled_execution) return group
def __init__( self, import_name, root_path=None, template_folder='templates', config_folder='config' ): self.import_name = import_name #: set paths for the application if root_path is None: root_path = get_root_path(self.import_name) self.root_path = root_path self.static_path = os.path.join(self.root_path, "static") self.template_path = os.path.join(self.root_path, template_folder) self.config_path = os.path.join(self.root_path, config_folder) #: the click command line context for this application self.cli = click.Group(self) #: init the configuration self.config = ConfigData() self.config.hostname_default = None self.config.static_version = None self.config.static_version_urls = None self.config.handle_static = True self.config.url_default_namespace = None self.config.templates_auto_reload = False #: try to create needed folders create_missing_app_folders(self) #: init expose module Expose.application = self self.error_handlers = {} self.template_default_extension = '.html' #: init logger self._logger = None self.logger_name = self.import_name #: set request.now reference self.now_reference = "utc" #: init languages self.languages = [] self.language_default = None self.language_force_on_url = False self.language_write = False #: init extensions self.ext = sdict() self._extensions_env = sdict() self._extensions_listeners = {key: [] for key in Extension._signals_} self.template_extensions = [] self.template_preloaders = {} self.template_lexers = {} #: init templater self.templater = Templater(self)
def command(timerange, daily): group = click.Group( commands={ "range": click.Command( "range", callback=timerange, params=[START, END, LENGTH], short_help= "Calculate and save target position in specific time range."), "daily": click.Command( "daily", callback=daily, short_help="Calculate and save most current target position") }) group()
def generate(): tick = TickRequester() command = click.Command( name='tick', callback=tick.request, params=[ FIELD_OPTION, START_OPTION, END_OPTION, click.Option(['--routing/--no-routing'], default=True) ], short_help="Request tick data and save into .xlsx file.") return { "request": click.Group("request", {"tick": command}, short_help="Initialize config and file system.") }
def autoclick(*object: typing.Union[types.FunctionType, click.Command], group=None, **settings) -> click.Command: app = group or click.Group() for command in object: if isinstance(command, click.Command): app.add_command(command) else: decorators = command_from_signature(command) for decorator in reversed(decorators): command = decorator(command) command = app.command(help=inspect.getdoc(command), no_args_is_help=bool(decorators), **settings)(command) if len(object) == 1: return command return app
def test_other_command_forward(runner): cli = click.Group() @cli.command() @click.option('--count', default=1) def test(count): click.echo('Count: %d' % count) @cli.command() @click.option('--count', default=1) @click.pass_context def dist(ctx, count): ctx.forward(test) ctx.invoke(test, count=42) result = runner.invoke(cli, ['dist']) assert not result.exception assert result.output == 'Count: 1\nCount: 42\n'