Python click.Parameter() Examples
The following are 13
code examples of click.Parameter().
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: update_urls.py From runway with Apache License 2.0 | 6 votes |
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 #2
Source File: config.py From ward with MIT License | 6 votes |
def set_defaults_from_config( context: click.Context, param: click.Parameter, value: Union[str, int], ) -> Path: supplied_paths = context.params.get("path") search_paths = supplied_paths if not search_paths: search_paths = (".",) project_root = find_project_root([Path(path) for path in search_paths]) file_config = read_config_toml(project_root, CONFIG_FILE) if file_config: config_path = project_root / "pyproject.toml" else: config_path = None context.params["config_path"] = config_path file_config = apply_multi_defaults(file_config, context.params) if context.default_map is None: context.default_map = {} context.default_map.update(file_config) return project_root
Example #3
Source File: test_black.py From black with MIT License | 6 votes |
def test_read_pyproject_toml(self) -> None: test_toml_file = THIS_DIR / "test.toml" # Fake a click context and parameter so mypy stays happy class FakeContext(click.Context): def __init__(self) -> None: self.default_map: Dict[str, Any] = {} class FakeParameter(click.Parameter): def __init__(self) -> None: pass fake_ctx = FakeContext() black.read_pyproject_toml( fake_ctx, FakeParameter(), str(test_toml_file), ) config = fake_ctx.default_map self.assertEqual(config["verbose"], "1") self.assertEqual(config["check"], "no") self.assertEqual(config["diff"], "y") self.assertEqual(config["color"], "True") self.assertEqual(config["line_length"], "79") self.assertEqual(config["target_version"], ["py36", "py37", "py38"]) self.assertEqual(config["exclude"], r"\.pyi?$") self.assertEqual(config["include"], r"\.py?$")
Example #4
Source File: server_run.py From nichtparasoup with MIT License | 5 votes |
def _param_get_config(_: Context, param: Parameter, config_file: Optional[_FilePath]) -> Config: # pragma: no cover try: return get_config(config_file) except Exception as ex: raise BadParameter( f'{ex}\n\tUse the "server config check" command for an analyse.', param=param ) from ex
Example #5
Source File: cli.py From raiden-services with MIT License | 5 votes |
def validate_address( _ctx: click.Context, _param: click.Parameter, value: Optional[str] ) -> Optional[Address]: if value is None: # None as default value allowed return None if not is_checksum_address(value): raise click.BadParameter("not an EIP-55 checksummed address") return to_canonical_address(value)
Example #6
Source File: __main__.py From raiden-contracts with MIT License | 5 votes |
def validate_address( _: Context, _param: Union[Option, Parameter], value: Optional[str] ) -> Optional[ChecksumAddress]: if not value: return None try: is_address(value) return to_checksum_address(value) except ValueError: raise click.BadParameter("must be a valid ethereum address")
Example #7
Source File: __main__.py From raiden-contracts with MIT License | 5 votes |
def error_removed_option(message: str) -> Callable: """ Takes a message and returns a callback that raises NoSuchOption if the value is not None. The message is used as an argument to NoSuchOption. """ def f(_: Any, param: Parameter, value: Any) -> None: if value is not None: raise click.NoSuchOption( f'--{param.name.replace("_", "-")} is no longer a valid option. ' + message ) return f
Example #8
Source File: config.py From tartufo with GNU General Public License v2.0 | 5 votes |
def read_pyproject_toml( ctx: click.Context, _param: click.Parameter, value: str ) -> Optional[str]: if not value: root_path = ctx.params.get("repo_path", None) if not root_path: root_path = "." root_path = pathlib.Path(root_path).resolve() config_path = root_path / "pyproject.toml" if config_path.is_file(): value = str(config_path) else: config_path = root_path / "tartufo.toml" if config_path.is_file(): value = str(config_path) else: return None try: toml_file = toml.load(value) config = toml_file.get("tool", {}).get("tartufo", {}) except (toml.TomlDecodeError, OSError) as exc: raise click.FileError( filename=str(config_path), hint="Error reading configuration file: {}".format(exc), ) if not config: return None if ctx.default_map is None: ctx.default_map = {} ctx.default_map.update( # type: ignore {k.replace("--", "").replace("-", "_"): v for k, v in config.items()} ) return str(value)
Example #9
Source File: main.py From typer with MIT License | 5 votes |
def get_install_completion_arguments() -> Tuple[click.Parameter, click.Parameter]: install_param, show_param = get_completion_inspect_parameters() click_install_param, _ = get_click_param(install_param) click_show_param, _ = get_click_param(show_param) return click_install_param, click_show_param
Example #10
Source File: main.py From typer with MIT License | 5 votes |
def get_callback( *, callback: Optional[Callable] = None, params: Sequence[click.Parameter] = [], convertors: Dict[str, Callable[[str], Any]] = {}, context_param_name: str = None, ) -> Optional[Callable]: if not callback: return None parameters = get_params_from_function(callback) use_params: Dict[str, Any] = {} for param_name in parameters: use_params[param_name] = None for param in params: use_params[param.name] = param.default def wrapper(**kwargs: Any) -> Any: for k, v in kwargs.items(): if k in convertors: use_params[k] = convertors[k](v) else: use_params[k] = v if context_param_name: use_params[context_param_name] = click.get_current_context() return callback(**use_params) # type: ignore update_wrapper(wrapper, callback) return wrapper
Example #11
Source File: models.py From typer with MIT License | 5 votes |
def __init__( self, *, name: str, default: Any = inspect.Parameter.empty, annotation: Any = inspect.Parameter.empty, ) -> None: self.name = name self.default = default self.annotation = annotation
Example #12
Source File: completion.py From typer with MIT License | 5 votes |
def install_callback(ctx: click.Context, param: click.Parameter, value: Any) -> Any: if not value or ctx.resilient_parsing: return value # pragma no cover if isinstance(value, str): shell, path = install(shell=value) else: shell, path = install() click.secho(f"{shell} completion installed in {path}", fg="green") click.echo("Completion will take effect once you restart the terminal") sys.exit(0)
Example #13
Source File: main.py From typer with MIT License | 4 votes |
def get_param_callback( *, callback: Optional[Callable] = None, convertor: Optional[Callable] = None ) -> Optional[Callable]: if not callback: return None parameters = get_params_from_function(callback) ctx_name = None click_param_name = None value_name = None untyped_names: List[str] = [] for param_name, param_sig in parameters.items(): if lenient_issubclass(param_sig.annotation, click.Context): ctx_name = param_name elif lenient_issubclass(param_sig.annotation, click.Parameter): click_param_name = param_name else: untyped_names.append(param_name) # Extract value param name first if untyped_names: value_name = untyped_names.pop() # If context and Click param were not typed (old/Click callback style) extract them if untyped_names: if ctx_name is None: ctx_name = untyped_names.pop(0) if click_param_name is None: if untyped_names: click_param_name = untyped_names.pop(0) if untyped_names: raise click.ClickException( "Too many CLI parameter callback function parameters" ) def wrapper(ctx: click.Context, param: click.Parameter, value: Any) -> Any: use_params: Dict[str, Any] = {} if ctx_name: use_params[ctx_name] = ctx if click_param_name: use_params[click_param_name] = param if value_name: if convertor: use_value = convertor(value) else: use_value = value use_params[value_name] = use_value return callback(**use_params) # type: ignore update_wrapper(wrapper, callback) return wrapper