File: _loader.py

package info (click to toggle)
mkdocs-click 0.9.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 300 kB
  • sloc: python: 715; sh: 17; makefile: 6
file content (37 lines) | stat: -rw-r--r-- 1,080 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# (C) Datadog, Inc. 2020-present
# All rights reserved
# Licensed under the Apache license (see LICENSE)
from __future__ import annotations

import importlib
from typing import Any

import click

from ._exceptions import MkDocsClickException


def load_command(module: str, attribute: str) -> click.Command:
    """
    Load and return the Click command object located at '<module>:<attribute>'.
    """
    command = _load_obj(module, attribute)

    if not (isinstance(command, click.Command) or hasattr(command, "context_class")):
        raise MkDocsClickException(
            f"{attribute!r} must be a 'click.Command'-like object, got {type(command)}"
        )

    return command


def _load_obj(module: str, attribute: str) -> Any:
    try:
        mod = importlib.import_module(module)
    except SystemExit:
        raise MkDocsClickException("the module appeared to call sys.exit()")  # pragma: no cover

    try:
        return getattr(mod, attribute)
    except AttributeError:
        raise MkDocsClickException(f"Module {module!r} has no attribute {attribute!r}")