xref: /linux/tools/net/ynl/pyynl/ynl_gen_rst.py (revision a34b0e4e21d6be3c3d620aa7f9dfbf0e9550c19e)
1#!/usr/bin/env python3
2# SPDX-License-Identifier: GPL-2.0
3# -*- coding: utf-8; mode: python -*-
4
5"""
6    Script to auto generate the documentation for Netlink specifications.
7
8    :copyright:  Copyright (C) 2023  Breno Leitao <leitao@debian.org>
9    :license:    GPL Version 2, June 1991 see linux/COPYING for details.
10
11    This script performs extensive parsing to the Linux kernel's netlink YAML
12    spec files, in an effort to avoid needing to heavily mark up the original
13    YAML file. It uses the library code from scripts/lib.
14"""
15
16import os.path
17import pathlib
18import sys
19import argparse
20import logging
21
22# pylint: disable=no-name-in-module,wrong-import-position
23sys.path.append(pathlib.Path(__file__).resolve().parent.as_posix())
24from lib import YnlDocGenerator    # pylint: disable=C0413
25
26def parse_arguments() -> argparse.Namespace:
27    """Parse arguments from user"""
28    parser = argparse.ArgumentParser(description="Netlink RST generator")
29
30    parser.add_argument("-v", "--verbose", action="store_true")
31    parser.add_argument("-o", "--output", help="Output file name")
32
33    # Index and input are mutually exclusive
34    group = parser.add_mutually_exclusive_group()
35    group.add_argument("-i", "--input", help="YAML file name")
36
37    args = parser.parse_args()
38
39    if args.verbose:
40        logging.basicConfig(level=logging.DEBUG)
41
42    if args.input and not os.path.isfile(args.input):
43        logging.warning("%s is not a valid file.", args.input)
44        sys.exit(-1)
45
46    if not args.output:
47        logging.error("No output file specified.")
48        sys.exit(-1)
49
50    if os.path.isfile(args.output):
51        logging.debug("%s already exists. Overwriting it.", args.output)
52
53    return args
54
55
56def write_to_rstfile(content: str, filename: str) -> None:
57    """Write the generated content into an RST file"""
58    logging.debug("Saving RST file to %s", filename)
59
60    with open(filename, "w", encoding="utf-8") as rst_file:
61        rst_file.write(content)
62
63
64# pylint: disable=broad-exception-caught
65def main() -> None:
66    """Main function that reads the YAML files and generates the RST files"""
67
68    args = parse_arguments()
69
70    parser = YnlDocGenerator()
71
72    if args.input:
73        logging.debug("Parsing %s", args.input)
74        try:
75            content = parser.parse_yaml_file(os.path.join(args.input))
76        except Exception as exception:
77            logging.warning("Failed to parse %s.", args.input)
78            logging.warning(exception)
79            sys.exit(-1)
80
81        write_to_rstfile(content, args.output)
82
83
84if __name__ == "__main__":
85    main()
86