Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux

Documentation: Document each netlink family

This is a simple script that parses the Netlink YAML spec files
(Documentation/netlink/specs/), and generates RST files to be rendered
in the Network -> Netlink Specification documentation page.

Create a python script that is invoked during 'make htmldocs', reads the
YAML specs input file and generate the correspondent RST file.

Create a new Documentation/networking/netlink_spec index page, and
reference each Netlink RST file that was processed above in this main
index.rst file.

In case of any exception during the parsing, dump the error and skip
the file.

Do not regenerate the RST files if the input files (YAML) were not
changed in-between invocations.

Suggested-by: Jakub Kicinski <kuba@kernel.org>
Signed-off-by: Breno Leitao <leitao@debian.org>

----
Changelog:

V3:
* Do not regenerate the RST files if the input files were not
changed. In order to do it, a few things changed:
- Rely on Makefile more to find what changed, and trigger
individual file processing
- The script parses file by file now (instead of batches)
- Create a new option to generate the index file

V2:
* Moved the logic from a sphinx extension to a external script
* Adjust some formatting as suggested by Donald Hunter and Jakub
* Auto generating all the rsts instead of having stubs
* Handling error gracefully
Reviewed-by: Jakub Kicinski <kuba@kernel.org>
Signed-off-by: David S. Miller <davem@davemloft.net>

authored by

Breno Leitao and committed by
David S. Miller
f061c9f7 45c226dd

+409 -1
+15 -1
Documentation/Makefile
··· 97 97 cp $(if $(patsubst /%,,$(DOCS_CSS)),$(abspath $(srctree)/$(DOCS_CSS)),$(DOCS_CSS)) $(BUILDDIR)/$3/_static/; \ 98 98 fi 99 99 100 - htmldocs: 100 + YNL_INDEX:=$(srctree)/Documentation/networking/netlink_spec/index.rst 101 + YNL_RST_DIR:=$(srctree)/Documentation/networking/netlink_spec 102 + YNL_YAML_DIR:=$(srctree)/Documentation/netlink/specs 103 + YNL_TOOL:=$(srctree)/tools/net/ynl/ynl-gen-rst.py 104 + 105 + YNL_RST_FILES_TMP := $(patsubst %.yaml,%.rst,$(wildcard $(YNL_YAML_DIR)/*.yaml)) 106 + YNL_RST_FILES := $(patsubst $(YNL_YAML_DIR)%,$(YNL_RST_DIR)%, $(YNL_RST_FILES_TMP)) 107 + 108 + $(YNL_INDEX): $(YNL_RST_FILES) 109 + @$(YNL_TOOL) -o $@ -x 110 + 111 + $(YNL_RST_DIR)/%.rst: $(YNL_YAML_DIR)/%.yaml 112 + @$(YNL_TOOL) -i $< -o $@ 113 + 114 + htmldocs: $(YNL_INDEX) 101 115 @$(srctree)/scripts/sphinx-pre-install --version-check 102 116 @+$(foreach var,$(SPHINXDIRS),$(call loop_cmd,sphinx,html,$(var),,$(var))) 103 117
+1
Documentation/networking/index.rst
··· 55 55 filter 56 56 generic-hdlc 57 57 generic_netlink 58 + netlink_spec/index 58 59 gen_stats 59 60 gtp 60 61 ila
+388
tools/net/ynl/ynl-gen-rst.py
··· 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. 14 + 15 + This code is split in three big parts: 16 + 1) RST formatters: Use to convert a string to a RST output 17 + 2) Parser helpers: Functions to parse the YAML data structure 18 + 3) Main function and small helpers 19 + """ 20 + 21 + from typing import Any, Dict, List 22 + import os.path 23 + import sys 24 + import argparse 25 + import logging 26 + import yaml 27 + 28 + 29 + SPACE_PER_LEVEL = 4 30 + 31 + 32 + # RST Formatters 33 + # ============== 34 + def headroom(level: int) -> str: 35 + """Return space to format""" 36 + return " " * (level * SPACE_PER_LEVEL) 37 + 38 + 39 + def bold(text: str) -> str: 40 + """Format bold text""" 41 + return f"**{text}**" 42 + 43 + 44 + def inline(text: str) -> str: 45 + """Format inline text""" 46 + return f"``{text}``" 47 + 48 + 49 + def sanitize(text: str) -> str: 50 + """Remove newlines and multiple spaces""" 51 + # This is useful for some fields that are spread across multiple lines 52 + return str(text).replace("\n", "").strip() 53 + 54 + 55 + def rst_fields(key: str, value: str, level: int = 0) -> str: 56 + """Return a RST formatted field""" 57 + return headroom(level) + f":{key}: {value}" 58 + 59 + 60 + def rst_definition(key: str, value: Any, level: int = 0) -> str: 61 + """Format a single rst definition""" 62 + return headroom(level) + key + "\n" + headroom(level + 1) + str(value) 63 + 64 + 65 + def rst_paragraph(paragraph: str, level: int = 0) -> str: 66 + """Return a formatted paragraph""" 67 + return headroom(level) + paragraph 68 + 69 + 70 + def rst_bullet(item: str, level: int = 0) -> str: 71 + """Return a formatted a bullet""" 72 + return headroom(level) + f" - {item}" 73 + 74 + 75 + def rst_subsection(title: str) -> str: 76 + """Add a sub-section to the document""" 77 + return f"{title}\n" + "-" * len(title) 78 + 79 + 80 + def rst_subsubsection(title: str) -> str: 81 + """Add a sub-sub-section to the document""" 82 + return f"{title}\n" + "~" * len(title) 83 + 84 + 85 + def rst_section(title: str) -> str: 86 + """Add a section to the document""" 87 + return f"\n{title}\n" + "=" * len(title) 88 + 89 + 90 + def rst_subtitle(title: str) -> str: 91 + """Add a subtitle to the document""" 92 + return "\n" + "-" * len(title) + f"\n{title}\n" + "-" * len(title) + "\n\n" 93 + 94 + 95 + def rst_title(title: str) -> str: 96 + """Add a title to the document""" 97 + return "=" * len(title) + f"\n{title}\n" + "=" * len(title) + "\n\n" 98 + 99 + 100 + def rst_list_inline(list_: List[str], level: int = 0) -> str: 101 + """Format a list using inlines""" 102 + return headroom(level) + "[" + ", ".join(inline(i) for i in list_) + "]" 103 + 104 + 105 + def rst_header() -> str: 106 + """The headers for all the auto generated RST files""" 107 + lines = [] 108 + 109 + lines.append(rst_paragraph(".. SPDX-License-Identifier: GPL-2.0")) 110 + lines.append(rst_paragraph(".. NOTE: This document was auto-generated.\n\n")) 111 + 112 + return "\n".join(lines) 113 + 114 + 115 + def rst_toctree(maxdepth: int = 2) -> str: 116 + """Generate a toctree RST primitive""" 117 + lines = [] 118 + 119 + lines.append(".. toctree::") 120 + lines.append(f" :maxdepth: {maxdepth}\n\n") 121 + 122 + return "\n".join(lines) 123 + 124 + 125 + # Parsers 126 + # ======= 127 + 128 + 129 + def parse_mcast_group(mcast_group: List[Dict[str, Any]]) -> str: 130 + """Parse 'multicast' group list and return a formatted string""" 131 + lines = [] 132 + for group in mcast_group: 133 + lines.append(rst_bullet(group["name"])) 134 + 135 + return "\n".join(lines) 136 + 137 + 138 + def parse_do(do_dict: Dict[str, Any], level: int = 0) -> str: 139 + """Parse 'do' section and return a formatted string""" 140 + lines = [] 141 + for key in do_dict.keys(): 142 + lines.append(rst_paragraph(bold(key), level + 1)) 143 + lines.append(parse_do_attributes(do_dict[key], level + 1) + "\n") 144 + 145 + return "\n".join(lines) 146 + 147 + 148 + def parse_do_attributes(attrs: Dict[str, Any], level: int = 0) -> str: 149 + """Parse 'attributes' section""" 150 + if "attributes" not in attrs: 151 + return "" 152 + lines = [rst_fields("attributes", rst_list_inline(attrs["attributes"]), level + 1)] 153 + 154 + return "\n".join(lines) 155 + 156 + 157 + def parse_operations(operations: List[Dict[str, Any]]) -> str: 158 + """Parse operations block""" 159 + preprocessed = ["name", "doc", "title", "do", "dump"] 160 + lines = [] 161 + 162 + for operation in operations: 163 + lines.append(rst_section(operation["name"])) 164 + lines.append(rst_paragraph(sanitize(operation["doc"])) + "\n") 165 + 166 + for key in operation.keys(): 167 + if key in preprocessed: 168 + # Skip the special fields 169 + continue 170 + lines.append(rst_fields(key, operation[key], 0)) 171 + 172 + if "do" in operation: 173 + lines.append(rst_paragraph(":do:", 0)) 174 + lines.append(parse_do(operation["do"], 0)) 175 + if "dump" in operation: 176 + lines.append(rst_paragraph(":dump:", 0)) 177 + lines.append(parse_do(operation["dump"], 0)) 178 + 179 + # New line after fields 180 + lines.append("\n") 181 + 182 + return "\n".join(lines) 183 + 184 + 185 + def parse_entries(entries: List[Dict[str, Any]], level: int) -> str: 186 + """Parse a list of entries""" 187 + lines = [] 188 + for entry in entries: 189 + if isinstance(entry, dict): 190 + # entries could be a list or a dictionary 191 + lines.append( 192 + rst_fields(entry.get("name", ""), sanitize(entry.get("doc", "")), level) 193 + ) 194 + elif isinstance(entry, list): 195 + lines.append(rst_list_inline(entry, level)) 196 + else: 197 + lines.append(rst_bullet(inline(sanitize(entry)), level)) 198 + 199 + lines.append("\n") 200 + return "\n".join(lines) 201 + 202 + 203 + def parse_definitions(defs: Dict[str, Any]) -> str: 204 + """Parse definitions section""" 205 + preprocessed = ["name", "entries", "members"] 206 + ignored = ["render-max"] # This is not printed 207 + lines = [] 208 + 209 + for definition in defs: 210 + lines.append(rst_section(definition["name"])) 211 + for k in definition.keys(): 212 + if k in preprocessed + ignored: 213 + continue 214 + lines.append(rst_fields(k, sanitize(definition[k]), 0)) 215 + 216 + # Field list needs to finish with a new line 217 + lines.append("\n") 218 + if "entries" in definition: 219 + lines.append(rst_paragraph(":entries:", 0)) 220 + lines.append(parse_entries(definition["entries"], 1)) 221 + if "members" in definition: 222 + lines.append(rst_paragraph(":members:", 0)) 223 + lines.append(parse_entries(definition["members"], 1)) 224 + 225 + return "\n".join(lines) 226 + 227 + 228 + def parse_attr_sets(entries: List[Dict[str, Any]]) -> str: 229 + """Parse attribute from attribute-set""" 230 + preprocessed = ["name", "type"] 231 + ignored = ["checks"] 232 + lines = [] 233 + 234 + for entry in entries: 235 + lines.append(rst_section(entry["name"])) 236 + for attr in entry["attributes"]: 237 + type_ = attr.get("type") 238 + attr_line = bold(attr["name"]) 239 + if type_: 240 + # Add the attribute type in the same line 241 + attr_line += f" ({inline(type_)})" 242 + 243 + lines.append(rst_subsubsection(attr_line)) 244 + 245 + for k in attr.keys(): 246 + if k in preprocessed + ignored: 247 + continue 248 + lines.append(rst_fields(k, sanitize(attr[k]), 2)) 249 + lines.append("\n") 250 + 251 + return "\n".join(lines) 252 + 253 + 254 + def parse_yaml(obj: Dict[str, Any]) -> str: 255 + """Format the whole YAML into a RST string""" 256 + lines = [] 257 + 258 + # Main header 259 + 260 + lines.append(rst_header()) 261 + 262 + title = f"Family ``{obj['name']}`` netlink specification" 263 + lines.append(rst_title(title)) 264 + lines.append(rst_paragraph(".. contents::\n")) 265 + 266 + if "doc" in obj: 267 + lines.append(rst_subtitle("Summary")) 268 + lines.append(rst_paragraph(obj["doc"], 0)) 269 + 270 + # Operations 271 + if "operations" in obj: 272 + lines.append(rst_subtitle("Operations")) 273 + lines.append(parse_operations(obj["operations"]["list"])) 274 + 275 + # Multicast groups 276 + if "mcast-groups" in obj: 277 + lines.append(rst_subtitle("Multicast groups")) 278 + lines.append(parse_mcast_group(obj["mcast-groups"]["list"])) 279 + 280 + # Definitions 281 + if "definitions" in obj: 282 + lines.append(rst_subtitle("Definitions")) 283 + lines.append(parse_definitions(obj["definitions"])) 284 + 285 + # Attributes set 286 + if "attribute-sets" in obj: 287 + lines.append(rst_subtitle("Attribute sets")) 288 + lines.append(parse_attr_sets(obj["attribute-sets"])) 289 + 290 + return "\n".join(lines) 291 + 292 + 293 + # Main functions 294 + # ============== 295 + 296 + 297 + def parse_arguments() -> argparse.Namespace: 298 + """Parse arguments from user""" 299 + parser = argparse.ArgumentParser(description="Netlink RST generator") 300 + 301 + parser.add_argument("-v", "--verbose", action="store_true") 302 + parser.add_argument("-o", "--output", help="Output file name") 303 + 304 + # Index and input are mutually exclusive 305 + group = parser.add_mutually_exclusive_group() 306 + group.add_argument( 307 + "-x", "--index", action="store_true", help="Generate the index page" 308 + ) 309 + group.add_argument("-i", "--input", help="YAML file name") 310 + 311 + args = parser.parse_args() 312 + 313 + if args.verbose: 314 + logging.basicConfig(level=logging.DEBUG) 315 + 316 + if args.input and not os.path.isfile(args.input): 317 + logging.warning("%s is not a valid file.", args.input) 318 + sys.exit(-1) 319 + 320 + if not args.output: 321 + logging.error("No output file specified.") 322 + sys.exit(-1) 323 + 324 + if os.path.isfile(args.output): 325 + logging.debug("%s already exists. Overwriting it.", args.output) 326 + 327 + return args 328 + 329 + 330 + def parse_yaml_file(filename: str) -> str: 331 + """Transform the YAML specified by filename into a rst-formmated string""" 332 + with open(filename, "r", encoding="utf-8") as spec_file: 333 + yaml_data = yaml.safe_load(spec_file) 334 + content = parse_yaml(yaml_data) 335 + 336 + return content 337 + 338 + 339 + def write_to_rstfile(content: str, filename: str) -> None: 340 + """Write the generated content into an RST file""" 341 + logging.debug("Saving RST file to %s", filename) 342 + 343 + with open(filename, "w", encoding="utf-8") as rst_file: 344 + rst_file.write(content) 345 + 346 + 347 + def generate_main_index_rst(output: str) -> None: 348 + """Generate the `networking_spec/index` content and write to the file""" 349 + lines = [] 350 + 351 + lines.append(rst_header()) 352 + lines.append(rst_title("Netlink Specification")) 353 + lines.append(rst_toctree(1)) 354 + 355 + index_dir = os.path.dirname(output) 356 + logging.debug("Looking for .rst files in %s", index_dir) 357 + for filename in os.listdir(index_dir): 358 + if not filename.endswith(".rst") or filename == "index.rst": 359 + continue 360 + lines.append(f" {filename.replace('.rst', '')}\n") 361 + 362 + logging.debug("Writing an index file at %s", output) 363 + write_to_rstfile("".join(lines), output) 364 + 365 + 366 + def main() -> None: 367 + """Main function that reads the YAML files and generates the RST files""" 368 + 369 + args = parse_arguments() 370 + 371 + if args.input: 372 + logging.debug("Parsing %s", args.input) 373 + try: 374 + content = parse_yaml_file(os.path.join(args.input)) 375 + except Exception as exception: 376 + logging.warning("Failed to parse %s.", args.input) 377 + logging.warning(exception) 378 + sys.exit(-1) 379 + 380 + write_to_rstfile(content, args.output) 381 + 382 + if args.index: 383 + # Generate the index RST file 384 + generate_main_index_rst(args.output) 385 + 386 + 387 + if __name__ == "__main__": 388 + main()