-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
__init__.py
243 lines (185 loc) · 6.98 KB
/
__init__.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
#!/usr/bin/env python3
#
# __init__.py
"""
Python formatting mate.
"""
#
# Copyright © 2020-2021 Dominic Davis-Foster <dominic@davis-foster.co.uk>
#
# 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.
#
# stdlib
from configparser import ConfigParser
from typing import Iterable, Mapping, Optional
# 3rd party
import click
import isort # type: ignore
from consolekit.terminal_colours import ColourTrilean, resolve_color_default
from consolekit.utils import coloured_diff
from domdf_python_tools.paths import PathPlus, TemporaryPathPlus
from domdf_python_tools.stringlist import StringList
from domdf_python_tools.typing import PathLike
from domdf_python_tools.words import TAB
from isort import Config
from isort.exceptions import FileSkipComment # type: ignore
from yapf.yapflib.yapf_api import FormatCode # type: ignore
# this package
from formate.classes import FormateConfigDict, Hook
from formate.config import parse_hooks
from formate.utils import wants_global_config
__all__ = ["call_hooks", "isort_hook", "yapf_hook", "Reformatter", "reformat_file"]
__author__: str = "Dominic Davis-Foster"
__copyright__: str = "2020-2021 Dominic Davis-Foster"
__license__: str = "MIT License"
__version__: str = "0.0.0"
__email__: str = "dominic@davis-foster.co.uk"
def call_hooks(hooks: Iterable[Hook], source: str) -> str:
"""
Given a list of hooks (in order), call them in turn to reformat the source.
:param hooks:
:param source: The source to reformat.
:returns: The reformatted source.
"""
for hook in hooks:
source = hook(source)
return source
@wants_global_config
def isort_hook(source: str, formate_global_config: Optional[Mapping] = None, **kwargs) -> str:
r"""
Call `isort <https://pypi.org/project/isort/>`_, using the given keyword arguments as its configuration.
:param source: The source to reformat.
:param formate_global_config: The global configuration dictionary. Optional.
:param \*\*kwargs:
:returns: The reformatted source.
"""
if "isort_config_file" in kwargs:
isort_config = Config(settings_file=str(kwargs["isort_config_file"]))
else:
if "line_length" not in kwargs and formate_global_config:
kwargs["line_length"] = formate_global_config["line_length"]
parsed_kwargs = {}
import_headings = {}
for option, value in kwargs.items():
if option.startswith("import_heading"):
import_headings[option[len("import_heading") + 1:]] = value
elif option == "force_to_top":
continue # TODO isort expects a frozenset but I thought it was boolean
else:
parsed_kwargs[option] = value
isort_config = Config(import_headings=import_headings, **kwargs)
try:
return isort.code(source, config=isort_config)
except FileSkipComment:
return source
@wants_global_config
def yapf_hook(source: str, formate_global_config: Optional[Mapping] = None, **kwargs) -> str:
r"""
Call `yapf <https://github.com/google/yapf>`_, using the given keyword arguments as its configuration.
:param source: The source to reformat.
:param formate_global_config: The global configuration dictionary. Optional.
:param \*\*kwargs:
:returns: The reformatted source.
"""
if "yapf_style" in kwargs:
return FormatCode(source, style_config=str(kwargs["yapf_style"]))[0]
else:
if "use_tabs" not in kwargs and formate_global_config:
kwargs["use_tabs"] = formate_global_config["indent"] == TAB
if "column_limit" not in kwargs and formate_global_config:
kwargs["column_limit"] = formate_global_config["line_length"]
with TemporaryPathPlus() as tmpdir:
config_file = tmpdir / ".style.yapf"
config = ConfigParser()
config.read_dict({"style": kwargs})
with config_file.open('w') as fp:
config.write(fp)
return FormatCode(source, style_config=str(config_file))[0]
class Reformatter:
"""
Reformat a Python source file.
:param filename: The filename to reformat.
:param config: The ``formate`` configuration, parsed from a TOML file (or similar).
"""
#: The filename being reformatted.
filename: str
#: The filename being reformatted.
file_to_format: PathPlus
#: The ``formate`` configuration, parsed from a TOML file (or similar).
config: FormateConfigDict
def __init__(self, filename: PathLike, config: FormateConfigDict):
self.file_to_format = PathPlus(filename)
self.filename = self.file_to_format.as_posix()
self.config = config
self._unformatted_source = self.file_to_format.read_text()
self._reformatted_source: Optional[str] = None
def run(self) -> bool:
"""
Run the reformatter.
:return: Whether the file was changed.
"""
hooks = parse_hooks(self.config)
reformatted_source = StringList(call_hooks(hooks, self._unformatted_source))
reformatted_source.blankline(ensure_single=True)
self._reformatted_source = str(reformatted_source)
return self._reformatted_source != self._unformatted_source
def get_diff(self) -> str:
"""
Returns the diff between the original and reformatted file content.
"""
# Based on yapf
# Apache 2.0 License
after = self.to_string().split('\n')
before = self._unformatted_source.split('\n')
return coloured_diff(
before,
after,
self.filename,
self.filename,
"(original)",
"(reformatted)",
lineterm='',
)
def to_string(self) -> str:
"""
Return the reformatted file as a string.
"""
if self._reformatted_source is None:
raise ValueError("'Reformatter.run()' must be called first!")
return self._reformatted_source
def to_file(self) -> None:
"""
Write the reformatted source to the original file.
"""
self.file_to_format.write_text(self.to_string())
def reformat_file(filename: PathLike, config: FormateConfigDict, colour: ColourTrilean = None):
"""
Reformat the given file.
:param filename: The filename to reformat.
:param config: The ``formate`` configuration, parsed from a TOML file (or similar).
:param colour: Whether to force coloured output on (:py:obj:`True`) or off (:py:obj:`False`).
"""
r = Reformatter(filename, config)
if r.run():
click.echo(r.get_diff(), color=resolve_color_default(colour))
ret = 1
else:
ret = 0
r.to_file()
return ret