|
| 1 | +"""The CLI for numpydoc.""" |
| 2 | + |
| 3 | +import argparse |
| 4 | +import ast |
| 5 | +from pathlib import Path |
| 6 | +from typing import List, Sequence, Union |
| 7 | + |
| 8 | +from .docscrape_sphinx import get_doc_object |
| 9 | +from .hooks import utils, validate_docstrings |
| 10 | +from .validate import ERROR_MSGS, Validator, validate |
| 11 | + |
| 12 | + |
| 13 | +def render_object(import_path: str, config: Union[List[str], None] = None) -> int: |
| 14 | + """Test numpydoc docstring generation for a given object.""" |
| 15 | + # TODO: Move Validator._load_obj to a better place than validate |
| 16 | + print(get_doc_object(Validator._load_obj(import_path), config=dict(config or []))) |
| 17 | + return 0 |
| 18 | + |
| 19 | + |
| 20 | +def validate_object(import_path: str) -> int: |
| 21 | + """Run numpydoc docstring validation for a given object.""" |
| 22 | + exit_status = 0 |
| 23 | + results = validate(import_path) |
| 24 | + for err_code, err_desc in results["errors"]: |
| 25 | + exit_status += 1 |
| 26 | + print(":".join([import_path, err_code, err_desc])) |
| 27 | + return exit_status |
| 28 | + |
| 29 | + |
| 30 | +def get_parser() -> argparse.ArgumentParser: |
| 31 | + """ |
| 32 | + Build an argument parser. |
| 33 | +
|
| 34 | + Returns |
| 35 | + ------- |
| 36 | + argparse.ArgumentParser |
| 37 | + The argument parser. |
| 38 | + """ |
| 39 | + ap = argparse.ArgumentParser(prog="numpydoc", description=__doc__) |
| 40 | + subparsers = ap.add_subparsers(title="subcommands") |
| 41 | + |
| 42 | + def _parse_config(s): |
| 43 | + key, _, value = s.partition("=") |
| 44 | + value = ast.literal_eval(value) |
| 45 | + return key, value |
| 46 | + |
| 47 | + render = subparsers.add_parser( |
| 48 | + "render", |
| 49 | + description="Generate an expanded RST-version of the docstring.", |
| 50 | + help="generate the RST docstring with numpydoc", |
| 51 | + ) |
| 52 | + render.add_argument("import_path", help="e.g. numpy.ndarray") |
| 53 | + render.add_argument( |
| 54 | + "-c", |
| 55 | + "--config", |
| 56 | + type=_parse_config, |
| 57 | + action="append", |
| 58 | + help="key=val where val will be parsed by literal_eval, " |
| 59 | + "e.g. -c use_plots=True. Multiple -c can be used.", |
| 60 | + ) |
| 61 | + render.set_defaults(func=render_object) |
| 62 | + |
| 63 | + validate = subparsers.add_parser( |
| 64 | + "validate", |
| 65 | + description="Validate an object's docstring against the numpydoc standard.", |
| 66 | + help="validate the object's docstring and report errors", |
| 67 | + ) |
| 68 | + validate.add_argument("import_path", help="e.g. numpy.ndarray") |
| 69 | + validate.set_defaults(func=validate_object) |
| 70 | + |
| 71 | + project_root_from_cwd, config_file = utils.find_project_root(["."]) |
| 72 | + config_options = validate_docstrings.parse_config(project_root_from_cwd) |
| 73 | + ignored_checks = [ |
| 74 | + f"- {check}: {ERROR_MSGS[check]}" |
| 75 | + for check in set(ERROR_MSGS.keys()) - config_options["checks"] |
| 76 | + ] |
| 77 | + ignored_checks_text = "\n " + "\n ".join(ignored_checks) + "\n" |
| 78 | + |
| 79 | + lint_parser = subparsers.add_parser( |
| 80 | + "lint", |
| 81 | + description="Run numpydoc validation on files with option to ignore individual checks.", |
| 82 | + help="validate all docstrings in file(s) using the abstract syntax tree", |
| 83 | + formatter_class=argparse.RawTextHelpFormatter, |
| 84 | + ) |
| 85 | + lint_parser.add_argument( |
| 86 | + "files", type=str, nargs="+", help="File(s) to run numpydoc validation on." |
| 87 | + ) |
| 88 | + lint_parser.add_argument( |
| 89 | + "--config", |
| 90 | + type=str, |
| 91 | + help=( |
| 92 | + "Path to a directory containing a pyproject.toml or setup.cfg file.\n" |
| 93 | + "The hook will look for it in the root project directory.\n" |
| 94 | + "If both are present, only pyproject.toml will be used.\n" |
| 95 | + "Options must be placed under\n" |
| 96 | + " - [tool:numpydoc_validation] for setup.cfg files and\n" |
| 97 | + " - [tool.numpydoc_validation] for pyproject.toml files." |
| 98 | + ), |
| 99 | + ) |
| 100 | + lint_parser.add_argument( |
| 101 | + "--ignore", |
| 102 | + type=str, |
| 103 | + nargs="*", |
| 104 | + help=( |
| 105 | + f"""Check codes to ignore.{ |
| 106 | + ' Currently ignoring the following from ' |
| 107 | + f'{Path(project_root_from_cwd) / config_file}: {ignored_checks_text}' |
| 108 | + 'Values provided here will be in addition to the above, unless an alternate config is provided.' |
| 109 | + if ignored_checks else '' |
| 110 | + }""" |
| 111 | + ), |
| 112 | + ) |
| 113 | + lint_parser.set_defaults(func=validate_docstrings.run_hook) |
| 114 | + |
| 115 | + return ap |
| 116 | + |
| 117 | + |
| 118 | +def main(argv: Union[Sequence[str], None] = None) -> int: |
| 119 | + """CLI for numpydoc.""" |
| 120 | + ap = get_parser() |
| 121 | + |
| 122 | + args = vars(ap.parse_args(argv)) |
| 123 | + |
| 124 | + try: |
| 125 | + func = args.pop("func") |
| 126 | + return func(**args) |
| 127 | + except KeyError: |
| 128 | + ap.exit(status=2, message=ap.format_help()) |
0 commit comments