Debian Codegraph @

scripts/build_config_option_docs.py

raw
1 #! /bin/env python
2 import dataclasses
3 import os
4 from collections.abc import Generator, Iterable
5 from textwrap import dedent
6 from typing import Any
7
8 from isort.main import _build_arg_parser
9 from isort.settings import _DEFAULT_SETTINGS as config
10
11 OUTPUT_FILE = os.path.abspath(
12 os.path.join(os.path.dirname(os.path.abspath(__file__)), "../docs/configuration/options.md")
13 )
14 MD_NEWLINE = " "
15 HUMAN_NAME = {
16 "py_version": "Python Version",
17 "vn": "Version Number",
18 "str": "String",
19 "frozenset": "List of Strings",
20 "tuple": "List of Strings",
21 }
22 CONFIG_DEFAULTS = {"False": "false", "True": "true", "None": ""}
23 DESCRIPTIONS = {}
24 IGNORED = {"source", "help", "sources", "directory"}
25 COLUMNS = ["Name", "Type", "Default", "Python / Config file", "CLI", "Description"]
26 HEADER = """# Configuration options for isort
27
28 As a code formatter isort has opinions. However, it also allows you to have your own. If your opinions disagree with those of isort,
29 isort will disagree but commit to your way of formatting. To enable this, isort exposes a plethora of options to specify
30 how you want your imports sorted, organized, and formatted.
31
32 Too busy to build your perfect isort configuration? For curated common configurations, see isort's [built-in
33 profiles](https://isort.readthedocs.io/en/latest/configuration/profiles.html).
34 """
35 parser = _build_arg_parser()
36
37
38 @dataclasses.dataclass
39 class Example:
40 section_complete: str = ""
41 cfg: str = ""
42 pyproject_toml: str = ""
43 cli: str = ""
44
45 def __post_init__(self):
46 if self.cfg or self.pyproject_toml or self.cli:
47 if self.cfg:
48 cfg = dedent(self.cfg).lstrip()
49 self.cfg = (
50 dedent(
51 """
52 ### Example `.isort.cfg`
53
54 ```
55 [settings]
56 {cfg}
57 ```
58 """
59 )
60 .format(cfg=cfg)
61 .lstrip()
62 )
63
64 if self.pyproject_toml:
65 pyproject_toml = dedent(self.pyproject_toml).lstrip()
66 self.pyproject_toml = (
67 dedent(
68 """
69 ### Example `pyproject.toml`
70
71 ```
72 [tool.isort]
73 {pyproject_toml}
74 ```
75 """
76 )
77 .format(pyproject_toml=pyproject_toml)
78 .lstrip()
79 )
80
81 if self.cli:
82 cli = dedent(self.cli).lstrip()
83 self.cli = (
84 dedent(
85 """
86 ### Example cli usage
87
88 `{cli}`
89 """
90 )
91 .format(cli=cli)
92 .lstrip()
93 )
94
95 sections = [s for s in [self.cfg, self.pyproject_toml, self.cli] if s]
96 sections_str = "\n".join(sections)
97 self.section_complete = f"""**Examples:**
98
99 {sections_str}"""
100
101 else:
102 self.section_complete = ""
103
104 def __str__(self):
105 return self.section_complete
106
107
108 description_mapping: dict[str, str]
109 description_mapping = {
110 "length_sort_sections": "Sort the given sections by length",
111 "forced_separate": "Force certain sub modules to show separately",
112 "sections": "What sections isort should display imports for and in what order",
113 "known_other": "known_OTHER is how imports of custom sections are defined. "
114 "OTHER is a placeholder for the custom section name.",
115 "comment_prefix": "Allows customizing how isort prefixes comments that it adds or modifies on import lines"
116 "Generally ` #` (two spaces before a pound symbol) is use, though one space is also common.",
117 "lines_before_imports": "The number of blank lines to place before imports. -1 for automatic determination",
118 "lines_after_imports": "The number of blank lines to place after imports. -1 for automatic determination",
119 "lines_between_sections": "The number of lines to place between sections",
120 "lines_between_types": "The number of lines to place between direct and from imports",
121 "lexicographical": "Lexicographical order is strictly alphabetical order. "
122 "For example by default isort will sort `1, 10, 2` into `1, 2, 10` - but with "
123 "lexicographical sorting enabled it will remain `1, 10, 2`.",
124 "ignore_comments": "If enabled, isort will strip comments that exist within import lines.",
125 "constants": "An override list of tokens to always recognize as a CONSTANT for order_by_type regardless of casing.",
126 "classes": "An override list of tokens to always recognize as a Class for order_by_type regardless of casing.",
127 "variables": "An override list of tokens to always recognize as a var for order_by_type regardless of casing.",
128 "auto_identify_namespace_packages": "Automatically determine local namespace packages, generally by lack of any src files before a src containing directory.",
129 "namespace_packages": "Manually specify one or more namespace packages.",
130 "follow_links": "If `True` isort will follow symbolic links when doing recursive sorting.",
131 "formatting_function": "The fully qualified Python path of a function to apply to format code sorted by isort.",
132 "group_by_package": "If `True` isort will automatically create section groups by the top-level package they come from.",
133 "indented_import_headings": "If `True` isort will apply import headings to indented imports the same way it does unindented ones.",
134 "import_headings": "A mapping of import sections to import heading comments that should show above them.",
135 "import_footers": "A mapping of import sections to import footer comments that should show below them.",
136 }
137
138 example_mapping: dict[str, Example]
139 example_mapping = {
140 "skip": Example(
141 cfg="""
142 skip=.gitignore,.dockerignore""",
143 pyproject_toml="""
144 skip = [".gitignore", ".dockerignore"]
145 """,
146 ),
147 "extend_skip": Example(
148 cfg="""
149 extend_skip=.md,.json""",
150 pyproject_toml="""
151 extend_skip = [".md", ".json"]
152 """,
153 ),
154 "skip_glob": Example(
155 cfg="""
156 skip_glob=docs/*
157 """,
158 pyproject_toml="""
159 skip_glob = ["docs/*"]
160 """,
161 ),
162 "extend_skip_glob": Example(
163 cfg="""
164 extend_skip_glob=my_*_module.py,test/*
165 """,
166 pyproject_toml="""
167 extend_skip_glob = ["my_*_module.py", "test/*"]
168 """,
169 ),
170 "known_third_party": Example(
171 cfg="""
172 known_third_party=my_module1,my_module2
173 """,
174 pyproject_toml="""
175 known_third_party = ["my_module1", "my_module2"]
176 """,
177 ),
178 "known_first_party": Example(
179 cfg="""
180 known_first_party=my_module1,my_module2
181 """,
182 pyproject_toml="""
183 known_first_party = ["my_module1", "my_module2"]
184 """,
185 ),
186 "known_local_folder": Example(
187 cfg="""
188 known_local_folder=my_module1,my_module2
189 """,
190 pyproject_toml="""
191 known_local_folder = ["my_module1", "my_module2"]
192 """,
193 ),
194 "known_standard_library": Example(
195 cfg="""
196 known_standard_library=my_module1,my_module2
197 """,
198 pyproject_toml="""
199 known_standard_library = ["my_module1", "my_module2"]
200 """,
201 ),
202 "extra_standard_library": Example(
203 cfg="""
204 extra_standard_library=my_module1,my_module2
205 """,
206 pyproject_toml="""
207 extra_standard_library = ["my_module1", "my_module2"]
208 """,
209 ),
210 "forced_separate": Example(
211 cfg="""
212 forced_separate=glob_exp1,glob_exp2
213 """,
214 pyproject_toml="""
215 forced_separate = ["glob_exp1", "glob_exp2"]
216 """,
217 ),
218 "length_sort_sections": Example(
219 cfg="""
220 length_sort_sections=future,stdlib
221 """,
222 pyproject_toml="""
223 length_sort_sections = ["future", "stdlib"]
224 """,
225 ),
226 "add_imports": Example(
227 cfg="""
228 add_imports=import os,import json
229 """,
230 pyproject_toml="""
231 add_imports = ["import os", "import json"]
232 """,
233 ),
234 "remove_imports": Example(
235 cfg="""
236 remove_imports=os,json
237 """,
238 pyproject_toml="""
239 remove_imports = ["os", "json"]
240 """,
241 ),
242 "single_line_exclusions": Example(
243 cfg="""
244 single_line_exclusions=os,json
245 """,
246 pyproject_toml="""
247 single_line_exclusions = ["os", "json"]
248 """,
249 ),
250 "no_lines_before": Example(
251 cfg="""
252 no_lines_before=future,stdlib
253 """,
254 pyproject_toml="""
255 no_lines_before = ["future", "stdlib"]
256 """,
257 ),
258 "src_paths": Example(
259 cfg="""
260 src_paths = src,tests
261 """,
262 pyproject_toml="""
263 src_paths = ["src", "tests"]
264 """,
265 ),
266 "treat_comments_as_code": Example(
267 cfg="""
268 treat_comments_as_code = # my comment 1, # my other comment
269 """,
270 pyproject_toml="""
271 treat_comments_as_code = ["# my comment 1", "# my other comment"]
272 """,
273 ),
274 "supported_extensions": Example(
275 cfg="""
276 supported_extensions=pyw,ext
277 """,
278 pyproject_toml="""
279 supported_extensions = ["pyw", "ext"]
280 """,
281 ),
282 "blocked_extensions": Example(
283 cfg="""
284 blocked_extensions=pyw,pyc
285 """,
286 pyproject_toml="""
287 blocked_extensions = ["pyw", "pyc"]
288 """,
289 ),
290 "known_other": Example(
291 cfg="""
292 sections=FUTURE,STDLIB,THIRDPARTY,AIRFLOW,FIRSTPARTY,LOCALFOLDER
293 known_airflow=airflow""",
294 pyproject_toml="""
295 sections = ['FUTURE', 'STDLIB', 'THIRDPARTY', 'AIRFLOW', 'FIRSTPARTY', 'LOCALFOLDER']
296 known_airflow = ['airflow']""",
297 ),
298 "multi_line_output": Example(cfg="multi_line_output=3", pyproject_toml="multi_line_output = 3"),
299 "show_version": Example(cli="isort --version"),
300 "py_version": Example(
301 cli="isort --py 39",
302 pyproject_toml="""
303 py_version=39
304 """,
305 cfg="""
306 py_version=39
307 """,
308 ),
309 }
310
311
312 @dataclasses.dataclass
313 class ConfigOption:
314 name: str
315 type: type = str
316 default: Any = ""
317 config_name: str = "**Not Supported**"
318 cli_options: Iterable[str] = (" **Not Supported**",)
319 description: str = "**No Description**"
320 example: Example | None = None
321
322 def __str__(self):
323 if self.name in IGNORED:
324 return ""
325
326 if self.cli_options == (" **Not Supported**",):
327 cli_options = self.cli_options[0]
328 else:
329 cli_options = "\n\n- " + "\n- ".join(self.cli_options)
330
331 # new line if example otherwise nothing
332 example = f"\n{self.example}" if self.example else ""
333 return f"""
334 ## {human(self.name)}
335
336 {self.description}
337
338 **Type:** {human(self.type.__name__)}{MD_NEWLINE}
339 **Default:** `{str(self.default) or " "}`{MD_NEWLINE}
340 **Config default:** `{config_default(self.default) or " "}`{MD_NEWLINE}
341 **Python & Config File Name:** {self.config_name}{MD_NEWLINE}
342 **CLI Flags:**{cli_options}
343 {example}"""
344
345
346 def config_default(default: Any) -> str:
347 if isinstance(default, (frozenset, tuple)):
348 default = list(default)
349 default_str = str(default)
350 if default_str in CONFIG_DEFAULTS:
351 return CONFIG_DEFAULTS[default_str]
352
353 if default_str.startswith("py"):
354 return default_str[2:]
355 return default_str
356
357
358 def human(name: str) -> str:
359 if name in HUMAN_NAME:
360 return HUMAN_NAME[name]
361
362 return " ".join(
363 part if part in ("of",) else part.capitalize() for part in name.replace("-", "_").split("_")
364 )
365
366
367 def config_options() -> Generator[ConfigOption, None, None]:
368 cli_actions = {action.dest: action for action in parser._actions}
369 for name, default in config.items():
370 extra_kwargs = {}
371 description: str | None = description_mapping.get(name, None)
372
373 cli = cli_actions.pop(name, None)
374 if cli:
375 extra_kwargs["cli_options"] = cli.option_strings
376 if cli.help and not description:
377 description = cli.help
378
379 default_display = default
380 if isinstance(default, (set, frozenset)) and len(default) > 0:
381 default_display = tuple(sorted(default))
382
383 # todo: refactor place for example params
384 # needs to integrate with isort/settings/_Config
385 # needs to integrate with isort/main/_build_arg_parser
386 yield ConfigOption(
387 name=name,
388 type=type(default),
389 default=default_display,
390 config_name=name,
391 description=description or "**No Description**",
392 example=example_mapping.get(name, None),
393 **extra_kwargs,
394 )
395
396 for name, cli in cli_actions.items():
397 extra_kwargs = {}
398 description: str | None = description_mapping.get(name, None)
399 if cli.type:
400 extra_kwargs["type"] = cli.type
401 elif cli.default is not None:
402 extra_kwargs["type"] = type(cli.default)
403
404 if cli.help and not description:
405 description = cli.help
406
407 yield ConfigOption(
408 name=name,
409 default=cli.default,
410 cli_options=cli.option_strings,
411 example=example_mapping.get(name, None),
412 description=description or "**No Description**",
413 **extra_kwargs,
414 )
415
416
417 def document_text() -> str:
418 return f"{HEADER}{''.join(str(config_option) for config_option in config_options())}"
419
420
421 def write_document():
422 with open(OUTPUT_FILE, "w") as output_file:
423 output_file.write(document_text())
424
425
426 if __name__ == "__main__":
427 write_document()