-
Notifications
You must be signed in to change notification settings - Fork 58
/
configuration.py
305 lines (279 loc) · 10.6 KB
/
configuration.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
#!/usr/bin/env python
#
# Copyright (C) 2012-2022 Steven Myint
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""This module provides docformatter's Configurater class."""
# Standard Library Imports
import argparse
import os
from configparser import ConfigParser
from typing import Dict, List, Union
try:
# Third Party Imports
import tomli
TOMLI_INSTALLED = True
except ImportError:
TOMLI_INSTALLED = False
# docformatter Package Imports
from docformatter import __pkginfo__
class Configurater:
"""Read and store all the docformatter configuration information."""
parser = None
"""Parser object."""
flargs_dct: Dict[str, Union[bool, float, int, str]] = {}
"""Dictionary of configuration file arguments."""
configuration_file_lst = [
"pyproject.toml",
"setup.cfg",
"tox.ini",
]
"""List of supported configuration files."""
args: argparse.Namespace = None
def __init__(self, args: List[Union[bool, int, str]]) -> None:
"""Initialize a Configurater class instance.
Parameters
----------
args : list
Any command line arguments passed during invocation.
"""
self.args_lst = args
self.config_file = ""
self.parser = argparse.ArgumentParser(
description=__doc__,
prog="docformatter",
)
try:
self.config_file = self.args_lst[
self.args_lst.index("--config") + 1
]
except ValueError:
for _configuration_file in self.configuration_file_lst:
if os.path.isfile(_configuration_file):
self.config_file = f"./{_configuration_file}"
break
if os.path.isfile(self.config_file):
self._do_read_configuration_file()
def do_parse_arguments(self) -> None:
"""Parse configuration file and command line arguments."""
changes = self.parser.add_mutually_exclusive_group()
changes.add_argument(
"-i",
"--in-place",
action="store_true",
help="make changes to files instead of printing diffs",
)
changes.add_argument(
"-c",
"--check",
action="store_true",
help="only check and report incorrectly formatted files",
)
self.parser.add_argument(
"-d",
"--diff",
action="store_true",
help="when used with `--check` or `--in-place`, also what changes would be made",
)
self.parser.add_argument(
"-r",
"--recursive",
action="store_true",
default=bool(self.flargs_dct.get("recursive", False)),
help="drill down directories recursively",
)
self.parser.add_argument(
"-e",
"--exclude",
nargs="*",
help="exclude directories and files by names",
)
self.parser.add_argument(
"--wrap-summaries",
default=int(self.flargs_dct.get("wrap-summaries", 79)),
type=int,
metavar="length",
help="wrap long summary lines at this length; "
"set to 0 to disable wrapping (default: 79)",
)
self.parser.add_argument(
"--wrap-descriptions",
default=int(self.flargs_dct.get("wrap-descriptions", 72)),
type=int,
metavar="length",
help="wrap descriptions at this length; "
"set to 0 to disable wrapping (default: 72)",
)
self.parser.add_argument(
"--force-wrap",
action="store_true",
default=bool(self.flargs_dct.get("force-wrap", False)),
help="force descriptions to be wrapped even if it may "
"result in a mess (default: False)",
)
self.parser.add_argument(
"--tab-width",
type=int,
dest="tab_width",
metavar="width",
default=int(self.flargs_dct.get("tab-width", 1)),
help="tabs in indentation are this many characters when "
"wrapping lines (default: 1)",
)
self.parser.add_argument(
"--blank",
dest="post_description_blank",
action="store_true",
default=bool(self.flargs_dct.get("blank", False)),
help="add blank line after description (default: False)",
)
self.parser.add_argument(
"--pre-summary-newline",
action="store_true",
default=bool(self.flargs_dct.get("pre-summary-newline", False)),
help="add a newline before the summary of a multi-line docstring "
"(default: False)",
)
self.parser.add_argument(
"--pre-summary-space",
action="store_true",
default=bool(self.flargs_dct.get("pre-summary-space", False)),
help="add a space after the opening triple quotes "
"(default: False)",
)
self.parser.add_argument(
"--make-summary-multi-line",
action="store_true",
default=bool(
self.flargs_dct.get("make-summary-multi-line", False)
),
help="add a newline before and after the summary of a one-line "
"docstring (default: False)",
)
self.parser.add_argument(
"--close-quotes-on-newline",
action="store_true",
default=bool(
self.flargs_dct.get("close-quotes-on-newline", False)
),
help="place closing triple quotes on a new-line when a "
"one-line docstring wraps to two or more lines "
"(default: False)",
)
self.parser.add_argument(
"--range",
metavar="line",
dest="line_range",
default=self.flargs_dct.get("range", None),
type=int,
nargs=2,
help="apply docformatter to docstrings between these "
"lines; line numbers are indexed at 1 (default: None)",
)
self.parser.add_argument(
"--docstring-length",
metavar="length",
dest="length_range",
default=self.flargs_dct.get("docstring-length", None),
type=int,
nargs=2,
help="apply docformatter to docstrings of given length range "
"(default: None)",
)
self.parser.add_argument(
"--non-strict",
action="store_true",
default=bool(self.flargs_dct.get("non-strict", False)),
help="don't strictly follow reST syntax to identify lists (see "
"issue #67) (default: False)",
)
self.parser.add_argument(
"--config",
default=self.config_file,
help="path to file containing docformatter options",
)
self.parser.add_argument(
"--version",
action="version",
version=f"%(prog)s {__pkginfo__.__version__}",
)
self.parser.add_argument(
"files",
nargs="+",
help="files to format or '-' for standard in",
)
self.args = self.parser.parse_args(self.args_lst[1:])
if self.args.line_range:
if self.args.line_range[0] <= 0:
self.parser.error("--range must be positive numbers")
if self.args.line_range[0] > self.args.line_range[1]:
self.parser.error(
"First value of --range should be less than or equal "
"to the second"
)
if self.args.length_range:
if self.args.length_range[0] <= 0:
self.parser.error(
"--docstring-length must be positive numbers"
)
if self.args.length_range[0] > self.args.length_range[1]:
self.parser.error(
"First value of --docstring-length should be less "
"than or equal to the second"
)
def _do_read_configuration_file(self) -> None:
"""Read docformatter options from a configuration file."""
argfile = os.path.basename(self.config_file)
for f in self.configuration_file_lst:
if argfile == f:
break
fullpath, ext = os.path.splitext(self.config_file)
filename = os.path.basename(fullpath)
if ext == ".toml" and TOMLI_INSTALLED and filename == "pyproject":
self._do_read_toml_configuration()
if (ext == ".cfg" and filename == "setup") or (
ext == ".ini" and filename == "tox"
):
self._do_read_parser_configuration()
def _do_read_toml_configuration(self) -> None:
"""Load configuration information from a *.toml file."""
with open(self.config_file, "rb") as f:
config = tomli.load(f)
result = config.get("tool", {}).get("docformatter", None)
if result is not None:
self.flargs_dct = {
k: v if isinstance(v, list) else str(v)
for k, v in result.items()
}
def _do_read_parser_configuration(self) -> None:
"""Load configuration information from a *.cfg or *.ini file."""
config = ConfigParser()
config.read(self.config_file)
for _section in [
"tool.docformatter",
"tool:docformatter",
"docformatter",
]:
if _section in config.sections():
self.flargs_dct = {
k: v if isinstance(v, list) else str(v)
for k, v in config[_section].items()
}