def _parse_args(source: str) -> List[click.Parameter]: ret = [] src1 = re.sub(r"([\[\]]|\.\.\.)", r" \1 ", source) src2 = [s for s in re.split(r"\s+|(\S*<.*?>)", src1) if s] required = True multiple = False brackets = False arg = None for item in src2: if item == "]": if not brackets: raise ConfigError(f'Missing open bracket in "{source}"') if arg is None: raise ConfigError( f'Missing argument inside brackets in "{source}"') brackets = False required = False elif item == "...": if arg is None: raise ConfigError( f'Ellipsis (...) should follow an argument in "{source}"') if brackets: raise ConfigError( f'Ellipsis (...) inside of brackets in "{source}"') if multiple: raise ConfigError(f'Successive ellipsis (...) in "{source}"') multiple = True else: if arg is not None: if brackets: raise ConfigError(f'Missing close bracket in "{source}"') ret.append( click.Argument( [arg], required=required, nargs=-1 if multiple else 1, type=click.UNPROCESSED, )) required = True multiple = False brackets = False arg = None if item == "[": if brackets: raise ConfigError(f'Nested brackets in "{source}"') brackets = True else: arg = item.upper() if arg is not None: if brackets: raise ConfigError(f'Missing close bracket in "{source}"') ret.append( click.Argument( [arg], required=required, nargs=-1 if multiple else 1, type=click.UNPROCESSED, )) return ret # type: ignore
def make_argument( self, validated, partial, many ): # pylint: disable=unused-argument choices = validated.pop("choices", None) if choices: validated["type"] = click.Choice(choices) return click.Argument(**validated)
def run_params(fn): click_util.append_params(fn, [ click.Argument(("args",), metavar="[ARG...]", nargs=-1), click.Option( ("-l", "--label"), metavar="LABEL", help="Set a label for the run."), click.Option( ("-d", "--run-dir"), metavar="DIR", help="Use an alternative run directory."), click.Option( ("--disable-plugins",), metavar="LIST", help=("A comma separated list of plugin names to disable. " "Use 'all' to disable all plugins.")), click.Option( ("-y", "--yes"), help="Do not prompt before running operation.", is_flag=True), click.Option( ("--print-command",), help="Show the operation command and exit (does not run).", is_flag=True), click.Option( ("--print-env",), help="Show the operation environment and exit (does not run).", is_flag=True), ]) return fn
def diff_params(fn): click_util.append_params(fn, [ click.Argument(("runs", ), metavar="[RUN1 [RUN2]]", nargs=-1), click.Option( ("-O", "--output"), is_flag=True, help="Diff run output."), click.Option( ("-c", "--sourcecode"), is_flag=True, help="Diff run source code."), click.Option( ("-e", "--env"), is_flag=True, help="Diff run environment."), click.Option(("-g", "--flags"), is_flag=True, help="Diff run flags."), click.Option(("-a", "--attrs"), is_flag=True, help=("Diff all run attributes; if specified other " "attribute options are ignored.")), click.Option( ("-d", "--deps"), is_flag=True, help="Diff run dependencies."), click.Option(("-p", "--path"), metavar="PATH", multiple=True, help="Diff specified path; may be used more than once."), click.Option( ("-w", "--working"), is_flag=True, help="Diff run sourcecode to the associated working directory."), click.Option(("-W", "--working-dir"), metavar="PATH", help="Diff run sourcecode to the specified directory."), click.Option( ("-m", "--cmd"), metavar="CMD", help="Command used to diff runs."), runs_support.all_filters, remote_support.remote_option("Diff remote runs."), ]) return fn
def run_params(fn): click_util.append_params(fn, [ click.Argument(("args", ), metavar="[ARG...]", nargs=-1), click.Option( ("-p", "--project", "project_location"), metavar="LOCATION", help="Project location (file system directory) for MODEL."), click.Option( ("--disable-plugins", ), metavar="LIST", help=("A comma separated list of plugin names to disable. " "Use 'all' to disable all plugins.")), click.Option(("-y", "--yes"), help="Do not prompt before running operation.", is_flag=True), click.Option( ("--print-cmd", ), help="Show the operation command and exit (does not run).", is_flag=True), click.Option( ("--print-env", ), help="Show the operation environment and exit (does not run).", is_flag=True), ]) return fn
def build_argument(a): a = copy.copy(a) name = popkey(a, "name") a["type"] = eval(a.get("type", "None"), {"click": click}) a["default"] = eval(a.get("default", "None")) a["nargs"] = eval(a.get("nargs", "None")) return click.Argument([name], **a)
def parse( self, args=None, prog=None, desc=None, otto_yml=None, otto_jobs=None, otto_version=None, ): default_spec = self.otto_spec(otto_yml, otto_jobs, otto_version) cmd = self.add_otto_cmd(prog or 'otto', default_spec.otto) cmd.params += [ click.Argument( param_decls=('remainder', ), nargs=-1, required=False, ) ] cmd.ignore_unknown_options = True cmd.main( args=args or self.args, standalone_mode=False, ) cmd.add_help_option = True cmd.params = [] otto_spec = otto_load(otto_yml=default_spec.otto.params.otto_yml.value) otto_spec.update(self.otto_spec(otto_yml, otto_jobs, otto_version)) cmd = self.add_cmd(prog or 'otto', otto_spec.otto, cmd=cmd) cmd.main( args=self.remainder, standalone_mode=False, ) return self.cmds, otto_spec
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.params.insert(0, click.Argument(("serial-port", ))) # self.params.insert( # --no-discover # 1, # click.Option( # ("-d/-nd", "--discover/--no-discover"), # is_flag=True, # default=False, # help="Log all packets to this file", # ), # ) self.params.insert( # --packet-log 2, click.Option( ("-o", "--packet-log"), type=click.Path(), help="Log all packets to this file", ), ) self.params.insert( # --evofw-flag 3, click.Option( ("-T", "--evofw-flag"), type=click.STRING, help="Pass this traceflag to evofw", ), )
def create(command_name, ipa_command=None, argument_name=None, help='', options={}, transform_options_callback=_default_transform_options_callback, handle_result_callback=_default_handle_result_callback): if not all([ipa_command, argument_name]): raise TypeError argument = click.Argument([argument_name]) options = [ click.Option([option_name], **option_config) for option_name, option_config in options.items() ] params = [argument] + options ipa_wrapper = create_ipa_wrapper( ipa_command, argument_name=argument_name, transform_options_callback=transform_options_callback, handle_result_callback=handle_result_callback) return click.Command(command_name, callback=ipa_wrapper, params=params, help=help)
def runs_arg(fn): """### Specify Runs You may use one or more `RUN` arguments to indicate which runs apply to the command. `RUN` may be a run ID, a run ID prefix, or a one-based index corresponding to a run returned by the list command. Indexes may also be specified in ranges in the form `START:END` where `START` is the start index and `END` is the end index. Either `START` or `END` may be omitted. If `START` is omitted, all runs up to `END` are selected. If `END` id omitted, all runs from `START` on are selected. If both `START` and `END` are omitted (i.e. the ``:`` char is used by itself) all runs are selected. """ click_util.append_params( fn, [ click.Argument( ("runs",), metavar="[RUN...]", nargs=-1, autocompletion=ac_run ) ], ) return fn
def _make_mount_handler_command( handler_name: str, handler: Type[ForeignDataWrapperDataSource] ) -> Command: """Turn the mount handler function into a Click subcommand with help text and kwarg/connection string passing""" help_text, handler_options_help = _generate_handler_help(handler) params = [ click.Argument(["schema"]), click.Option( ["--connection", "-c"], help="Connection string in the form username:password@server:port", ), click.Option( ["--handler-options", "-o"], help=handler_options_help, default="{}", type=JsonType() ), ] from splitgraph.core.output import conn_string_to_dict def _callback(schema, connection, handler_options): handler_options.update(conn_string_to_dict(connection)) mount(schema, mount_handler=handler_name, handler_kwargs=handler_options) cmd = click.Command(handler_name, params=params, callback=_callback, help=help_text) return cmd
def test_missing_argument_string_cast(): ctx = click.Context(click.Command("")) with pytest.raises(click.MissingParameter) as excinfo: click.Argument(["a"], required=True).process_value(ctx, None) assert str(excinfo.value) == "Missing parameter: a"
def diff_params(fn): click_util.append_params(fn, [ click.Argument(("runs", ), metavar="[RUN1 RUN2]", nargs=-1), click.Option( ("-O", "--output"), is_flag=True, help="Diff run output."), click.Option( ("-s", "--source"), is_flag=True, help="Diff run source."), click.Option( ("-e", "--env"), is_flag=True, help="Diff run environment."), click.Option(("-g", "--flags"), is_flag=True, help="Diff run flags."), click.Option(("-a", "--attrs"), is_flag=True, help=("Diff all run attributes; if specified other " "attribute options are ignored.")), click.Option( ("-d", "--deps"), is_flag=True, help="Diff run dependencies."), click.Option(("-p", "--path"), metavar="PATH", multiple=True, help="Diff specified path; may be used more than once."), click.Option( ("-c", "--cmd"), metavar="CMD", help="Command used to diff runs."), runs_support.op_and_label_filters, runs_support.status_filters, ]) return fn
def generate_cli(spec): origin_url = None if isinstance(spec, str): if spec.startswith('https://') or spec.startswith('http://'): origin_url = spec r = requests.get(spec) r.raise_for_status() spec = yaml.safe_load(r.text) else: with open(spec, 'rb') as fd: spec = yaml.safe_load(fd.read()) spec = sanitize_spec(spec) cli = clickclick.AliasedGroup(context_settings=CONTEXT_SETTINGS) spec = Spec.from_dict(spec, origin_url=origin_url) for res_name, res in spec.resources.items(): grp = clickclick.AliasedGroup(normalize_command_name(res_name), short_help='Manage {}'.format(res_name)) cli.add_command(grp) for op_name, op in res.operations.items(): name = get_command_name(op) cmd = click.Command(name, callback=partial(invoke, op=op), short_help=op.op_spec.get('summary')) for param_name, param in op.params.items(): if param.required: arg = click.Argument([param.name]) cmd.params.append(arg) else: arg = click.Option(['--' + param.name]) cmd.params.append(arg) grp.add_command(cmd) return cli
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.params.insert( 0, click.Argument(("input-file", ), type=click.File("r"), default=sys.stdin))
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), ], ) assert fn.__click_params__[-1].name == "runs", fn.__click_params__ fn.__click_params__[-1].autocompletion = _ac_location return fn
def __init__(self): super().__init__('start') self.help = 'Start a project' self.no_args_is_help = True self.params.append(click.Argument(['project'], required=True, default=None)) self.params.append(click.Option(['--noexec'], default=False, is_flag=True, help='Don\'t run specified exec commands'))
def add_project_type_argument(self): """ Add project type to current arguments :return: """ dpt = self.detect_project_type() if dpt is None: self.no_args_is_help = True self.params.append( click.Argument(['project_type'], required=True, type=click.Choice(project_type_names()))) else: self.params.append( click.Argument(['project_type'], required=False, default=dpt.name, type=click.Choice(project_type_names())))
def test_path_type(runner, cls, expect): cli = click.Command( "cli", params=[click.Argument(["p"], type=click.Path(path_type=cls))], callback=lambda p: p, ) result = runner.invoke(cli, ["a/b/c.txt"], standalone_mode=False) assert result.exception is None assert result.return_value == expect
def cmd_restore(self): return click.Command( "restore", callback=getattr(self.provider, "restore_backup"), params=[ click.Argument(["backup_file"]), click.Argument(["database"]), click.Option( ["--recreate"], is_flag=True, help= "Drop the database if it already exists (display a warning if not), " "and create the database."), click.Option(["--create"], is_flag=True, help="Create the database. Will raise an \ exception if the database already exists.") ])
def remote_arg(fn): """`REMOTE` is the name of a configured remote. Use ``guild remotes`` to list available remotes. For information on configuring remotes, see ``guild remotes --help``. """ click_util.append_params(fn, [click.Argument(("remote", ))]) return fn
def test_cast_multi_default(runner, nargs, multiple, default, expect): if nargs == -1: param = click.Argument(["a"], nargs=nargs, default=default) else: param = click.Option(["-a"], nargs=nargs, multiple=multiple, default=default) cli = click.Command("cli", params=[param], callback=lambda a: a) result = runner.invoke(cli, standalone_mode=False) assert result.exception is None assert result.return_value == expect
def get_command(self, ctx, name): params = [click.Argument(["command"], nargs=-1)] plugin = pkg_resources.load_entry_point("pifpaf", "pifpaf.daemons", name) params.extend(map(lambda kw: click.Option(**kw), plugin.get_options())) def _run_cb(*args, **kwargs): return self._run(name, plugin, ctx, *args, **kwargs) return click.Command(name=name, callback=_run_cb, params=params)
def run_arg(fn): """### Specify a Run You may specify a run using a run ID, a run ID prefix, or a one-based index corresponding to a run returned by the list command. """ click_util.append_params(fn, [click.Argument(("run", ), required=False)]) return fn
def __init__(self): super().__init__('start') self.help = 'Create a project' self.no_args_is_help = True self.params.append(click.Argument(['project'], required=True)) self.add_project_type_argument() self.params.append(click.Option(['--vcs'], default=False, type=click.Choice(vcs_names()), help='Stop the vm too')) self.params.append(click.Option(['--template'], default=False, help='Template to use'))
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
class Argument(object): hostname = click.Argument(['hostname'], type=unicode, nargs=1, callback=ArgumentValidation.hostname) ip = click.Argument(['ip'], type=unicode, nargs=1, callback=ArgumentValidation.ip) relm = click.Argument(['relm'], type=unicode, nargs=1, callback=ArgumentValidation.relm) device_type = click.Argument(['device_type'], type=unicode, nargs=1, callback=ArgumentValidation.device_type) search_term = click.Argument(['search_term'], type=unicode, nargs=-1, callback=ArgumentValidation.search_term)
def remote_arg(fn): """`REMOTE` is the name of a configured remote. Use ``tracker remotes`` to list available remotes. For information on configuring remotes, see ``tracker remotes --help``. """ click_utils.append_params(fn, [ click.Argument(("remote",), autocompletion=config.get_remote_names) ]) return fn
def generate(): import click return { 'create': click.Command( "create", callback=create, help= "Create adjust config file with rqalpha bundle adjust data path.", params=[click.Argument(["path"], nargs=1)]) }
def test_params_argument(runner): opt = click.Argument(["a"]) @click.command(params=[opt]) @click.argument("b") def cli(a, b): click.echo(f"{a} {b}") assert cli.params[0].name == "a" assert cli.params[1].name == "b" result = runner.invoke(cli, ["1", "2"]) assert result.output == "1 2\n"