|
| 1 | +#!/usr/bin/env python |
| 2 | +"""A script that can be quickly run that explores the public API of Parcels |
| 3 | +and validates docstrings along the way according to the numpydoc conventions. |
| 4 | +
|
| 5 | +This script is a best attempt, and it meant as a first line of defence (compared |
| 6 | +to the sphinx numpydoc integration which is the ground truth - as those are the |
| 7 | +docstrings that end up in the documentation). |
| 8 | +""" |
| 9 | + |
| 10 | +import functools |
| 11 | +import importlib |
| 12 | +import logging |
| 13 | +import sys |
| 14 | +import tomllib |
| 15 | +import types |
| 16 | +from pathlib import Path |
| 17 | + |
| 18 | +from numpydoc.validate import validate |
| 19 | + |
| 20 | +logger = logging.getLogger("numpydoc-public-api") |
| 21 | +handler = logging.StreamHandler() |
| 22 | +handler.setFormatter(logging.Formatter("%(levelname)s: %(message)s")) |
| 23 | +logger.addHandler(handler) |
| 24 | + |
| 25 | +PROJECT_ROOT = (Path(__file__).parent / "..").resolve() |
| 26 | +PUBLIC_MODULES = ["parcels", "parcels.interpolators"] |
| 27 | +ROOT_PACKAGE = "parcels" |
| 28 | + |
| 29 | + |
| 30 | +def is_built_in(type_or_instance: type | object): |
| 31 | + if isinstance(type_or_instance, type): |
| 32 | + return type_or_instance.__module__ == "builtins" |
| 33 | + else: |
| 34 | + return type_or_instance.__class__.__module__ == "builtins" |
| 35 | + |
| 36 | + |
| 37 | +def walk_module(module_str: str, public_api: list[str] | None = None) -> list[str]: |
| 38 | + if public_api is None: |
| 39 | + public_api = [] |
| 40 | + |
| 41 | + module = importlib.import_module(module_str) |
| 42 | + try: |
| 43 | + all_ = module.__all__ |
| 44 | + except AttributeError: |
| 45 | + print(f"No __all__ variable found in public module {module_str!r}") |
| 46 | + return public_api |
| 47 | + |
| 48 | + if module_str not in public_api: |
| 49 | + public_api.append(module_str) |
| 50 | + for item_str in all_: |
| 51 | + item = getattr(module, item_str) |
| 52 | + if isinstance(item, types.ModuleType): |
| 53 | + walk_module(f"{module_str}.{item_str}", public_api) |
| 54 | + if isinstance(item, (types.FunctionType,)): |
| 55 | + public_api.append(f"{module_str}.{item_str}") |
| 56 | + elif is_built_in(item): |
| 57 | + print(f"Found builtin at '{module_str}.{item_str}' of type {type(item)}") |
| 58 | + continue |
| 59 | + elif isinstance(item, type): |
| 60 | + public_api.append(f"{module_str}.{item_str}") |
| 61 | + walk_class(module_str, item, public_api) |
| 62 | + else: |
| 63 | + logger.info( |
| 64 | + f"Encountered unexpected public object at '{module_str}.{item_str}' of {item!r} in public API. Don't know how to handle with numpydoc - ignoring." |
| 65 | + ) |
| 66 | + |
| 67 | + return public_api |
| 68 | + |
| 69 | + |
| 70 | +def get_public_class_attrs(class_: type) -> set[str]: |
| 71 | + return {a for a in dir(class_) if not a.startswith("_")} |
| 72 | + |
| 73 | + |
| 74 | +def walk_class(module_str: str, class_: type, public_api: list[str]) -> list[str]: |
| 75 | + class_str = class_.__name__ |
| 76 | + |
| 77 | + # attributes that were introduced by this class specifically - not from inheritance |
| 78 | + attrs = get_public_class_attrs(class_) - functools.reduce( |
| 79 | + set.add, (get_public_class_attrs(base) for base in class_.__bases__) |
| 80 | + ) |
| 81 | + |
| 82 | + public_api.extend([f"{module_str}.{class_str}.{attr_str}" for attr_str in attrs]) |
| 83 | + return public_api |
| 84 | + |
| 85 | + |
| 86 | +def main(): |
| 87 | + import argparse |
| 88 | + |
| 89 | + parser = argparse.ArgumentParser(description="Validate numpydoc docstrings in the public API") |
| 90 | + parser.add_argument("-v", "--verbose", action="count", default=0, help="Increase verbosity (can be repeated)") |
| 91 | + args = parser.parse_args() |
| 92 | + |
| 93 | + # Set logging level based on verbosity: 0=WARNING, 1=INFO, 2+=DEBUG |
| 94 | + if args.verbose == 0: |
| 95 | + log_level = logging.WARNING |
| 96 | + elif args.verbose == 1: |
| 97 | + log_level = logging.INFO |
| 98 | + else: |
| 99 | + log_level = logging.DEBUG |
| 100 | + |
| 101 | + logger.setLevel(log_level) |
| 102 | + |
| 103 | + with open(PROJECT_ROOT / "tools/tool-data.toml", "rb") as f: |
| 104 | + skip_errors = tomllib.load(f)["numpydoc_skip_errors"] |
| 105 | + public_api = [] |
| 106 | + for module in PUBLIC_MODULES: |
| 107 | + public_api += walk_module(module) |
| 108 | + |
| 109 | + errors = 0 |
| 110 | + for item in public_api: |
| 111 | + logger.info(f"Processing validating {item}") |
| 112 | + try: |
| 113 | + res = validate(item) |
| 114 | + except (AttributeError, StopIteration) as e: |
| 115 | + logger.warning(f"Could not process {item!r}. Encountered error. {e!r}") |
| 116 | + continue |
| 117 | + if res["type"] in ("module", "float", "int", "dict"): |
| 118 | + continue |
| 119 | + for err in res["errors"]: |
| 120 | + if err[0] not in skip_errors: |
| 121 | + print(f"{item}: {err}") |
| 122 | + errors += 1 |
| 123 | + sys.exit(errors) |
| 124 | + |
| 125 | + |
| 126 | +if __name__ == "__main__": |
| 127 | + main() |
0 commit comments