vuls: init at 0.27.0
[NixPkgs.git] / nixos / lib / test-driver / extract-docstrings.py
blob64850ca711f3b6d02d15969a0ffba842dcd9bd5f
1 import ast
2 import sys
3 from pathlib import Path
5 """
6 This program takes all the Machine class methods and prints its methods in
7 markdown-style. These can then be included in the NixOS test driver
8 markdown style, assuming the docstrings themselves are also in markdown.
10 These are included in the test driver documentation in the NixOS manual.
11 See https://nixos.org/manual/nixos/stable/#ssec-machine-objects
13 The python input looks like this:
15 ```py
16 ...
18 class Machine(...):
19 ...
21 def some_function(self, param1, param2):
23 documentation string of some_function.
24 foo bar baz.
26 ...
27 ```
29 Output will be:
31 ```markdown
32 ...
34 some_function(param1, param2)
36 : documentation string of some_function.
37 foo bar baz.
39 ...
40 ```
42 """
45 def main() -> None:
46 if len(sys.argv) != 2:
47 print(f"Usage: {sys.argv[0]} <path-to-test-driver>")
48 sys.exit(1)
50 module = ast.parse(Path(sys.argv[1]).read_text())
52 class_definitions = (node for node in module.body if isinstance(node, ast.ClassDef))
54 machine_class = next(filter(lambda x: x.name == "Machine", class_definitions))
55 assert machine_class is not None
57 function_definitions = [
58 node for node in machine_class.body if isinstance(node, ast.FunctionDef)
60 function_definitions.sort(key=lambda x: x.name)
62 for function in function_definitions:
63 docstr = ast.get_docstring(function)
64 if docstr is not None:
65 args = ", ".join(a.arg for a in function.args.args[1:])
66 args = f"({args})"
68 docstr = "\n".join(f" {line}" for line in docstr.strip().splitlines())
70 print(f"{function.name}{args}\n\n:{docstr[1:]}\n")
73 if __name__ == "__main__":
74 main()