Skip to content

Commit

Permalink
feat: @metric_input as a standardized way to input --metric values
Browse files Browse the repository at this point in the history
  • Loading branch information
Max KvR authored and devmaxde committed Oct 17, 2024
1 parent 9f3e93d commit 7f14037
Show file tree
Hide file tree
Showing 6 changed files with 41 additions and 7 deletions.
3 changes: 2 additions & 1 deletion examples/metricq_get_history.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@

import metricq
from metricq.cli import metricq_command
from metricq.cli.params import metric_input

logger = metricq.get_logger()

Expand Down Expand Up @@ -100,7 +101,7 @@ async def aget_history(


@metricq_command(default_token="history-py-dummy")
@click.option("--metric", default=None)
@metric_input()
@click.option("--list-metrics", is_flag=True)
@click.option("--list-metadata", is_flag=True)
@click_log.simple_verbosity_option(logger) # type: ignore
Expand Down
4 changes: 2 additions & 2 deletions examples/metricq_pandas.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
import click_log # type: ignore

import metricq
from metricq.cli import metricq_command
from metricq.cli import metric_input, metricq_command
from metricq.pandas import PandasHistoryClient

logger = metricq.get_logger()
Expand Down Expand Up @@ -83,7 +83,7 @@ async def aget_history(server: str, token: str, metric: str) -> None:


@metricq_command(default_token="history-py-dummy")
@click.option("--metric", default="example.quantity")
@metric_input(default="example.quantity")
@click_log.simple_verbosity_option(logger) # type: ignore
def get_history(server: str, token: str, metric: str) -> None:
asyncio.run(aget_history(server, token, metric))
Expand Down
4 changes: 3 additions & 1 deletion metricq/cli/__init__.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
from .command import metricq_command
from .params import (
ChoiceParam,
CommandLineChoice,
DurationParam,
TemplateStringParam,
TimestampParam,
metric_input,
)
from .wrapper import metricq_command

__all__ = [
"ChoiceParam",
Expand All @@ -14,4 +15,5 @@
"TemplateStringParam",
"TimestampParam",
"metricq_command",
"metric_input",
]
29 changes: 27 additions & 2 deletions metricq/cli/params.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@
from getpass import getuser
from socket import gethostname
from string import Template
from typing import Any, Generic, List, Optional, Type, TypeVar, Union, cast
from typing import Any, Generic, List, Optional, Type, TypeVar, Union, cast, Callable

import click
from click import Context, Parameter, ParamType, option

from ..timeseries import Timedelta, Timestamp
from .types import FC

_C = TypeVar("_C", covariant=True)

Expand Down Expand Up @@ -169,3 +169,28 @@ def convert(
if not isinstance(value, str):
raise TypeError("expected a string type for TemplateStringParam")
return Template(value).safe_substitute(self.mapping)


class MetricInputParam(ParamType):
pattern = re.compile(r"([a-zA-Z][a-zA-Z0-9_]+\.)+[a-zA-Z][a-zA-Z0-9_]+")

def convert(
self, value: Any, param: Optional[Parameter], ctx: Optional[Context]
) -> str:
if not isinstance(value, str):
raise TypeError("expected a string type for the metric input")
if not self.pattern.match(value):
raise ValueError(f"Invalid metric format: '{value}'.")
return value


def metric_input(default: Optional[str] = None) -> Callable[[FC], FC]:
return option(
"--metric",
type=MetricInputParam(),
metavar="METRIC",
show_default=True,
required=default is None,
default=default,
help="Use the -–metric parameter to specify which metric the program should use",
)
5 changes: 5 additions & 0 deletions metricq/cli/types.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from typing import Any, Callable, TypeVar, Union

import click

FC = TypeVar("FC", bound=Union[Callable[..., Any], click.Command])
3 changes: 2 additions & 1 deletion metricq/cli/command.py → metricq/cli/wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
from dotenv import find_dotenv, load_dotenv

from .. import get_logger
from .params import FC, TemplateStringParam
from .params import TemplateStringParam
from .types import FC

# We do not interpolate (i.e. replace ${VAR} with corresponding environment variables).
# That is because we want to be able to interpolate ourselves for metrics and tokens
Expand Down

0 comments on commit 7f14037

Please sign in to comment.