authentik.blueprints.management.commands.blueprint_shell

Test and debug Blueprints

 1"""Test and debug Blueprints"""
 2
 3import atexit
 4from pathlib import Path
 5from pprint import pformat
 6from sys import exit as sysexit
 7from textwrap import indent
 8
 9from django.core.management.base import BaseCommand, no_translations
10from structlog.stdlib import get_logger
11from yaml import load
12
13try:
14    import readline
15except ImportError:  # pragma: no cover
16    # There's no libreadline in the distroless image, degrade instead of failing
17    readline = None
18
19from authentik.blueprints.v1.common import BlueprintLoader, EntryInvalidError
20from authentik.core.management.commands.shell import get_banner_text
21from authentik.lib.utils.errors import exception_to_string
22
23LOGGER = get_logger()
24
25
26class Command(BaseCommand):
27    """Test and debug Blueprints"""
28
29    lines = []
30
31    def __init__(self, *args, **kwargs) -> None:
32        super().__init__(*args, **kwargs)
33        if readline is None:
34            self.stderr.write("readline is not available, line editing and history are disabled")
35            return
36        histfolder = Path("~").expanduser() / Path(".local/share/authentik")
37        histfolder.mkdir(parents=True, exist_ok=True)
38        histfile = histfolder / Path("blueprint_shell_history")
39        readline.parse_and_bind("tab: complete")
40        readline.parse_and_bind("set editing-mode vi")
41
42        try:
43            readline.read_history_file(str(histfile))
44        except FileNotFoundError:
45            pass
46
47        atexit.register(readline.write_history_file, str(histfile))
48
49    @no_translations
50    def handle(self, *args, **options):
51        """Interactively debug blueprint files"""
52        self.stdout.write(get_banner_text("Blueprint shell"))
53        self.stdout.write("Type '.eval' to evaluate previously entered statement(s).")
54
55        def do_eval():
56            yaml_input = "\n".join([line for line in self.lines if line])
57            data = load(yaml_input, BlueprintLoader)
58            self.stdout.write(pformat(data))
59            self.lines = []
60
61        while True:
62            try:
63                line = input("> ")
64                if line == ".eval":
65                    do_eval()
66                else:
67                    self.lines.append(line)
68            except EntryInvalidError as exc:
69                self.stdout.write("Failed to evaluate expression:")
70                self.stdout.write(indent(exception_to_string(exc), prefix="  "))
71            except EOFError:
72                break
73            except KeyboardInterrupt:
74                self.stdout.write()
75                sysexit(0)
76        self.stdout.write()
LOGGER = <BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
class Command(django.core.management.base.BaseCommand):
27class Command(BaseCommand):
28    """Test and debug Blueprints"""
29
30    lines = []
31
32    def __init__(self, *args, **kwargs) -> None:
33        super().__init__(*args, **kwargs)
34        if readline is None:
35            self.stderr.write("readline is not available, line editing and history are disabled")
36            return
37        histfolder = Path("~").expanduser() / Path(".local/share/authentik")
38        histfolder.mkdir(parents=True, exist_ok=True)
39        histfile = histfolder / Path("blueprint_shell_history")
40        readline.parse_and_bind("tab: complete")
41        readline.parse_and_bind("set editing-mode vi")
42
43        try:
44            readline.read_history_file(str(histfile))
45        except FileNotFoundError:
46            pass
47
48        atexit.register(readline.write_history_file, str(histfile))
49
50    @no_translations
51    def handle(self, *args, **options):
52        """Interactively debug blueprint files"""
53        self.stdout.write(get_banner_text("Blueprint shell"))
54        self.stdout.write("Type '.eval' to evaluate previously entered statement(s).")
55
56        def do_eval():
57            yaml_input = "\n".join([line for line in self.lines if line])
58            data = load(yaml_input, BlueprintLoader)
59            self.stdout.write(pformat(data))
60            self.lines = []
61
62        while True:
63            try:
64                line = input("> ")
65                if line == ".eval":
66                    do_eval()
67                else:
68                    self.lines.append(line)
69            except EntryInvalidError as exc:
70                self.stdout.write("Failed to evaluate expression:")
71                self.stdout.write(indent(exception_to_string(exc), prefix="  "))
72            except EOFError:
73                break
74            except KeyboardInterrupt:
75                self.stdout.write()
76                sysexit(0)
77        self.stdout.write()

Test and debug Blueprints

Command(*args, **kwargs)
32    def __init__(self, *args, **kwargs) -> None:
33        super().__init__(*args, **kwargs)
34        if readline is None:
35            self.stderr.write("readline is not available, line editing and history are disabled")
36            return
37        histfolder = Path("~").expanduser() / Path(".local/share/authentik")
38        histfolder.mkdir(parents=True, exist_ok=True)
39        histfile = histfolder / Path("blueprint_shell_history")
40        readline.parse_and_bind("tab: complete")
41        readline.parse_and_bind("set editing-mode vi")
42
43        try:
44            readline.read_history_file(str(histfile))
45        except FileNotFoundError:
46            pass
47
48        atexit.register(readline.write_history_file, str(histfile))
lines = []
def handle(*args, **kwargs):
106    def wrapper(*args, **kwargs):
107        from django.utils import translation
108
109        saved_locale = translation.get_language()
110        translation.deactivate_all()
111        try:
112            res = handle_func(*args, **kwargs)
113        finally:
114            if saved_locale is not None:
115                translation.activate(saved_locale)
116        return res

The type of the None singleton.