Skip to content

metric_build

django_spire.metric.domain.management.commands.metric_build

Command

Bases: BaseCommand

help = 'Builds or checks the declarative metric structure from the registered Metric registries.' class-attribute instance-attribute

add_arguments

Source code in django_spire/metric/domain/management/commands/metric_build.py
def add_arguments(self, parser: ArgumentParser) -> None:
    parser.add_argument(
        '--check',
        action='store_true',
        help='Only verify that the declared structure exists; exit non-zero when it does not.',
    )
    parser.add_argument(
        '--registry',
        type=str,
        default=None,
        help='Dotted path to a single Metric subclass instead of DJANGO_SPIRE_METRIC_REGISTRY.',
    )

handle

Source code in django_spire/metric/domain/management/commands/metric_build.py
def handle(self, *args, **options) -> None:  # noqa: ARG002
    registries = self._get_registries(options['registry'])

    if not registries:
        self.stdout.write('No metric registries configured in DJANGO_SPIRE_METRIC_REGISTRY.')
        return

    if not options['check']:
        local_registries = []

        for registry in registries:
            if registry.target is Metric.Target.REMOTE:
                label = f'{registry.__module__}.{registry.__qualname__}'
                self.stdout.write(label)
                self.stdout.write('  skipped: targets a remote installation; run metric_build on that installation')
                continue

            local_registries.append(registry)

        registries = local_registries

    failures = []

    for registry in registries:
        label = f'{registry.__module__}.{registry.__qualname__}'
        summary = registry.check() if options['check'] else registry.build()

        self.stdout.write(label)
        self.stdout.write(f'  created {summary.created}, updated {summary.updated}, unchanged {summary.unchanged}')

        for missing in summary.missing:
            self.stdout.write(self.style.WARNING(f'  missing: {missing}'))
        for error in summary.errors:
            self.stdout.write(self.style.ERROR(f'  error: {error}'))

        if not summary.ok:
            failures.append(label)

    if not options['check'] and options['registry'] is None and registries:
        self._apply_orphans(registries)

    if failures:
        mode = 'check' if options['check'] else 'build'
        message = f'Metric {mode} failed for: {", ".join(failures)}'
        raise CommandError(message)

    if options['check']:
        self.stdout.write(self.style.SUCCESS('Metric structure check passed.'))
    else:
        self.stdout.write(self.style.SUCCESS('Metric structure built.'))