-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSwift Format.py
executable file
·313 lines (260 loc) · 10.2 KB
/
Swift Format.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
306
307
308
309
310
311
312
313
#
# Swift Format.py
#
# AGPLv3 License
# Created by github.com/aerobounce on 2020/07/19.
# Copyright © 2020-2022, aerobounce. All rights reserved.
#
# pyright: reportUnknownArgumentType=false
# pyright: reportUnknownMemberType=false, reportUnknownVariableType=false
from fnmatch import fnmatch
from html import escape
from os import R_OK, access, path
from re import IGNORECASE, search, sub
from subprocess import PIPE, Popen
from sublime import LAYOUT_BELOW, Edit, Phantom, PhantomSet, Region, View
from sublime import error_message as alert
from sublime import expand_variables, load_settings
from sublime_plugin import TextCommand, ViewEventListener
SETTINGS_FILENAME = "Swift Format.sublime-settings"
ON_CHANGE_TAG = "reload_settings"
UTF_8 = "utf-8"
PHANTOM_STYLE = """
<style>
div.error-arrow {
border-top: 0.4rem solid transparent;
border-left: 0.5rem solid color(var(--redish) blend(var(--background) 30%));
width: 0;
height: 0;
}
div.error {
padding: 0.4rem 0 0.4rem 0.7rem;
margin: 0 0 0.2rem;
border-radius: 0 0.2rem 0.2rem 0.2rem;
}
div.error span.message {
padding-right: 0.7rem;
}
div.error a {
text-decoration: inherit;
padding: 0.35rem 0.7rem 0.45rem 0.8rem;
position: relative;
bottom: 0.05rem;
border-radius: 0 0.2rem 0.2rem 0;
font-weight: bold;
}
html.dark div.error a {
background-color: #00000018;
}
html.light div.error a {
background-color: #ffffff18;
}
</style>
"""
def plugin_loaded():
SwiftFormat.settings = load_settings(SETTINGS_FILENAME)
SwiftFormat.reload_settings()
SwiftFormat.settings.add_on_change(ON_CHANGE_TAG, SwiftFormat.reload_settings)
def plugin_unloaded():
SwiftFormat.settings.clear_on_change(ON_CHANGE_TAG)
class SwiftFormat:
settings = load_settings(SETTINGS_FILENAME)
phantom_sets = {}
shell_command = ""
last_valid_config_path = ""
format_on_save = True
ignored_filenames = []
show_error_inline = True
scroll_to_error_point = True
config_paths = []
@classmethod
def reload_settings(cls):
cls.shell_command = cls.settings.get("swiftformat_bin_path")
cls.last_valid_config_path = ""
cls.format_on_save = cls.settings.get("format_on_save")
cls.ignored_filenames = cls.settings.get("ignored_filenames")
cls.show_error_inline = cls.settings.get("show_error_inline")
cls.scroll_to_error_point = cls.settings.get("scroll_to_error_point")
cls.config_paths = cls.settings.get("config_paths")
@classmethod
def update_phantoms(cls, view: View, stderr: str, error_point: int):
view_id = view.id()
if view_id not in cls.phantom_sets:
cls.phantom_sets[view_id] = PhantomSet(view, str(view_id))
# Create Phantom
def phantom_content():
# Remove unneeded text from stderr
error_message = stderr.replace("error: ", "")
return (
"<body id=inline-error>"
+ PHANTOM_STYLE
+ '<div class="error-arrow"></div><div class="error">'
+ '<span class="message">'
+ escape(error_message, quote=False)
+ "</span>"
+ "<a href=hide>"
+ chr(0x00D7)
+ "</a></div>"
+ "</body>"
)
new_phantom = Phantom(
Region(error_point, view.line(error_point).b),
phantom_content(),
LAYOUT_BELOW,
lambda _: view.erase_phantoms(str(view_id)),
)
# Store Phantom
cls.phantom_sets[view_id].update([new_phantom])
@staticmethod
def parse_error_point(view: View, stderr: str):
if not stderr:
return
matches = search(r"(?:Unexpected|Expected).+?\b(\d+)\b\b(?::(\d+))?\b", stderr)
if matches:
if len(matches.groups()) == 0:
return
line = int(matches.group(1)) - 1
column = int(matches.group(2) or 1) - 1
return view.text_point(line, column)
@staticmethod
def is_readable_file(filepath: str):
if path.isfile(filepath):
return access(filepath, R_OK)
return False
@staticmethod
def shell(command: str, stdin: str):
with Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE) as shell:
# Print command executed to the console of ST
print("[Swift Format] Popen:", command)
# Nil check to suppress linter
if not shell.stdin or not shell.stdout or not shell.stderr:
return ("", "")
# Write target_text into stdin and ensure the descriptor is closed
_ = shell.stdin.write(stdin.encode(UTF_8))
shell.stdin.close()
# Read stdout and stderr
return (
shell.stdout.read().decode(UTF_8),
shell.stderr.read().decode(UTF_8),
)
@classmethod
def execute_format(cls, view: View, edit: Edit):
# Get entire string
entire_region = Region(0, view.size())
entire_text = view.substr(entire_region)
# Early return
if not entire_text:
return
# Base command
shell_command = cls.shell_command
# Use cached path
if cls.config_paths and cls.is_readable_file(cls.last_valid_config_path):
shell_command += ' --config "{}"'.format(cls.last_valid_config_path)
# Find and use config file
elif cls.config_paths:
cls.last_valid_config_path = ""
active_window = view.window()
if active_window:
variables = active_window.extract_variables()
# Iterate directories to find config file
for path_candidate in cls.config_paths:
config_file = expand_variables(path_candidate, variables)
if cls.is_readable_file(config_file):
shell_command += ' --config "{}"'.format(config_file)
cls.last_valid_config_path = config_file
break
# Config file is not in use anymore
else:
cls.last_valid_config_path = ""
# Execute shell and get output
output = cls.shell(shell_command, entire_text)
stdout = output[0]
stderr = output[1].replace("Running SwiftFormat...\n", "")
stderr = sub(
"SwiftFormat completed successfully.\n", "", stderr, flags=IGNORECASE
)
stderr = stderr.replace("\n", "")
# Present alert for 'command not found'
if "command not found" in stderr:
alert("Swift Format\n" + stderr)
return
# Parse possible error point
error_point = cls.parse_error_point(view, stderr)
# Present alert for other errors
if stderr and not error_point:
alert("Swift Format\n" + stderr)
return
# Print parsing error
if error_point:
print("[Swift Format]", stderr)
# Store original viewport position
original_viewport_position = view.viewport_position()
# Replace with the result only if no error has been caught
if stdout and not stderr:
view.replace(edit, entire_region, stdout)
# Update Phantoms
view.erase_phantoms(str(view.id()))
if cls.show_error_inline and error_point:
cls.update_phantoms(view, stderr, error_point)
# Scroll to the syntax error point
if cls.scroll_to_error_point and error_point:
view.sel().clear()
view.sel().add(Region(error_point))
view.show_at_center(error_point)
else:
# Restore viewport position
view.set_viewport_position((0, 0), False)
view.set_viewport_position(original_viewport_position, False)
class GenerateConfigCommand(TextCommand):
def run(self, edit: Edit, cwd: str): # pyright: ignore
active_window = self.view.window()
if not active_window:
return
cwd = active_window.extract_variables()[cwd]
command = SwiftFormat.shell_command + ' --inferoptions "{}"'.format(cwd)
output = SwiftFormat.shell(command, "")
stdout = output[0]
stderr = output[1]
if "Failed to to infer options" in stderr:
alert("Swift Format\nFailed to to infer options.")
return
if "Options inferred from" in stderr:
stdout = stdout.replace(" --", "\n--")
new_view = active_window.new_file()
new_view.set_name(".swiftformat")
try:
new_view.assign_syntax("scope:source.genconfig")
except:
pass
_ = new_view.insert(edit, 0, stdout)
_ = new_view.insert(edit, 0, "# Inferred from {}\n".format(cwd))
class SwiftFormatCommand(TextCommand):
def run(self, edit: Edit): # pyright: ignore
SwiftFormat.execute_format(self.view, edit)
class SwiftFormatListener(ViewEventListener):
def on_pre_save(self):
active_window = self.view.window()
if not active_window:
return
try:
project_data = active_window.project_data() or {}
if not project_data["settings"]["Swift Format"]["format_on_save"]:
return
except:
pass
is_syntax_swift = "Swift" in self.view.settings().get("syntax")
is_extension_swift = (
active_window.extract_variables()["file_extension"] == "swift"
)
file = active_window.extract_variables()["file"]
file_name = active_window.extract_variables()["file_name"]
if not (SwiftFormat.format_on_save and (is_syntax_swift or is_extension_swift)):
return
for ignored_filename in SwiftFormat.ignored_filenames:
if fnmatch(file, ignored_filename) or fnmatch(file_name, ignored_filename):
return
self.view.run_command("swift_format")
def on_close(self):
view_id = self.view.id()
if view_id in SwiftFormat.phantom_sets:
_ = SwiftFormat.phantom_sets.pop(view_id)