Debian Codegraph @

docs/scripts/generate_snippet.py

raw symbols SCIP
1 #!/usr/bin/env python
2 # Copyright (c) 2023-2026 Arista Networks, Inc.
3 # Use of this source code is governed by the Apache License 2.0
4 # that can be found in the LICENSE file.
5 """A script to generate svg or txt files from anta command.
6
7 usage:
8
9 python generate_snippet.py anta ...
10 """
11 # This script contains print statements
12 # ruff: noqa: T201
13
14 import io
15 import logging
16 import os
17 import pathlib
18 import re
19 import sys
20 from contextlib import redirect_stdout, suppress
21 from importlib import import_module
22 from importlib.metadata import entry_points
23 from typing import Literal
24 from unittest.mock import patch
25
26 from rich.logging import RichHandler
27 from rich.markup import escape
28 from rich.progress import Progress
29
30 sys.path.insert(0, str(pathlib.Path(__file__).parents[2]))
31
32 from anta.cli.console import console
33 from anta.cli.nrfu.utils import anta_progress_bar
34
35 root = logging.getLogger()
36
37 r = RichHandler(console=console)
38 root.addHandler(r)
39
40 SNAPSHOT_OUTPUT_PATTERN = re.compile(r"anta_snapshot_\d{4}-\d{2}-\d{2}_\d{2}_\d{2}_\d{2}")
41
42
43 def custom_progress_bar() -> Progress:
44 """Set the console of progress_bar to main anta console.
45
46 Caveat: this capture all steps of the progress bar..
47 Disabling refresh to only capture beginning and end
48 """
49 progress = anta_progress_bar()
50 progress.live.auto_refresh = False
51 progress.live.console = console
52 return progress
53
54
55 def main(args: list[str], output: Literal["svg", "txt"] = "svg") -> None:
56 """Execute the script."""
57 # Sane rich size
58 os.environ["COLUMNS"] = "120"
59
60 output_dir = pathlib.Path(__file__).parent.parent / "snippets" if output == "txt" else pathlib.Path(__file__).parent.parent / "imgs"
61
62 # stolen from https://github.com/ewels/rich-click/blob/main/src/rich_click/cli.py
63 script_name = args[0]
64 console_scripts = entry_points(group="console_scripts")
65 scripts = {script.name: script for script in console_scripts}
66
67 if script_name in scripts:
68 # A VALID SCRIPT WAS passed
69 script = scripts[script_name]
70 module_path, function_name = script.value.split(":", 1)
71 prog = script_name
72 elif ":" in script_name:
73 # the path to a function was passed
74 module_path, function_name = args[0].split(":", 1)
75 prog = module_path.split(".", 1)[0]
76 else:
77 print("This is supposed to be used with anta only")
78 print("Usage: python generate_svg.py anta <options>")
79 sys.exit(1)
80
81 # possibly-used-before-assignment - prog / function_name -> not understanding sys.exit here...
82 # pylint: disable=E0606
83 sys.argv = [prog, *args[1:]]
84 module = import_module(module_path)
85 function = getattr(module, function_name)
86
87 pipe = io.StringIO()
88 console.record = True
89 console.file = pipe
90 # Redirect stdout of the program towards another StringIO to capture help
91 # that is not part or anta rich console
92 # redirect potential progress bar output to console by patching
93 with redirect_stdout(io.StringIO()) as f, patch("anta.cli.nrfu.utils.anta_progress_bar", custom_progress_bar), suppress(SystemExit):
94 if output == "txt":
95 console.print(f"$ {' '.join(sys.argv)}")
96 function()
97
98 if "--help" in args:
99 console.print(escape(f.getvalue()))
100
101 filename = f"{'_'.join(x.replace('/', '_').replace('-', '').replace('.', '') for x in args)}.{output}"
102 filename = output_dir / filename
103 if output == "txt":
104 content = SNAPSHOT_OUTPUT_PATTERN.sub("anta_snapshot_<date>_<time>", console.export_text()[:-1])
105 with filename.open("w") as fd:
106 fd.write(content)
107 # TODO: Not using this to avoid newline console.save_text(str(filename))
108 elif output == "svg":
109 console.save_svg(str(filename), title=" ".join(args))
110
111 print(f"File saved at {filename}")
112
113
114 if __name__ == "__main__":
115 main(sys.argv[1:], "svg")