|
| 1 | +from operator import itemgetter |
| 2 | +from typing import Any, Callable |
| 3 | + |
| 4 | +import prometheus_client |
| 5 | +from django.core.management import BaseCommand, CommandParser |
| 6 | +from django.template.loader import get_template |
| 7 | +from django.utils.module_loading import autodiscover_modules |
| 8 | +from prometheus_client.metrics import MetricWrapperBase |
| 9 | + |
| 10 | + |
| 11 | +class Command(BaseCommand): |
| 12 | + help = "Generate documentation for the Flagsmith codebase." |
| 13 | + |
| 14 | + def add_arguments(self, parser: CommandParser) -> None: |
| 15 | + subparsers = parser.add_subparsers( |
| 16 | + title="sub-commands", |
| 17 | + required=True, |
| 18 | + ) |
| 19 | + |
| 20 | + metric_parser = subparsers.add_parser( |
| 21 | + "metrics", |
| 22 | + help="Generate metrics documentation.", |
| 23 | + ) |
| 24 | + metric_parser.set_defaults(handle_method=self.handle_metrics) |
| 25 | + |
| 26 | + def initialise(self) -> None: |
| 27 | + from common.gunicorn import metrics # noqa: F401 |
| 28 | + |
| 29 | + autodiscover_modules( |
| 30 | + "metrics", |
| 31 | + ) |
| 32 | + |
| 33 | + def handle( |
| 34 | + self, |
| 35 | + *args: Any, |
| 36 | + handle_method: Callable[..., None], |
| 37 | + **options: Any, |
| 38 | + ) -> None: |
| 39 | + self.initialise() |
| 40 | + handle_method(*args, **options) |
| 41 | + |
| 42 | + def handle_metrics(self, *args: Any, **options: Any) -> None: |
| 43 | + template = get_template("docgen-metrics.md") |
| 44 | + |
| 45 | + flagsmith_metrics = sorted( |
| 46 | + ( |
| 47 | + { |
| 48 | + "name": collector._name, |
| 49 | + "documentation": collector._documentation, |
| 50 | + "labels": collector._labelnames, |
| 51 | + "type": collector._type, |
| 52 | + } |
| 53 | + for collector in prometheus_client.REGISTRY._collector_to_names |
| 54 | + if isinstance(collector, MetricWrapperBase) |
| 55 | + ), |
| 56 | + key=itemgetter("name"), |
| 57 | + ) |
| 58 | + |
| 59 | + self.stdout.write( |
| 60 | + template.render( |
| 61 | + context={"flagsmith_metrics": flagsmith_metrics}, |
| 62 | + ) |
| 63 | + ) |
0 commit comments