| 1 |
"""Runner of rstcheck_core.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import logging |
| 6 |
import multiprocessing |
| 7 |
import os |
| 8 |
import pathlib |
| 9 |
import re |
| 10 |
import sys |
| 11 |
import typing as t |
| 12 |
|
| 13 |
from . import _sphinx, checker, config, types |
| 14 |
|
| 15 |
logger = logging.getLogger(__name__) |
| 16 |
|
| 17 |
|
| 18 |
class RstcheckMainRunner: |
| 19 |
"""Main runner of rstcheck_core.""" |
| 20 |
|
| 21 |
def __init__( |
| 22 |
self, |
| 23 |
check_paths: list[pathlib.Path], |
| 24 |
rstcheck_config: config.RstcheckConfig, |
| 25 |
*, |
| 26 |
overwrite_config: bool = True, |
| 27 |
) -> None: |
| 28 |
"""Initialize the :py:class:`RstcheckMainRunner` with a base config. |
| 29 |
|
| 30 |
:param check_paths: Files to check. |
| 31 |
:param rstcheck_config: Base configuration config from e.g. the CLI. |
| 32 |
:param overwrite_config: If file config overwrites current config; defaults to True |
| 33 |
""" |
| 34 |
self.config = rstcheck_config |
| 35 |
self.overwrite_config = overwrite_config |
| 36 |
if rstcheck_config.config_path: |
| 37 |
self.load_config_file( |
| 38 |
rstcheck_config.config_path, |
| 39 |
warn_unknown_settings=rstcheck_config.warn_unknown_settings or False, |
| 40 |
) |
| 41 |
|
| 42 |
self.check_paths = check_paths |
| 43 |
self._files_to_check: list[pathlib.Path] = [] |
| 44 |
self._nonexisting_paths: list[pathlib.Path] = [] |
| 45 |
self.update_file_list() |
| 46 |
|
| 47 |
pool_size = multiprocessing.cpu_count() |
| 48 |
|
| 49 |
self._pool_size = pool_size if sys.platform != "win32" else min(pool_size, 61) |
| 50 |
|
| 51 |
self.errors: list[types.LintError] = [] |
| 52 |
|
| 53 |
@property |
| 54 |
def files_to_check(self) -> list[pathlib.Path]: |
| 55 |
"""List of files to check. |
| 56 |
|
| 57 |
This list is updated via the :py:meth:`RstcheckMainRunner.update_file_list` method. |
| 58 |
""" |
| 59 |
return self._files_to_check |
| 60 |
|
| 61 |
@property |
| 62 |
def nonexisting_paths(self) -> list[pathlib.Path]: |
| 63 |
"""List of paths which do not exist. |
| 64 |
|
| 65 |
This list is updated via the :py:meth:`RstcheckMainRunner.update_file_list` method. |
| 66 |
""" |
| 67 |
return self._nonexisting_paths |
| 68 |
|
| 69 |
def load_config_file( |
| 70 |
self, config_path: pathlib.Path, *, warn_unknown_settings: bool = False |
| 71 |
) -> None: |
| 72 |
"""Load config from file and merge with current config. |
| 73 |
|
| 74 |
If the loaded file config overwrites the current config depends on the |
| 75 |
``self.overwrite_config`` attribute set on initialization. |
| 76 |
|
| 77 |
:param config_path: Path to config file; can be directory or file |
| 78 |
:param warn_unknown_settings: If a warning should be logged for unknown settings in config |
| 79 |
file; |
| 80 |
defaults to :py:obj:`False` |
| 81 |
""" |
| 82 |
logger.info("Load config file for main runner: '%s'.", config_path) |
| 83 |
file_config = config.load_config_file_from_path( |
| 84 |
config_path, warn_unknown_settings=warn_unknown_settings |
| 85 |
) |
| 86 |
|
| 87 |
if file_config is None: |
| 88 |
logger.warning("Config file was empty or not found.") |
| 89 |
return |
| 90 |
|
| 91 |
logger.debug( |
| 92 |
"Merging config from file into main config. File config is dominant: %s", |
| 93 |
self.overwrite_config, |
| 94 |
) |
| 95 |
self.config = config.merge_configs( |
| 96 |
self.config, file_config, config_add_is_dominant=self.overwrite_config |
| 97 |
) |
| 98 |
|
| 99 |
def update_file_list(self) -> None: |
| 100 |
"""Update file path list with paths specified on initialization. |
| 101 |
|
| 102 |
Uses paths from ``RstcheckMainRunner.check_paths``, resolves all file paths and |
| 103 |
saves them in :py:attr:`RstcheckMainRunner.files_to_check`. |
| 104 |
|
| 105 |
If a given path does not exist, it is filtered out and saved in |
| 106 |
:py:attr:`RstcheckMainRunner.files_to_check`. |
| 107 |
|
| 108 |
Clear the current file list. Then get the file and directory paths specified with |
| 109 |
``self.check_paths`` attribute set on initialization and search them for rst files |
| 110 |
to check. Add those files to the file list. |
| 111 |
""" |
| 112 |
logger.debug("Updating list of files to check.") |
| 113 |
paths = list(self.check_paths) |
| 114 |
self._files_to_check = [] |
| 115 |
|
| 116 |
if len(paths) == 1 and paths[0].name == "-": |
| 117 |
logger.info("'-' detected. Using stdin for input.'") |
| 118 |
self._files_to_check.append(paths[0]) |
| 119 |
return |
| 120 |
|
| 121 |
paths = self._filter_nonexisting_paths(paths) |
| 122 |
|
| 123 |
def checkable_rst_file(f: pathlib.Path) -> bool: |
| 124 |
return f.is_file() and not f.name.startswith(".") and f.suffix.casefold() == ".rst" |
| 125 |
|
| 126 |
while paths: |
| 127 |
path = paths.pop(0) |
| 128 |
resolved_path = path.resolve() |
| 129 |
if self.config.recursive and resolved_path.is_dir(): |
| 130 |
for root, directories, children in os.walk(path): |
| 131 |
root_path = pathlib.Path(root) |
| 132 |
paths += [ |
| 133 |
root_path / f |
| 134 |
for f in children |
| 135 |
if checkable_rst_file((root_path / f).resolve()) |
| 136 |
] |
| 137 |
directories[:] = [d for d in directories if not d.startswith(".")] |
| 138 |
continue |
| 139 |
|
| 140 |
if checkable_rst_file(resolved_path): |
| 141 |
self._files_to_check.append(path) |
| 142 |
|
| 143 |
def _filter_nonexisting_paths(self, paths: list[pathlib.Path]) -> list[pathlib.Path]: |
| 144 |
"""Filter nonexisting paths out. |
| 145 |
|
| 146 |
If recursive is not active only files are allowed, else directories are also allowed. |
| 147 |
|
| 148 |
:param paths: List of paths to filter |
| 149 |
:return: Filtered path list |
| 150 |
""" |
| 151 |
self._nonexisting_paths = [] |
| 152 |
_paths = list(paths) |
| 153 |
|
| 154 |
for path in _paths: |
| 155 |
resolved_path = path.resolve() |
| 156 |
|
| 157 |
if resolved_path.is_file(): |
| 158 |
continue |
| 159 |
|
| 160 |
if self.config.recursive and resolved_path.is_dir(): |
| 161 |
continue |
| 162 |
|
| 163 |
_paths.remove(path) |
| 164 |
self._nonexisting_paths.append(path) |
| 165 |
|
| 166 |
if self.config.recursive: |
| 167 |
logger.warning( |
| 168 |
"Path does not exist or is neither a file nor a directory: '%s'.", |
| 169 |
path, |
| 170 |
) |
| 171 |
continue |
| 172 |
|
| 173 |
logger.warning( |
| 174 |
"Path does not exist or is not a file: '%s'.", |
| 175 |
path, |
| 176 |
) |
| 177 |
|
| 178 |
return _paths |
| 179 |
|
| 180 |
def _run_checks_sync(self) -> list[list[types.LintError]]: |
| 181 |
"""Check all files from the file list syncronously and return the errors. |
| 182 |
|
| 183 |
:return: List of lists of errors found per file |
| 184 |
""" |
| 185 |
logger.debug("Runnning checks synchronically.") |
| 186 |
with _sphinx.load_sphinx_if_available(): |
| 187 |
return [ |
| 188 |
checker.check_file(file, self.config, self.overwrite_config) |
| 189 |
for file in self._files_to_check |
| 190 |
] |
| 191 |
|
| 192 |
def _run_checks_parallel(self) -> list[list[types.LintError]]: |
| 193 |
"""Check all files from the file list in parallel and return the errors. |
| 194 |
|
| 195 |
:return: List of lists of errors found per file |
| 196 |
""" |
| 197 |
logger.debug( |
| 198 |
"Runnning checks in parallel with pool size of %s.", |
| 199 |
self._pool_size, |
| 200 |
) |
| 201 |
with _sphinx.load_sphinx_if_available(), multiprocessing.Pool(self._pool_size) as pool: |
| 202 |
return pool.starmap( |
| 203 |
checker.check_file, |
| 204 |
[(file, self.config, self.overwrite_config) for file in self._files_to_check], |
| 205 |
) |
| 206 |
|
| 207 |
def _update_results(self, results: list[list[types.LintError]]) -> None: |
| 208 |
"""Take results and update error cache. |
| 209 |
|
| 210 |
Result normally come from :py:meth:`RstcheckMainRunner._run_checks_sync` or |
| 211 |
:py:meth:`RstcheckMainRunner._run_checks_parallel`. |
| 212 |
:param results: List of lists of errors found |
| 213 |
""" |
| 214 |
self.errors = [] |
| 215 |
for errors in results: |
| 216 |
self.errors += errors |
| 217 |
|
| 218 |
def check(self) -> None: |
| 219 |
"""Check all files in the file list and save the errors. |
| 220 |
|
| 221 |
Multiple files are run in parallel. |
| 222 |
|
| 223 |
A new call overwrite the old cached errors. |
| 224 |
""" |
| 225 |
logger.info("Run checks for all files.") |
| 226 |
results = ( |
| 227 |
self._run_checks_parallel() |
| 228 |
if len(self._files_to_check) > 1 |
| 229 |
else self._run_checks_sync() |
| 230 |
) |
| 231 |
self._update_results(results) |
| 232 |
|
| 233 |
def print_result(self, output_file: t.TextIO | None = None) -> int: |
| 234 |
"""Print all cached error messages and return exit code. |
| 235 |
|
| 236 |
:param output_file: file to print to; defaults to sys.stderr (if ``None``) |
| 237 |
:return: exit code 0 if no error is printed; 1 if any error is printed |
| 238 |
""" |
| 239 |
if len(self.errors) == 0 and len(self._nonexisting_paths) == 0: |
| 240 |
print("Success! No issues detected.", file=output_file or sys.stdout) |
| 241 |
return 0 |
| 242 |
|
| 243 |
err_msg_regex = re.compile(r"\([A-Z]+/[0-9]+\)") |
| 244 |
|
| 245 |
for error in self.errors: |
| 246 |
err_msg = error["message"] |
| 247 |
if not err_msg_regex.match(err_msg): |
| 248 |
err_msg = "(ERROR/3) " + err_msg |
| 249 |
|
| 250 |
message = f"{error['source_origin']}:{error['line_number']}: {err_msg}" |
| 251 |
|
| 252 |
print(message, file=output_file or sys.stderr) |
| 253 |
|
| 254 |
print("Error! Issues detected.", file=output_file or sys.stderr) |
| 255 |
return 1 |
| 256 |
|
| 257 |
def run(self) -> int: |
| 258 |
"""Run checks, print error messages and return the result. |
| 259 |
|
| 260 |
:return: exit code 0 if no error is printed; 1 if any error is printed |
| 261 |
""" |
| 262 |
logger.info("Run checks and print results.") |
| 263 |
self.check() |
| 264 |
return self.print_result() |