Last active
November 9, 2025 02:45
-
-
Save ink-splatters/7d95adef2163d4d04cba8828f5901f5c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| Defines click argument Source type which resolves to URL or filesystem Path | |
| Example: | |
| ```python | |
| @click.command() | |
| @click.argument( | |
| "source", type=SourceType(path_opts={"exists": True, "dir_okay": False}) | |
| ) | |
| def load(source: Source) -> None: ...""" | |
| import pathlib | |
| import typing as t | |
| from urllib.parse import urlparse | |
| import click | |
| # https://click-params.readthedocs.io | |
| from click_params.domain import UrlParamType | |
| type Source = click.Path | str | |
| class SourceType(click.ParamType): | |
| """Click parameter type for Source: URL or filesystem path.""" | |
| name = "source" | |
| def __init__( | |
| self, *, path_opts: dict[str, t.Any] | None = None, url_opts: dict[str, t.Any] | None = None | |
| ) -> None: | |
| path_opts = path_opts if path_opts else {} | |
| if "path_type" not in path_opts: | |
| path_opts |= {"path_type": pathlib.Path} | |
| self._path_opts = path_opts | |
| url_opts = url_opts if url_opts else {} | |
| if "may_have_port" not in url_opts: | |
| url_opts |= {"may_have_port": True} | |
| self._url_opts = url_opts | |
| def convert( | |
| self, | |
| value: str, | |
| param: click.Parameter | None, | |
| ctx: click.Context | None, | |
| ) -> Source: | |
| """Source converter | |
| Returns string if urlparse detected schema, otherwise Path (pathlib.Path by default). | |
| """ | |
| param_type: click.ParamType = ( | |
| UrlParamType(**self._url_opts) | |
| if urlparse(value).scheme | |
| else click.Path(**self._path_opts) | |
| ) | |
| return param_type.convert(value, param, ctx) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment