|
| 1 | +import dataclasses |
| 2 | +import datetime as dt |
| 3 | +import logging |
| 4 | +from typing import Any, Dict, Optional |
| 5 | + |
| 6 | +import docutils.nodes |
| 7 | +import requests |
| 8 | +from docutils import nodes |
| 9 | +from docutils.examples import internals |
| 10 | +from docutils.parsers.rst.directives import register_directive |
| 11 | +from docutils.parsers.rst.directives.admonitions import Note |
| 12 | +from docutils.parsers.rst.roles import normalized_role_options, register_canonical_role # type: ignore[attr-defined] |
| 13 | + |
| 14 | +from cratedb_toolkit.docs.util import GenericProcessor |
| 15 | + |
| 16 | +logger = logging.getLogger(__name__) |
| 17 | + |
| 18 | + |
| 19 | +DOCS_URL = "https://github.com/crate/crate/raw/refs/heads/5.10/docs/general/builtins/scalar-functions.rst" |
| 20 | + |
| 21 | + |
| 22 | +@dataclasses.dataclass |
| 23 | +class Function: |
| 24 | + name: str |
| 25 | + signature: str |
| 26 | + category: str |
| 27 | + description: str |
| 28 | + # TODO: Parse `returns` and `example` from `description`. |
| 29 | + returns: Optional[str] = None |
| 30 | + example: Optional[str] = None |
| 31 | + |
| 32 | + def to_dict(self) -> Dict[str, Any]: |
| 33 | + """ |
| 34 | + Convert the dataclass instance to a dictionary. |
| 35 | +
|
| 36 | + Returns: |
| 37 | + Dict[str, Any]: A dictionary containing all fields of the instance. |
| 38 | + """ |
| 39 | + return dataclasses.asdict(self) |
| 40 | + |
| 41 | + |
| 42 | +@dataclasses.dataclass |
| 43 | +class FunctionRegistry: |
| 44 | + meta: Dict[str, str] = dataclasses.field(default_factory=dict) |
| 45 | + functions: Dict[str, Function] = dataclasses.field(default_factory=dict) |
| 46 | + |
| 47 | + def register(self, function: Function): |
| 48 | + """ |
| 49 | + Register a new function in the registry. |
| 50 | +
|
| 51 | + Adds a Function instance to the registry using its signature as the unique key. |
| 52 | + Raises a ValueError if a function with the same signature is already registered. |
| 53 | +
|
| 54 | + Args: |
| 55 | + function: A Function instance to be added to the registry. |
| 56 | + """ |
| 57 | + if function.signature in self.functions: |
| 58 | + raise ValueError(f"Function already registered: {function.signature}") |
| 59 | + self.functions[function.signature] = function |
| 60 | + |
| 61 | + def to_dict(self) -> Dict[str, Any]: |
| 62 | + """ |
| 63 | + Convert the instance to a dictionary. |
| 64 | +
|
| 65 | + Returns: |
| 66 | + dict: A dictionary containing the instance's fields and their values. |
| 67 | + """ |
| 68 | + return dataclasses.asdict(self) |
| 69 | + |
| 70 | + |
| 71 | +def sphinx_ref_role(role, rawtext, text=None, lineno=None, inliner=None, options=None, content=None): |
| 72 | + options = normalized_role_options(options) |
| 73 | + text = nodes.unescape(text, True) # type: ignore[attr-defined] |
| 74 | + label = text.split(" ", 1)[0] |
| 75 | + node = nodes.raw(rawtext, label, **options) |
| 76 | + node.source, node.line = inliner.reporter.get_source_and_line(lineno) |
| 77 | + return [node], [] |
| 78 | + |
| 79 | + |
| 80 | +@dataclasses.dataclass |
| 81 | +class FunctionsExtractor(GenericProcessor): |
| 82 | + """ |
| 83 | + Extract CrateDB functions from documentation. |
| 84 | + Output in JSON, YAML, Markdown, or SQL format. |
| 85 | + """ |
| 86 | + |
| 87 | + registry: FunctionRegistry = dataclasses.field(default_factory=FunctionRegistry) |
| 88 | + thing: Dict[str, Dict[str, Any]] = dataclasses.field(default_factory=dict) |
| 89 | + payload: Optional[str] = None |
| 90 | + |
| 91 | + def acquire(self): |
| 92 | + """ |
| 93 | + Extract and register CrateDB functions from online documentation. |
| 94 | +
|
| 95 | + Fetch documentation from a defined URL, and process its content to extract functions grouped |
| 96 | + under categories. For each function section, it parses the title and description to create a |
| 97 | + Function instance, updates the registry with metadata such as creation time and generator info. |
| 98 | + If no functions are found, the method logs an error and terminates the program. The registry |
| 99 | + is then converted to a dictionary and stored in the instance attribute 'thing'. |
| 100 | +
|
| 101 | + Returns: |
| 102 | + FunctionsExtractor: The instance with an updated function registry. |
| 103 | + """ |
| 104 | + register_canonical_role("ref", sphinx_ref_role) |
| 105 | + register_directive("seealso", Note) |
| 106 | + document, pub = internals(requests.get(DOCS_URL, timeout=10).text) |
| 107 | + |
| 108 | + self.registry.meta["created"] = dt.datetime.now().isoformat() |
| 109 | + self.registry.meta["generator"] = "CrateDB Toolkit" |
| 110 | + |
| 111 | + item: docutils.nodes.Element |
| 112 | + function: docutils.nodes.Element |
| 113 | + for item in document: |
| 114 | + if item.tagname == "section": |
| 115 | + category_title = item.children[0].astext() |
| 116 | + for function in item.children: # type: ignore[assignment] |
| 117 | + if function.tagname == "section": |
| 118 | + function_title = function.children[0].astext() |
| 119 | + function_body = function.children[1].astext() |
| 120 | + fun = Function( |
| 121 | + name=function_title.split("(")[0], |
| 122 | + signature=function_title, |
| 123 | + category=category_title, |
| 124 | + description=function_body, |
| 125 | + ) |
| 126 | + self.registry.register(fun) |
| 127 | + |
| 128 | + if self.registry.functions: |
| 129 | + self.thing = self.registry.to_dict() |
| 130 | + else: |
| 131 | + logger.error("No functions were extracted. Please check the script or documentation structure.") |
| 132 | + return self |
0 commit comments