| 1 |
from urllib import parse as urlparse |
| 2 |
|
| 3 |
import click |
| 4 |
|
| 5 |
|
| 6 |
def validate_count(ctx, param, value): |
| 7 |
if value < 0 or value % 2 != 0: |
| 8 |
raise click.BadParameter("Should be a positive, even integer.") |
| 9 |
return value |
| 10 |
|
| 11 |
|
| 12 |
class URL(click.ParamType): |
| 13 |
name = "url" |
| 14 |
|
| 15 |
def convert(self, value, param, ctx): |
| 16 |
if not isinstance(value, tuple): |
| 17 |
value = urlparse.urlparse(value) |
| 18 |
if value.scheme not in ("http", "https"): |
| 19 |
self.fail( |
| 20 |
f"invalid URL scheme ({value.scheme}). Only HTTP URLs are allowed", |
| 21 |
param, |
| 22 |
ctx, |
| 23 |
) |
| 24 |
return value |
| 25 |
|
| 26 |
|
| 27 |
@click.command() |
| 28 |
@click.option( |
| 29 |
"--count", default=2, callback=validate_count, help="A positive even number." |
| 30 |
) |
| 31 |
@click.option("--foo", help="A mysterious parameter.") |
| 32 |
@click.option("--url", help="A URL", type=URL()) |
| 33 |
@click.version_option() |
| 34 |
def cli(count, foo, url): |
| 35 |
"""Validation. |
| 36 |
|
| 37 |
This example validates parameters in different ways. It does it |
| 38 |
through callbacks, through a custom type as well as by validating |
| 39 |
manually in the function. |
| 40 |
""" |
| 41 |
if foo is not None and foo != "wat": |
| 42 |
raise click.BadParameter( |
| 43 |
'If a value is provided it needs to be the value "wat".', |
| 44 |
param_hint=["--foo"], |
| 45 |
) |
| 46 |
click.echo(f"count: {count}") |
| 47 |
click.echo(f"foo: {foo}") |
| 48 |
click.echo(f"url: {url!r}") |