Debian Codegraph @

src/rstcheck/_cli.py

raw symbols SCIP
1 """CLI for rstcheck."""
2
3 from __future__ import annotations
4
5 import logging
6 import pathlib
7 import typing as t
8 from importlib.metadata import version
9
10 import typer
11 from rstcheck_core import _extras, config as config_mod, runner
12
13 HELP_CONFIG = """Config file to load. Can be a INI file or directory.
14 If a directory is passed it will be searched for .rstcheck.cfg | setup.cfg.
15 If 'NONE' is passed no config file is loaded at all.
16 """
17 if _extras.TOMLI_INSTALLED: # pragma: no cover
18 HELP_CONFIG = """Config file to load. Can be a INI or TOML file or directory.
19 If a directory is passed it will be searched for .rstcheck.cfg | pyproject.toml | setup.cfg.
20 If 'NONE' is passed no config file is loaded at all.
21 """
22 HELP_WARN_UNKNOWN_SETTINGS = """Log a WARNING for unknown settings in config files.
23 Can be hidden via --log-level."""
24 HELP_RECURSIVE = "Recursively search passed directories for RST files to check."
25 HELP_REPORT_LEVEL = f"""The report level of the linting issues found.
26 Valid levels are: INFO | WARNING | ERROR | SEVERE | NONE.
27 Defaults to {config_mod.DEFAULT_REPORT_LEVEL.name}.
28 Can be set in config file.
29 """
30 HELP_LOG_LEVEL = """The log level of the application for information that is not a linting issue.
31 Valid levels are: DEBUG | INFO | WARNING | ERROR | CRITICAL.
32 Defaults to WARNING.
33 """
34 HELP_IGNORE_DIRECTIVES = """Comma-separated-list of directives to add to the ignore list.
35 Can be set in config file.
36 """
37 HELP_IGNORE_ROLES = """Comma-separated-list of roles to add to the ignore list.
38 Can be set in config file.
39 """
40 HELP_IGNORE_SUBSTITUTIONS = """Comma-separated-list of substitutions to add to the ignore list.
41 Can be set in config file.
42 """
43 HELP_IGNORE_LANGUAGES = """Comma-separated-list of languages for code-blocks to add to the ignore
44 list. The code in ignored code-blocks will not be checked for errors.
45 Can be set in config file.
46 """
47 HELP_IGNORE_MESSAGES = """A regular expression to match linting issue messages against to ignore.
48 Can be set in config file.
49 """
50 HELP_VERSION = "Print versions and exit."
51
52
53 def setup_logger(loglevel: str) -> None:
54 """Set up logging.
55
56 :param loglevel: Level to log at.
57 :raises TypeError: On invalid logging levels.
58 """
59 numeric_level = getattr(logging, loglevel.upper(), None)
60 if not isinstance(numeric_level, int):
61 msg = f"Invalid log level: {loglevel}"
62 raise TypeError(msg)
63
64 logging.basicConfig(level=numeric_level)
65
66
67 def version_callback(value: bool) -> None: # noqa: FBT001
68 """Print the version and exit."""
69 if value:
70 typer.echo(f"rstcheck CLI Version: {version('rstcheck')}")
71 typer.echo(f"rstcheck-core Version: {version('rstcheck-core')}")
72 raise typer.Exit
73
74
75 def cli( # noqa: PLR0913
76 files: t.List[pathlib.Path] = typer.Argument(..., allow_dash=True, hidden=True), # noqa: UP006
77 config: t.Optional[pathlib.Path] = typer.Option( # noqa: UP007
78 None, "--config", help=HELP_CONFIG
79 ),
80 warn_unknown_settings: t.Optional[bool] = typer.Option( # noqa: UP007
81 None, "--warn-unknown-settings", help=HELP_WARN_UNKNOWN_SETTINGS
82 ),
83 recursive: t.Optional[bool] = typer.Option( # noqa: UP007
84 None, "--recursive", "-r", help=HELP_RECURSIVE
85 ),
86 report_level: t.Optional[str] = typer.Option( # noqa: UP007
87 None, metavar="LEVEL", help=HELP_REPORT_LEVEL
88 ),
89 # TODO: #i# use `t.Literal["INFO", "WARNING", "ERROR", "SEVERE", "NONE"]` when supported
90 log_level: str = typer.Option("WARNING", metavar="LEVEL", help=HELP_LOG_LEVEL),
91 ignore_directives: t.Optional[str] = typer.Option( # noqa: UP007
92 None, help=HELP_IGNORE_DIRECTIVES
93 ),
94 ignore_roles: t.Optional[str] = typer.Option(None, help=HELP_IGNORE_ROLES), # noqa: UP007
95 ignore_substitutions: t.Optional[str] = typer.Option( # noqa: UP007
96 None, help=HELP_IGNORE_SUBSTITUTIONS
97 ),
98 ignore_languages: t.Optional[str] = typer.Option( # noqa: UP007
99 None, help=HELP_IGNORE_LANGUAGES
100 ),
101 ignore_messages: t.Optional[str] = typer.Option( # noqa: UP007
102 None, metavar="REGEX", help=HELP_IGNORE_MESSAGES
103 ),
104 version: t.Optional[bool] = typer.Option( # noqa: ARG001, UP007
105 None, "--version", callback=version_callback, is_eager=True, help=HELP_VERSION
106 ),
107 ) -> None:
108 """CLI of rstcheck."""
109 setup_logger(log_level)
110 logger = logging.getLogger(__name__)
111
112 if pathlib.Path("-") in files and len(files) > 1:
113 typer.echo("'-' is only allowed without additional files.", err=True)
114 raise typer.Abort
115
116 logger.info("Create main configuration from CLI options.")
117 rstcheck_config = config_mod.RstcheckConfig(
118 config_path=config,
119 warn_unknown_settings=warn_unknown_settings,
120 recursive=recursive,
121 report_level=report_level,
122 ignore_directives=ignore_directives,
123 ignore_roles=ignore_roles,
124 ignore_substitutions=ignore_substitutions,
125 ignore_languages=ignore_languages,
126 ignore_messages=ignore_messages,
127 )
128
129 exit_code = 1
130
131 try:
132 logger.debug("Create main runner instance.")
133 _runner = runner.RstcheckMainRunner(
134 check_paths=files, rstcheck_config=rstcheck_config, overwrite_config=False
135 )
136 logger.info("Run main runner instance.")
137 _runner.check()
138 exit_code = _runner.print_result()
139
140 except FileNotFoundError as exc:
141 if exc.strerror == "Passed config path not found.": # pragma: no cover
142 logger.critical("Passed config path was not found: '%(path)s'", {"path": exc.filename})
143 raise typer.Exit(code=1) from None
144
145 raise
146
147 raise typer.Exit(code=exit_code)
148
149
150 enabled_features = []
151 if _extras.SPHINX_INSTALLED:
152 enabled_features.append("Sphinx")
153 if _extras.TOMLI_INSTALLED: # pragma: no cover
154 enabled_features.append("Toml")
155
156 cli.__doc__ = f"""CLI of rstcheck.
157
158 Enabled features: {enabled_features}
159
160 Pass one or more RST FILES to check.
161 Can be files or directories if --recursive is passed too.
162 Pass "-" if you want to read from stdin.
163 """
164
165
166 app = typer.Typer()
167 app.command()(cli)
168 typer_click_object = typer.main.get_command(app)
169
170
171 def main() -> None: # pragma: no cover
172 """Run CLI."""
173 typer.run(cli)
174
175
176 if __name__ == "__main__":
177 main()