Debian Codegraph @

core/src/rstcheck_core/inline_config.py

raw symbols SCIP
1 """Inline config comment functionality."""
2
3 from __future__ import annotations
4
5 import functools
6 import logging
7 import re
8 import typing as t
9
10 from . import types
11
12 logger = logging.getLogger(__name__)
13
14
15 RSTCHECK_CONFIG_COMMENT_REGEX = re.compile(r"\.\. rstcheck: (.*)=(.*)$")
16 VALID_INLINE_CONFIG_KEYS = (
17 "ignore-directives",
18 "ignore-roles",
19 "ignore-substitutions",
20 "ignore-languages",
21 )
22 ValidInlineConfigKeys = t.Literal[
23 "ignore-directives", "ignore-roles", "ignore-substitutions", "ignore-languages"
24 ]
25
26 RSTCHECK_FLOW_CONTROL_COMMENT_REGEX = re.compile(r"\.\. rstcheck: ([a-z-]*)$")
27 VALID_INLINE_FLOW_CONTROLS = ("ignore-next-code-block",)
28
29
30 @functools.lru_cache
31 def get_inline_config_from_source(
32 source: str, source_origin: types.SourceFileOrString, *, warn_unknown_settings: bool = False
33 ) -> list[types.InlineConfig]:
34 """Get rstcheck inline configs from source.
35
36 Unknown configs are ignored.
37
38 :param source: Source to get config from
39 :param source_origin: Origin of the source with the inline ignore comments
40 :param warn_unknown_settings: If a warning should be logged on unknown settings;
41 defaults to :py:obj:`False`
42 :return: A list of inline configs
43 """
44 configs: list[types.InlineConfig] = []
45 for idx, line in enumerate(source.splitlines()):
46 match = RSTCHECK_CONFIG_COMMENT_REGEX.search(line)
47 if match is None:
48 continue
49
50 key = match.group(1).strip()
51 value = match.group(2).strip()
52
53 if key not in VALID_INLINE_CONFIG_KEYS:
54 if warn_unknown_settings:
55 logger.warning(
56 "Unknown inline config '%s' found. Source: '%s' at line %s",
57 key,
58 source_origin,
59 idx + 1,
60 )
61 continue
62
63 configs.append(types.InlineConfig(key=key, value=value))
64
65 return configs
66
67
68 def _filter_config_and_split_values(
69 target_config: ValidInlineConfigKeys,
70 source: str,
71 source_origin: types.SourceFileOrString,
72 *,
73 warn_unknown_settings: bool = False,
74 ) -> t.Generator[str, None, None]:
75 """Get specified configs and comma split them.
76
77 :param target_config: Config target to filter for
78 :param source: Source to get config from
79 :param source_origin: Origin of the source with the inline ignore comments
80 :param warn_unknown_settings: If a warning should be logged on unknown settings;
81 defaults to :py:obj:`False`
82 :return: None
83 :yield: Single values for the ``target_config``
84 """
85 inline_configs = get_inline_config_from_source(
86 source, source_origin, warn_unknown_settings=warn_unknown_settings
87 )
88 for inline_config in inline_configs:
89 if inline_config["key"] == target_config:
90 for language in inline_config["value"].split(","):
91 yield language.strip()
92
93
94 def find_ignored_directives(
95 source: str, source_origin: types.SourceFileOrString, *, warn_unknown_settings: bool = False
96 ) -> t.Generator[str, None, None]:
97 """Search the rst source for rstcheck inline ignore-directives comments.
98
99 Directives are ignored via comment.
100
101 For example, to ignore directive1, directive2, and directive3:
102
103 .. testsetup::
104
105 from rstcheck_core.inline_config import find_ignored_directives
106
107 >>> list(find_ignored_directives('''
108 ... Example
109 ... =======
110 ...
111 ... .. rstcheck: ignore-directives=directive1,directive3
112 ...
113 ... .. rstcheck: ignore-directives=directive2
114 ... ''', "<string>"))
115 ['directive1', 'directive3', 'directive2']
116
117 :param source: Rst source code
118 :param source_origin: Origin of the source with the inline ignore comments
119 :return: None
120 :yield: Found directives to ignore
121 """
122 yield from _filter_config_and_split_values(
123 "ignore-directives", source, source_origin, warn_unknown_settings=warn_unknown_settings
124 )
125
126
127 def find_ignored_roles(
128 source: str, source_origin: types.SourceFileOrString, *, warn_unknown_settings: bool = False
129 ) -> t.Generator[str, None, None]:
130 """Search the rst source for rstcheck inline ignore-roles comments.
131
132 Roles are ignored via comment.
133
134 For example, to ignore role1, role2, and role3:
135
136 .. testsetup::
137
138 from rstcheck_core.inline_config import find_ignored_roles
139
140 >>> list(find_ignored_roles('''
141 ... Example
142 ... =======
143 ...
144 ... .. rstcheck: ignore-roles=role1,role3
145 ...
146 ... .. rstcheck: ignore-roles=role2
147 ... ''', "<string>"))
148 ['role1', 'role3', 'role2']
149
150 :param source: Rst source code
151 :param source_origin: Origin of the source with the inline ignore comments
152 :return: None
153 :yield: Found roles to ignore
154 """
155 yield from _filter_config_and_split_values(
156 "ignore-roles", source, source_origin, warn_unknown_settings=warn_unknown_settings
157 )
158
159
160 def find_ignored_substitutions(
161 source: str, source_origin: types.SourceFileOrString, *, warn_unknown_settings: bool = False
162 ) -> t.Generator[str, None, None]:
163 """Search the rst source for rstcheck inline ignore-substitutions comments.
164
165 Substitutions are ignored via comment.
166
167 For example, to ignore substitution1, substitution2, and substitution3:
168
169 .. testsetup::
170
171 from rstcheck_core.inline_config import find_ignored_substitutions
172
173 >>> list(find_ignored_substitutions('''
174 ... Example
175 ... =======
176 ...
177 ... .. rstcheck: ignore-substitutions=substitution1,substitution3
178 ...
179 ... .. rstcheck: ignore-substitutions=substitution2
180 ... ''', "<string>"))
181 ['substitution1', 'substitution3', 'substitution2']
182
183 :param source: Rst source code
184 :param source_origin: Origin of the source with the inline ignore comments
185 :return: None
186 :yield: Found substitutions to ignore
187 """
188 yield from _filter_config_and_split_values(
189 "ignore-substitutions", source, source_origin, warn_unknown_settings=warn_unknown_settings
190 )
191
192
193 def find_ignored_languages(
194 source: str, source_origin: types.SourceFileOrString, *, warn_unknown_settings: bool = False
195 ) -> t.Generator[str, None, None]:
196 """Search the rst source for rstcheck inline ignore-languages comments.
197
198 Languages are ignored via comment.
199
200 For example, to ignore C++, JSON, and Python:
201
202 .. testsetup::
203
204 from rstcheck_core.inline_config import find_ignored_languages
205
206 >>> list(find_ignored_languages('''
207 ... Example
208 ... =======
209 ...
210 ... .. rstcheck: ignore-languages=cpp,json
211 ...
212 ... .. rstcheck: ignore-languages=python
213 ... ''', "<string>"))
214 ['cpp', 'json', 'python']
215
216 :param source: Rst source code
217 :param source_origin: Origin of the source with the inline ignore comments
218 :return: None
219 :yield: Found languages to ignore
220 """
221 yield from _filter_config_and_split_values(
222 "ignore-languages", source, source_origin, warn_unknown_settings=warn_unknown_settings
223 )
224
225
226 @functools.lru_cache
227 def get_inline_flow_control_from_source(
228 source: str, source_origin: types.SourceFileOrString, *, warn_unknown_settings: bool = False
229 ) -> list[types.InlineFlowControl]:
230 """Get rstcheck inline flow control from source.
231
232 Unknown flow controls are ignored.
233
234 :param source: Source to get config from
235 :param source_origin: Origin of the source with the inline flow control
236 :param warn_unknown_settings: If a warning should be logged on unknown settings;
237 defaults to :py:obj:`False`
238 :return: A list of inline flow controls
239 """
240 configs: list[types.InlineFlowControl] = []
241 for idx, line in enumerate(source.splitlines()):
242 match = RSTCHECK_FLOW_CONTROL_COMMENT_REGEX.search(line)
243 if match is None:
244 continue
245
246 value = match.group(1).strip()
247 line_number = idx + 1
248
249 if value not in VALID_INLINE_FLOW_CONTROLS:
250 if warn_unknown_settings:
251 logger.warning(
252 "Unknown inline flow control '%s' found. Source: '%s' at line %s",
253 value,
254 source_origin,
255 line_number,
256 )
257 continue
258
259 configs.append(types.InlineFlowControl(value=value, line_number=line_number))
260
261 return configs
262
263
264 def find_code_block_ignore_lines(
265 source: str,
266 source_origin: types.SourceFileOrString,
267 *,
268 warn_unknown_settings: bool = False,
269 ) -> t.Generator[int, None, None]:
270 """Get lines of ``ignore-next-code-block`` flow control comments.
271
272 :param source: Source to get config from
273 :param source_origin: Origin of the source with the inline ignore comments
274 :param warn_unknown_settings: If a warning should be logged on unknown settings;
275 defaults to :py:obj:`False`
276 :return: None
277 :yield: Single values for the ``target_config``
278 """
279 flow_controls = get_inline_flow_control_from_source(
280 source, source_origin, warn_unknown_settings=warn_unknown_settings
281 )
282 for flow_control in flow_controls:
283 if flow_control["value"] == "ignore-next-code-block":
284 yield flow_control["line_number"]