Debian Codegraph @

core/src/rstcheck_core/checker.py

raw symbols SCIP
1 """Checking functionality."""
2
3 from __future__ import annotations
4
5 import contextlib
6 import copy
7 import doctest
8 import io
9 import json
10 import locale
11 import logging
12 import os
13 import pathlib
14 import re
15 import shlex
16 import subprocess
17 import sys
18 import tempfile
19 import typing as t
20 import warnings
21 import xml.etree.ElementTree
22
23 import docutils.core
24 import docutils.io
25 import docutils.nodes
26 import docutils.utils
27
28 from . import _docutils, _extras, _sphinx, config, inline_config, types
29
30 try:
31 import yaml
32
33 yaml_imported = True
34 except ImportError:
35 yaml_imported = False
36
37
38 logger = logging.getLogger(__name__)
39
40
41 EXCEPTION_LINE_NO_REGEX = re.compile(r": line\s+([0-9]+)[^:]*$")
42 DOCTEST_LINE_NO_REGEX = re.compile(r"line ([0-9]+)")
43 MARKDOWN_LINK_REGEX = re.compile(r"\[[^\]]+\]\([^\)]+\)")
44
45
46 def check_file(
47 source_file: pathlib.Path,
48 rstcheck_config: config.RstcheckConfig,
49 overwrite_with_file_config: bool = True, # noqa: FBT001,FBT002
50 ) -> list[types.LintError]:
51 """Check the given file for issues.
52
53 On every call docutils' caches for roles and directives are cleared by reloading their modules.
54
55 :param source_file: Path to file to check
56 :param rstcheck_config: Main configuration of the application
57 :param overwrite_with_file_config: If the loaded file config should overwrite the
58 ``rstcheck_config``;
59 defaults to :py:obj:`True`
60 :return: A list of found issues
61 """
62 logger.info("Check file'%s'", source_file)
63 run_config = _load_run_config(
64 source_file.parent, rstcheck_config, overwrite_config=overwrite_with_file_config
65 )
66 ignore_dict = _create_ignore_dict_from_config(run_config)
67
68 source = _get_source(source_file)
69
70 _docutils.clean_docutils_directives_and_roles_cache()
71
72 with _sphinx.load_sphinx_if_available():
73 return list(
74 check_source(
75 source,
76 source_file=source_file,
77 ignores=ignore_dict,
78 report_level=run_config.report_level or config.DEFAULT_REPORT_LEVEL,
79 warn_unknown_settings=run_config.warn_unknown_settings or False,
80 )
81 )
82
83
84 def _load_run_config(
85 source_file_dir: pathlib.Path,
86 rstcheck_config: config.RstcheckConfig,
87 *,
88 overwrite_config: bool = True,
89 ) -> config.RstcheckConfig:
90 """Load file specific config file and create run config.
91
92 If the ``rstcheck_config`` does not contain a ``config_path`` the ``source_file_dir`` directory
93 tree is searched for a config file to load and merge into the ``rstcheck_config``. The merge
94 strategy is set via ``overwrite_config``.
95
96 :param source_file_dir: Directory of the current file to check
97 :param rstcheck_config: Main configuration of the application
98 :param overwrite_config: If the loaded config should overwrite the ``rstcheck_config``;
99 defaults to :py:obj:`True`
100 :return: Merged config
101 """
102 if rstcheck_config.config_path is not None:
103 return rstcheck_config
104
105 file_config = config.load_config_file_from_dir_tree(source_file_dir)
106
107 if file_config is None:
108 return rstcheck_config
109
110 return config.merge_configs(
111 copy.copy(rstcheck_config), file_config, config_add_is_dominant=overwrite_config
112 )
113
114
115 def _get_source(source_file: pathlib.Path) -> str:
116 """Get source from file or stdin.
117
118 If the file name is "-" then stdin is read for input instead of a file.
119
120 :param source_file: File path to read contents from
121 :return: Loaded content
122 """
123 if source_file.name == "-":
124 logger.info("Load source from stdin.")
125 return sys.stdin.read()
126
127 resolved_file_path = source_file.resolve()
128 with contextlib.closing(docutils.io.FileInput(source_path=resolved_file_path)) as input_file:
129 return input_file.read()
130
131
132 def _replace_ignored_substitutions(source: str, ignore_substitutions: list[str]) -> str:
133 """Replace rst substitutions from the ignore list with a dummy.
134
135 :param source: Source to replace substitutions in
136 :param ignore_substitutions: Substitutions to replace with dummy
137 :return: Cleaned source
138 """
139 for substitution in ignore_substitutions:
140 source = source.replace(f"|{substitution}|", f"x{substitution}x")
141 return source
142
143
144 def _create_ignore_dict_from_config(rstcheck_config: config.RstcheckConfig) -> types.IgnoreDict:
145 """Extract ignore settings from config and create a :py:class:`rstcheck_core.types.IgnoreDict`.
146
147 :param rstcheck_config: Config to extract ignore settings from
148 :return: :py:class:`rstcheck_core.types.IgnoreDict`
149 """
150 return types.construct_ignore_dict(
151 messages=rstcheck_config.ignore_messages,
152 languages=rstcheck_config.ignore_languages,
153 directives=rstcheck_config.ignore_directives,
154 roles=rstcheck_config.ignore_roles,
155 substitutions=rstcheck_config.ignore_substitutions,
156 )
157
158
159 def check_source(
160 source: str,
161 source_file: types.SourceFileOrString | None = None,
162 ignores: types.IgnoreDict | None = None,
163 report_level: config.ReportLevel = config.DEFAULT_REPORT_LEVEL,
164 *,
165 warn_unknown_settings: bool = False,
166 ) -> types.YieldedLintError:
167 """Check the given rst source for issues.
168
169 :param source_file: Path to file the source comes from if it comes from a file;
170 defaults to :py:obj:`None`
171 :param ignores: Ignore information; defaults to :py:obj:`None`
172 :param report_level: Report level; defaults to
173 :py:data:`rstcheck_core.config.DEFAULT_REPORT_LEVEL`
174 :param warn_unknown_settings: If a warning should be logged for unknown settings in config file;
175 defaults to :py:obj:`False`
176 :return: :py:obj:`None`
177 :yield: Found issues
178 """
179 source_origin: types.SourceFileOrString = source_file or "<string>"
180 if isinstance(source_origin, pathlib.Path) and source_origin.name == "-":
181 source_origin = "<stdin>"
182 logger.info("Check source from '%s'", source_origin)
183 ignores = ignores or types.construct_ignore_dict()
184 ignores["directives"].extend(
185 inline_config.find_ignored_directives(
186 source, source_origin, warn_unknown_settings=warn_unknown_settings
187 )
188 )
189 ignores["roles"].extend(
190 inline_config.find_ignored_roles(
191 source, source_origin, warn_unknown_settings=warn_unknown_settings
192 )
193 )
194 ignores["substitutions"].extend(
195 inline_config.find_ignored_substitutions(
196 source, source_origin, warn_unknown_settings=warn_unknown_settings
197 )
198 )
199 ignores["languages"].extend(
200 inline_config.find_ignored_languages(
201 source, source_origin, warn_unknown_settings=warn_unknown_settings
202 )
203 )
204
205 source = _replace_ignored_substitutions(source, ignores["substitutions"])
206
207 _docutils.register_code_directive(
208 ignore_code_directive="code" in ignores["directives"],
209 ignore_codeblock_directive="code-block" in ignores["directives"],
210 ignore_sourcecode_directive="sourcecode" in ignores["directives"],
211 )
212
213 _docutils.ignore_directives_and_roles(ignores["directives"] or [], ignores["roles"] or [])
214
215 if _extras.SPHINX_INSTALLED:
216 _sphinx.load_sphinx_ignores()
217
218 writer = _CheckWriter(source, source_origin, ignores, report_level)
219
220 string_io = io.StringIO()
221
222 # This is a hack to avoid false positive from docutils (#23). docutils mistakes BOMs for actual
223 # visible letters. This results in the "underline too short" warning firing.
224 # This is tested in the CLI integration tests with the `testing/examples/good/bom.rst` file.
225 with contextlib.suppress(UnicodeError):
226 source = source.encode("utf-8").decode("utf-8-sig")
227
228 with contextlib.suppress(docutils.utils.SystemMessage):
229 # Sphinx will sometimes throw an `AttributeError` trying to access
230 # "self.state.document.settings.env". Ignore this for now until we
231 # figure out a better approach.
232 # https://github.com/rstcheck/rstcheck-core/issues/3
233 try:
234 docutils.core.publish_string(
235 source,
236 writer=writer,
237 source_path=str(source_origin),
238 settings_overrides={
239 "halt_level": 5,
240 "report_level": report_level.value,
241 "warning_stream": string_io,
242 },
243 )
244 except AttributeError:
245 if not _extras.SPHINX_INSTALLED:
246 raise
247 logger.warning(
248 "An `AttributeError` error occured. This is most probably due to a code block "
249 "directive (code/code-block/sourcecode) without a specified language. "
250 "This may result in a false negative for source: '%s'. "
251 "The reason can also be another directive. "
252 "For more information see the FAQ (https://rstcheck-core.rtfd.io/en/latest/faq) "
253 "or the corresponding github issue: "
254 "https://github.com/rstcheck/rstcheck-core/issues/3.",
255 source_origin,
256 )
257
258 yield from _run_code_checker_and_filter_errors(writer.checkers, ignores["messages"])
259
260 rst_errors = string_io.getvalue().strip()
261
262 if not rst_errors:
263 return
264
265 yield from _parse_and_filter_rst_errors(rst_errors, source_origin, ignores["messages"])
266
267
268 def _run_code_checker_and_filter_errors(
269 checker_list: list[types.CheckerRunFunction],
270 ignore_messages: t.Pattern[str] | None = None,
271 ) -> types.YieldedLintError:
272 """Run all code block checker functions.
273
274 :param checker_list: List of code block checker functions
275 :param ignore_messages: Regex for ignoring error messages;
276 defaults to :py:obj:`None`
277 :return: :py:obj:`None`
278 :yield: Filtered :py:class:`rstcheck_core.types.LintError` s from run checker function
279 """
280 for checker in checker_list:
281 for lint_error in checker():
282 if ignore_messages and ignore_messages.search(lint_error["message"]):
283 continue
284 yield lint_error
285
286
287 def _parse_and_filter_rst_errors(
288 rst_errors: str,
289 source_origin: types.SourceFileOrString,
290 ignore_messages: t.Pattern[str] | None = None,
291 ) -> types.YieldedLintError:
292 """Parse rst errors and yield filtered :py:class:`rstcheck_core.types.LintError`.
293
294 :param rst_errors: String with rst errors
295 :param source_origin: Origin of the source with the errors
296 :param ignore_messages: Regex for ignoring error messages;
297 defaults to :py:obj:`None`
298 :return: :py:obj:`None`
299 :yield: Parsed and filtered :py:class:`rstcheck_core.types.LintError` s
300 """
301 for message in rst_errors.splitlines():
302 with contextlib.suppress(ValueError):
303 if ignore_messages and ignore_messages.search(message):
304 continue
305 yield _parse_gcc_style_error_message(
306 message, source_origin=source_origin, has_column=False
307 )
308
309
310 class _CheckWriter(docutils.writers.Writer):
311 """Runs CheckTranslator on code blocks."""
312
313 def __init__(
314 self,
315 source: str,
316 source_origin: types.SourceFileOrString,
317 ignores: types.IgnoreDict | None = None,
318 report_level: config.ReportLevel = config.DEFAULT_REPORT_LEVEL,
319 *,
320 warn_unknown_settings: bool = False,
321 ) -> None:
322 """Inititalize :py:class:`_CheckWriter`.
323
324 :param source: Rst source to check
325 :param source_origin: Path to file the source comes from
326 :param ignores: Ignore information; defaults to :py:obj:`None`
327 :param report_level: Report level;
328 defaults to :py:data:`rstcheck_core.config.DEFAULT_REPORT_LEVEL`
329 :param warn_unknown_settings: If a warning should be logged for unknown settings in config
330 file;
331 defaults to :py:obj:`False`
332 """
333 docutils.writers.Writer.__init__(self)
334 self.checkers: list[types.CheckerRunFunction] = []
335 self.source = source
336 self.source_origin = source_origin
337 self.ignores = ignores
338 self.report_level = report_level
339 self.warn_unknown_settings = warn_unknown_settings
340
341 def translate(self) -> None:
342 """Run CheckTranslator."""
343 visitor = _CheckTranslator(
344 self.document,
345 source=self.source,
346 source_origin=self.source_origin,
347 ignores=self.ignores,
348 report_level=self.report_level,
349 warn_unknown_settings=self.warn_unknown_settings,
350 )
351 self.document.walkabout(visitor)
352 self.checkers += visitor.checkers
353
354
355 class _CheckTranslator(docutils.nodes.NodeVisitor):
356 """Visits code blocks and checks for syntax errors in code."""
357
358 def __init__( # noqa: PLR0913
359 self,
360 document: docutils.nodes.document,
361 source: str,
362 source_origin: types.SourceFileOrString,
363 ignores: types.IgnoreDict | None = None,
364 report_level: config.ReportLevel = config.DEFAULT_REPORT_LEVEL,
365 *,
366 warn_unknown_settings: bool = False,
367 ) -> None:
368 """Inititalize :py:class:`_CheckTranslator`.
369
370 :param document: Document node
371 :param source: Rst source to check
372 :param source_origin: Path to file the source comes from
373 :param ignores: Ignore information; defaults to :py:obj:`None`
374 :param report_level: Report level;
375 defaults to :py:data:`rstcheck_core.config.DEFAULT_REPORT_LEVEL`
376 :param warn_unknown_settings: If a warning should be logged for unknown settings in config
377 file;
378 defaults to :py:obj:`False`
379 """
380 docutils.nodes.NodeVisitor.__init__(self, document)
381 self.checkers: list[types.CheckerRunFunction] = []
382 self.source = source
383 self.source_origin = source_origin
384 self.ignores = ignores or types.construct_ignore_dict()
385 self.report_level = report_level
386 self.warn_unknown_settings = warn_unknown_settings
387 self.code_block_checker = CodeBlockChecker(
388 source_origin, ignores, report_level, warn_unknown_settings=warn_unknown_settings
389 )
390 self.code_block_ignore_lines = list(
391 inline_config.find_code_block_ignore_lines(
392 source=self.source,
393 source_origin=self.source_origin,
394 warn_unknown_settings=self.warn_unknown_settings,
395 )
396 )
397
398 def visit_doctest_block(self, node: docutils.nodes.Element) -> None:
399 """Add check for syntax of doctest.
400
401 :param node: The doctest node
402 """
403 if "doctest" in self.ignores["languages"]:
404 return
405
406 self._add_check(
407 node=node,
408 run=self.code_block_checker.create_checker(node.rawsource, "doctest"),
409 language="doctest",
410 is_code_node=False,
411 )
412
413 def visit_literal_block(self, node: docutils.nodes.Element) -> None:
414 """Add check for syntax of code block.
415
416 :param node: The code block node
417 :raises docutils.nodes.SkipNode: After a check was added or nothing to do
418 """
419 # For "..code-block:: language"
420 language = node.get("language")
421 is_code_node = False
422 if not language:
423 # For "..code:: language"
424 is_code_node = True
425 classes = node.get("classes")
426 if "code" not in classes:
427 return
428 language = classes[-1]
429
430 directive_line = _get_code_block_directive_line(node, self.source)
431 if directive_line is None:
432 logger.warning(
433 "Could not find line for literal block directive. "
434 "This could be due to an indented code block. "
435 "This message only warns about the missing line number "
436 "and is no error of itself. "
437 "Source: '%s'%s",
438 self.source_origin,
439 f" at line {node.line}" if node.line is not None else "",
440 )
441 return
442
443 if directive_line - 1 in self.code_block_ignore_lines:
444 logger.debug(
445 "Skipping code-block due to skip comment. Source: '%s' at line %s",
446 self.source_origin,
447 node.line,
448 )
449 return
450
451 if language in self.ignores["languages"]:
452 return
453
454 if language == "doctest" or (
455 language == "python" and node.rawsource.lstrip().startswith(">>> ")
456 ):
457 self.visit_doctest_block(node)
458 raise docutils.nodes.SkipNode
459
460 if self.code_block_checker.language_is_supported(language):
461 run = self.code_block_checker.create_checker(node.rawsource, language)
462 self._add_check(node=node, run=run, language=language, is_code_node=is_code_node)
463
464 raise docutils.nodes.SkipNode
465
466 def visit_paragraph(self, node: docutils.nodes.Element) -> None:
467 """Check syntax of reStructuredText.
468
469 :param node: The rst node
470 """
471 find = MARKDOWN_LINK_REGEX.search(node.rawsource)
472 if find is not None:
473 self.document.reporter.warning(
474 "(rst) Link is formatted in Markdown style.", base_node=node
475 )
476
477 def _add_check(
478 self,
479 node: docutils.nodes.Element,
480 run: types.CheckerRunFunction,
481 language: str,
482 *,
483 is_code_node: bool,
484 ) -> None:
485 """Add node checker that will be run.
486
487 :param node: The node to check
488 :param run: The runner function that checks the node
489 :param language: The language of the node
490 :param is_code_node: If it is a code block node
491 """
492
493 def run_check() -> types.YieldedLintError:
494 """Yield found issues."""
495 all_results = run()
496 if all_results is not None:
497 if all_results:
498 for result in all_results:
499 error_offset = result["line_number"] - 1
500
501 line_number = getattr(node, "line", None)
502 if line_number is not None:
503 yield types.LintError(
504 source_origin=result["source_origin"],
505 line_number=_beginning_of_code_block(
506 node=node,
507 line_number=line_number,
508 full_contents=self.source,
509 is_code_node=is_code_node,
510 )
511 + error_offset,
512 message=f"({language}) {result['message']}",
513 )
514 else:
515 yield types.LintError(
516 source_origin=self.source_origin, line_number=0, message="unknown error"
517 )
518
519 self.checkers.append(run_check)
520
521 def unknown_visit(self, node: docutils.nodes.Node) -> None:
522 """Ignore."""
523
524 def unknown_departure(self, node: docutils.nodes.Node) -> None:
525 """Ignore."""
526
527
528 def _beginning_of_code_block(
529 node: docutils.nodes.Element, line_number: int, full_contents: str, *, is_code_node: bool
530 ) -> int:
531 """Get line number of beginning of code block.
532
533 :param node: The code block node
534 :param line_number: The current line number
535 :param full_contents: The node's contents
536 :param is_code_node: If it is a code block node
537 :return: First fine number of the block
538 """
539 if _extras.SPHINX_INSTALLED and not is_code_node:
540 sphinx_code_block_delta = -1
541 delta = len(node.non_default_attributes())
542 current_line_contents = full_contents.splitlines()[line_number:]
543 blank_lines = next((i for (i, x) in enumerate(current_line_contents) if x), 0)
544 return line_number + delta - 1 + blank_lines - 1 + sphinx_code_block_delta
545
546 lines = full_contents.splitlines()
547 code_block_length = len(node.rawsource.splitlines())
548
549 with contextlib.suppress(IndexError):
550 # Case where there are no extra spaces.
551 if lines[line_number - 1].strip():
552 return line_number - code_block_length + 1
553
554 # The offsets are wrong if the RST text has multiple blank lines after
555 # the code block. This is a workaround.
556 for line_no in range(line_number, 1, -1):
557 if lines[line_no - 2].strip():
558 break
559
560 return line_no - code_block_length
561
562
563 CODE_BLOCK_RE = re.compile(r"\.\. code::|\.\. code-block::|\.\. sourcecode::")
564
565
566 def _get_code_block_directive_line(node: docutils.nodes.Element, full_contents: str) -> int | None:
567 """Find line of code block directive.
568
569 :param node: The code block node
570 :param full_contents: The node's contents
571 :return: Line of code block directive or :py:obj:`None`
572 """
573 line_number = node.line
574 if line_number is None:
575 return None
576
577 if _extras.SPHINX_INSTALLED:
578 return line_number
579
580 lines = full_contents.splitlines()
581 for line_no in range(line_number, 1, -1):
582 if CODE_BLOCK_RE.match(lines[line_no - 2].strip()) is not None:
583 return line_no - 1
584
585 return None
586
587
588 class CodeBlockChecker:
589 """Checker for code blockes with different languages."""
590
591 def __init__(
592 self,
593 source_origin: types.SourceFileOrString,
594 ignores: types.IgnoreDict | None = None,
595 report_level: config.ReportLevel = config.DEFAULT_REPORT_LEVEL,
596 *,
597 warn_unknown_settings: bool = False,
598 ) -> None:
599 """Inititalize CodeBlockChecker.
600
601 :param source_origin: Path to file the source comes from
602 :param ignores: Ignore information; defaults to :py:obj:`None`
603 :param report_level: Report level;
604 defaults to :py:data:`rstcheck_core.config.DEFAULT_REPORT_LEVEL`
605 :param warn_unknown_settings: If a warning should be logged for unknown settings in config
606 file;
607 defaults to :py:obj:`False`
608 """
609 self.source_origin = source_origin
610 self.ignores = ignores
611 self.report_level = report_level
612 self.warn_unknown_settings = warn_unknown_settings
613
614 def language_is_supported(self, language: str) -> bool:
615 """Check if given language can be checked.
616
617 :param language: Language to check
618 :return: If langauge can be checked
619 """
620 return getattr(self, f"check_{language}", None) is not None
621
622 def create_checker(self, source_code: str, language: str) -> types.CheckerRunFunction:
623 """Create a checker function for the given source and language.
624
625 :param source: Source code to check
626 :param language: Language of the source code
627 :return: Checker function
628 """
629 return lambda: self.check(source_code, language)
630
631 def check(self, source_code: str, language: str) -> types.YieldedLintError:
632 """Call the appropiate checker function for the given langauge to check given source.
633
634 :param source: Source code to check
635 :param language: Language of the source code
636 :return: :py:obj:`None` if language is not supported
637 :yield: Found issues
638 """
639 checker_function = t.Callable[[str], types.YieldedLintError]
640 checker: checker_function | None = getattr(self, f"check_{language}", None)
641 if checker is None:
642 return None
643
644 yield from checker(source_code)
645 return None
646
647 def check_python(self, source_code: str) -> types.YieldedLintError:
648 """Check python source for syntax errors.
649
650 :param source: Python source code to check
651 :return: :py:obj:`None`
652 :yield: Found issues
653 """
654 logger.debug("Check python source.")
655 try:
656 with warnings.catch_warnings():
657 warnings.simplefilter("error", SyntaxWarning)
658 compile(source_code, "<string>", "exec")
659 except SyntaxError as exception:
660 yield types.LintError(
661 source_origin=self.source_origin,
662 line_number=int(exception.lineno or 0),
663 message=exception.msg,
664 )
665
666 def check_json(self, source_code: str) -> types.YieldedLintError:
667 """Check JSON source for syntax errors.
668
669 :param source: JSON source code to check
670 :return: :py:obj:`None`
671 :yield: Found issues
672 """
673 logger.debug("Check JSON source.")
674 try:
675 json.loads(source_code)
676 except ValueError as exception:
677 message = f"{exception}"
678 found = EXCEPTION_LINE_NO_REGEX.search(message)
679 line_number = int(found.group(1)) if found else 0
680
681 yield types.LintError(
682 source_origin=self.source_origin, line_number=int(line_number), message=message
683 )
684
685 def check_yaml(self, source_code: str) -> types.YieldedLintError:
686 """Check YAML source for syntax errors.
687
688 :param source: JSON source code to check
689 :return: :py:obj:`None`
690 :yield: Found issues
691 """
692 if not yaml_imported:
693 logger.debug("PyYAML is not installed, ignoring YAML source.")
694 return
695 logger.debug("Check YAML source.")
696 try:
697 yaml.safe_load(source_code)
698 except yaml.error.YAMLError as exception:
699 message = f"{exception}"
700 found = EXCEPTION_LINE_NO_REGEX.search(message)
701 line_number = int(found.group(1)) if found else 0
702
703 yield types.LintError(
704 source_origin=self.source_origin, line_number=int(line_number), message=message
705 )
706
707 def check_xml(self, source_code: str) -> types.YieldedLintError:
708 """Check XML source for syntax errors.
709
710 :param source: XML source code to check
711 :return: :py:obj:`None`
712 :yield: Found issues
713 """
714 logger.debug("Check XML source.")
715 try:
716 xml.etree.ElementTree.fromstring(source_code) # noqa: S314
717 except xml.etree.ElementTree.ParseError as exception:
718 message = f"{exception}"
719 found = EXCEPTION_LINE_NO_REGEX.search(message)
720 line_number = int(found.group(1)) if found else 0
721
722 yield types.LintError(
723 source_origin=self.source_origin, line_number=int(line_number), message=message
724 )
725
726 def check_rst(self, source_code: str) -> types.YieldedLintError:
727 """Check nested rst source for syntax errors.
728
729 :param source: rst source code to check
730 :return: :py:obj:`None`
731 :yield: Found issues
732 """
733 logger.debug("Check RST source.")
734 yield from check_source(
735 source_code,
736 source_file=self.source_origin,
737 ignores=self.ignores,
738 report_level=self.report_level,
739 warn_unknown_settings=self.warn_unknown_settings,
740 )
741
742 def check_doctest(self, source_code: str) -> types.YieldedLintError:
743 """Check doctest source for syntax errors.
744
745 This does not run the test as that would be unsafe. Nor does this
746 check the Python syntax in the doctest. That could be purposely
747 incorrect for testing purposes.
748
749 :param source: XML source code to check
750 :return: :py:obj:`None`
751 :yield: Found issues
752 """
753 logger.debug("Check doctest source.")
754 parser = doctest.DocTestParser()
755 try:
756 parser.parse(source_code)
757 except ValueError as exception:
758 message = f"{exception}"
759 match = DOCTEST_LINE_NO_REGEX.match(message)
760 if match:
761 yield types.LintError(
762 source_origin=self.source_origin,
763 line_number=int(match.group(1)),
764 message=message,
765 )
766
767 def check_bash(self, source_code: str) -> types.YieldedLintError:
768 """Check bash source for syntax errors.
769
770 :param source: bash source code to check
771 :return: :py:obj:`None`
772 :yield: Found issues
773 """
774 logger.debug("Check bash source.")
775 result = self._run_in_subprocess(source_code, ".bash", ["bash", "-n"])
776
777 if result:
778 (output, filename) = result
779 prefix = str(filename) + ": line "
780 for line in output.splitlines():
781 if not line.startswith(prefix): # pragma: no cover # NOTE: Case not reproducible
782 continue
783 message = line[len(prefix) :]
784 split_message = message.split(":", 1)
785 yield types.LintError(
786 source_origin=self.source_origin,
787 line_number=int(split_message[0]) - 1,
788 message=split_message[1].strip(),
789 )
790
791 def check_c(self, source_code: str) -> types.YieldedLintError:
792 """Check C source for syntax errors.
793
794 :param source: C source code to check
795 :return: :py:obj:`None`
796 :yield: Found issues
797 """
798 logger.debug("Check C source.")
799 return self._gcc_checker(
800 source_code,
801 ".c",
802 [
803 os.getenv("CC", "gcc"),
804 *shlex.split(os.getenv("CFLAGS", "")),
805 *shlex.split(os.getenv("CPPFLAGS", "")),
806 "-I.",
807 "-I..",
808 ],
809 )
810
811 def check_cpp(self, source_code: str) -> types.YieldedLintError:
812 """Check C++ source for syntax errors.
813
814 :param source: C++ source code to check
815 :return: :py:obj:`None`
816 :yield: Found issues
817 """
818 logger.debug("Check C++ source.")
819 yield from self._gcc_checker(
820 # Add a newline to ignore "no newline at end of file" errors
821 # that are reported using clang (e.g. on macOS).
822 source_code + "\n",
823 ".cpp",
824 [
825 os.getenv("CXX", "g++"),
826 *shlex.split(os.getenv("CXXFLAGS", "")),
827 *shlex.split(os.getenv("CPPFLAGS", "")),
828 "-I.",
829 "-I..",
830 ],
831 )
832
833 def _gcc_checker(
834 self, source_code: str, filename_suffix: str, arguments: list[str]
835 ) -> types.YieldedLintError:
836 """Check code blockes using gcc (Helper function).
837
838 :param source_code: Source code to check
839 :param filename_suffix: File suffix for language of the source code
840 :param arguments: Command and arguments to run
841 :return: :py:obj:`None`
842 :yield: Found issues
843 """
844 result = self._run_in_subprocess(
845 source_code, filename_suffix, [*arguments, "-pedantic", "-fsyntax-only"]
846 )
847
848 if result:
849 (output, temp_file_name) = result
850 for line in output.splitlines():
851 try:
852 yield _parse_gcc_style_error_message(
853 line, source_origin=self.source_origin, temp_file_name=temp_file_name
854 )
855 except ValueError:
856 continue
857
858 def _run_in_subprocess(
859 self,
860 code: str,
861 filename_suffix: str,
862 arguments: list[str],
863 ) -> tuple[str, pathlib.Path] | None:
864 """Run checker in a subprocess (Helper function).
865
866 :param source_code: Source code to check
867 :param filename_suffix: File suffix for language of the source code
868 :param arguments: Command and arguments to run
869 :return: :py:obj:`None` if no issues were found else a tuple of the stderr and temp-file
870 name
871 """
872 encoding = locale.getpreferredencoding() or sys.getdefaultencoding()
873
874 source_origin_path = self.source_origin
875 if isinstance(source_origin_path, str):
876 source_origin_path = pathlib.Path(source_origin_path)
877
878 # NOTE: On windows a file cannot be opened twice.
879 # Therefore close it before using it in subprocess.
880 temporary_file = tempfile.NamedTemporaryFile(
881 mode="wb", suffix=filename_suffix, delete=False
882 )
883 temporary_file_path = pathlib.Path(temporary_file.name)
884 try:
885 temporary_file.write(code.encode("utf-8"))
886 temporary_file.flush()
887 temporary_file.close()
888
889 subprocess.run(
890 [*arguments, temporary_file.name], # noqa: S603
891 capture_output=True,
892 cwd=source_origin_path.parent,
893 check=True,
894 )
895 except subprocess.CalledProcessError as exc:
896 return (exc.stderr.decode(encoding), temporary_file_path)
897 else:
898 return None
899 finally:
900 temporary_file_path.unlink()
901
902
903 def _parse_gcc_style_error_message(
904 message: str,
905 source_origin: types.SourceFileOrString,
906 *,
907 temp_file_name: pathlib.Path | None = None,
908 has_column: bool = True,
909 ) -> types.LintError:
910 """Parse GCC-style error message.
911
912 Return (line_number, message). Raise ValueError if message cannot be
913 parsed.
914
915 :param message: Message to parse
916 :param filename: File the code block producing the errors comes from
917 :param temp_file_name: File the message is associated with
918 :param has_column: The the message has a column number; defaults to :py:obj:`True`
919 :raises ValueError: If the message cannot be parsed
920 :return: Parsed message
921 """
922 colons = 2 if has_column else 1
923 prefix = str(temp_file_name or source_origin) + ":"
924 if not message.startswith(prefix):
925 logger.debug("Skipping unparsable message: '%s'.", message)
926 msg = "Message cannot be parsed."
927 raise ValueError(msg)
928 message = message[len(prefix) :]
929 split_message = message.split(":", colons)
930 line_number = int(split_message[0])
931 return types.LintError(
932 source_origin=source_origin, line_number=line_number, message=split_message[colons].strip()
933 )