Skip to content

Commit

Permalink
Working on Documentation
Browse files Browse the repository at this point in the history
  • Loading branch information
devmaxde committed Nov 25, 2024
1 parent 497bd92 commit 9f7e18c
Show file tree
Hide file tree
Showing 4 changed files with 175 additions and 50 deletions.
58 changes: 10 additions & 48 deletions docs/api/cli.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ CLI



This package provides CLI utilities and decorators for MetricQ applications, including custom parameter types for choices, durations, timestamps, templates, and metrics.
This module provides CLI utilities and decorators for MetricQ applications, including custom parameter types for choices, durations, timestamps, templates, and metrics.

The main focus of this module is to standardize the CLI interfaces of different programs.

To use this part of the package you need to install additional dependencies. You can install the dependencies using the following command:

Expand All @@ -19,64 +21,24 @@ Wrapper
@metricq_command
^^^^^^^^^^^^^^^^^^

Decorates a function to create a MetricQ CLI command with options for server and token configuration.
Server and Token must be in the right order.

**Parameters**

- **default_token** (`str`): The default client token for the MetricQ network.

**Usage**

.. code-block:: python
@metricq_command(default_token="example.program")
def example(
server: str, token: str
) -> None:
pass
if __name__ == "__main__":
example()
..
.. autofunction:: metricq.cli.wrapper.metricq_command

@metricq_metric_option
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Defines an option for specifying one or more metrics. Should be used in combination with @metricq_command().
If multiple is set to true, the return type changes to List[metric]
.. autofunction:: metricq.cli.wrapper.metricq_metric_option

**Parameters**

- **default** (`Optional[str]`, optional): The default metric. Defaults to `None`.
- **multiple** (`bool`, optional): If `True`, allows multiple metrics to be specified. Defaults to `False`.
- **required** (`bool`, optional): If `True`, makes the option required. Defaults to `False`.

**Usage**

.. code-block:: python
@metricq_command(default_token="example.program")
@metricq_metricq_option(required=true, default="example.metric")
def metric_example(
server: str, token: str, metric: Metric
) -> None:
pass
@metricq_command(default_token="example.program")
@metricq_metricq_option(required=true, multiple=True) # <-- multiple is set
def multi_metric_example(
server: str, token: str, metric: List[Metric]
) -> None:
pass
..

Parameter
----------------

.. automodule:: metricq.cli.params
:members:
:exclude-members: get_metavar, convert, name





85 changes: 83 additions & 2 deletions metricq/cli/params.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,49 @@ def from_choice(cls: Type[_C], option: str) -> _C:


class ChoiceParam(Generic[ChoiceType], ParamType):
"""
A custom parameter type for Click, enabling choice-based selection.
Example implementation:
.. code-block:: python
from enum import Enum, auto
from click import option
from metricq.cli import metricq_command, ChoiceParam, CommandLineChoice
class OutputFormat(CommandLineChoice, Enum):
Pretty = auto()
Json = auto()
@classmethod
def default(cls) -> "OutputFormat":
return OutputFormat.Pretty
FORMAT = ChoiceParam(OutputFormat, "format")
@metricq_command(default_token="example.program")
@option(
"--format",
type=FORMAT,
default=OutputFormat.default(),
show_default=OutputFormat.default().as_choice(),
help="Print results in this format",
)
def dummy_program(
server: str, token: str, format: str
) -> None:
Dummy(server=server, token=token, format=format).run()
if __name__ == "__main__":
dummy_program()
..
"""
def __init__(self, cls: Type[ChoiceType], name: str):
self.cls = cls
self.name = name
Expand Down Expand Up @@ -78,10 +121,48 @@ def convert(

class DurationParam(ParamType):
"""
Convert strings to ``metricq.Timedelta`` objects.
A custom parameter type for Click, enabling Time values.
Accepts the following string inputs
- <value>[<unit>]
- <value>[<unit>] eg:
The following units are supported:
- 's' / 'seconds[s]' for seconds
- 'min' / 'minute[s]' for minutes
- 'h' / 'hour[s]' for hours
- 'd' / 'day[s]' for days
example implementation:
.. code-block:: python
from typing import Optional
from click import option
from metricq import Timedelta
from metricq.cli import metricq_command, DurationParam
TIMEOUT = DurationParam(default=None)
@metricq_command(default_token="example.program")
@option(
"--timeout",
type=TIMEOUT,
default=TIMEOUT.default,
help="A timeout for the program",
)
def dummy_program(
server: str, token: str, timeout: Optional[Timedelta]
) -> None:
Dummy(server=server, token=token, timeout=timeout).run()
if __name__ == "__main__":
dummy_program()
..
"""

name = "duration"
Expand Down
81 changes: 81 additions & 0 deletions metricq/cli/wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,42 @@ def metricq_token_option(default: str) -> Callable[[FC], FC]:
def metricq_metric_option(
default: Optional[str] = None, multiple: bool = False, required: bool = False
) -> Callable[[FC], FC]:
"""
The metric option can be used to select one or more metrics the program should use.
The metric can be set with the -\\-metric or -m parameter. If no default value is set, the parameter is required. The metric input must follow the specification (``([a-zA-Z][a-zA-Z0-9_]+\\.)+[a-zA-Z][a-zA-Z0-9_]+``).
**Parameter**
- **default** (`Optional[str]`, optional): The default metric. Defaults to `None`. You can only set one default, even if the program allows multiple inputs.
- **multiple** (`bool`, optional): If `True`, allows multiple metrics to be specified. Defaults to `False`.
- **required** (`bool`, optional): If `True`, makes the -\\-metric option required. Defaults to `False`. If required is set and no default is provided, at least one metric input is required.
**Usage**
.. code-block:: python
@metricq_command(default_token="example.program")
@metricq_metricq_option(required=true, default="example.metric")
def metric_example(
server: str, token: str, metric: str
) -> None:
# Initialize the DummySink class with a list of metrics given on the
# command line.
sink = DummySink(metrics=metric, token=token, url=server)
# Run the sink. This call will block until the connection is closed.
sink.run()
@metricq_command(default_token="example.program")
@metricq_metricq_option(required=true, multiple=True) # <-- multiple is set
def multi_metric_example(
server: str, token: str, metric: List[str]
) -> None:
sink = DummySink(metrics=metric, token=token, url=server)
sink.run()
..
"""
response_default = default if (default is None or not multiple) else [default]
help = "Use the -–metric / -m parameter to specify which metric the program should use."
if multiple:
Expand Down Expand Up @@ -73,6 +109,51 @@ def get_metric_command_logger() -> logging.Logger:
def metricq_command(
default_token: str, client_version: str | None = None
) -> Callable[[FC], click.Command]:
"""
The @metricq_command is the first parameter of any given click/cli command. The main purpose is to provide the most used parameters.
These parameters are 'server', 'token' and 'syslog'.
- -\\-server:
The Server param is used to specify the amqp url of the Network. for example: amqp://localhost/
The server param can be set using the environment variable METRICQ_SERVER or adding the --server {value} option to the cli command
- -\\-token:
The Token is used to identify each program on the metricq network. for example: sink-py-dummy
The token param can be set using the environment variable METRICQ_TOKEN or adding the --token {value} option to the cli command
- -\\-syslog:
The Syslog param is used to enable syslog. It can be used with or without parameter.
If used without parameter (for example: ``metricq-check --syslog`` ) the Syslog will default to localhost:514.
You can also specify a Unix socket (for example: /dev/log) or a custom host (for example: example.com:5114) by adding the value to the syslog flag (for example: ``metricq-check --syslog example.com:5114``)
Full example:
``metricq-check --server amqp://localhost/ --token sink-py-dummy --syslog``
**Parameters**
- **default_token** (`str`): The default token can be set by the developer to reduce the required params when calling the program. The token can be overwritten by using the -\\-token or environment variable. If no default token is set, the -\\-token input is required to run the program.
**Usage**
.. code-block:: python
@metricq_command(default_token="source-py-dummy")
def dummy(
server: str, token: str
) -> None:
src = DummySource(token=token, url=server)
src.run()
if __name__ == "__main__":
dummy()
..
"""
logger = get_metric_command_logger()

log_decorator = cast(
Expand Down
1 change: 1 addition & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ typing =
%(examples)s
%(test)s
docs =
%(pandas)s
sphinx ~= 6.1.3
sphinx_rtd_theme ~= 1.2.0
sphinx_autodoc_typehints ~= 1.22.0
Expand Down

0 comments on commit 9f7e18c

Please sign in to comment.