-
Notifications
You must be signed in to change notification settings - Fork 6
/
commands.py
221 lines (171 loc) · 6.88 KB
/
commands.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: thepoy
# @Email: thepoy@163.com
# @File Name: commands.py
# @Created: 2022-02-04 10:51:04
# @Modified: 2023-02-08 13:31:30
import sublime
import sublime_plugin
from os import path
from typing import Any, Dict, List, Union
from .python_black.constants import CONFIGURATION_FILENAME, CONFIGURATION_CONTENTS
from .python_black.black import black_format
from .python_black.mode import Mode
from .python_black.log import child_logger
from .python_black.utils import (
get_mode,
get_package_settings,
get_project_settings,
set_mode,
)
from .python_black.lib.black import __version__ as black_version
from .python_black.lib.pathspec import __version__ as pathspec_version
from .python_black.lib.platformdirs import __version__ as platformdirs_version
from .python_black.lib.tomli import __version__ as tomli_version
from .python_black.lib.appdirs import __version__ as appdirs_version
logger = child_logger(__name__)
logger.info(
"versions: black=%s, pathspec=%s, platformdirs=%s, tomli=%s, appdirs=%s",
black_version,
pathspec_version,
platformdirs_version,
tomli_version,
appdirs_version,
)
class BlackCommand(sublime_plugin.TextCommand):
def is_visible(self, *args):
region = self.view.sel()[0]
return self.view.match_selector(region.b, "source.python")
def get_source(self, use_selection: bool):
region = self.view.sel()[0]
# select the whole view if there is no selected region
if region.a == region.b or not use_selection:
region = sublime.Region(0, self.view.size())
return region, self.view.substr(region), self.view.encoding()
def run(self, edit: sublime.Edit, use_selection=True, smart_mode=False):
logger.info("use smart mode: %s", smart_mode)
filename = self.view.file_name() or ""
if self.view.settings().get("syntax").lower().find("python") == -1:
sublime.status_message(
f"black: The current file is not a python script: {filename}"
)
return
region, source, encoding = self.get_source(use_selection)
if not isinstance(source, str) and hasattr(source, "decode"):
source = source.decode(encoding)
package_settings: SublimeSettings = get_package_settings().to_dict() # type: ignore
logger.debug("get package settings: %s", package_settings)
project_settings = get_project_settings(self.view)
logger.debug("get project settings: %s", project_settings)
black_format(
source=source,
filepath=filename,
region=region,
encoding=encoding,
edit=edit,
view=self.view,
smart_mode=smart_mode,
package_settings=package_settings,
project_settings=project_settings,
)
class BlackCreateConfiguration(sublime_plugin.WindowCommand):
def run(self) -> None:
folders = self.window.folders()
if len(folders) == 0:
sublime.message_dialog(
"No folders found in the window. Please add a folder first."
)
elif len(folders) == 1:
self._create_configuration(folders[0])
else:
self.window.show_quick_panel(
folders,
lambda index: self._on_selected(folders, index),
placeholder="Select a folder to create the configuration file in",
)
def _on_selected(self, folders: List[str], index: int) -> None:
if index > -1:
self._create_configuration(folders[index])
def _create_configuration(self, folder_path: str) -> None:
config_path = path.join(folder_path, CONFIGURATION_FILENAME)
new_view = self.window.open_file(config_path)
if not path.isfile(config_path):
self._poll_view_until_loaded(new_view)
def _poll_view_until_loaded(self, view: sublime.View, attempt: int = 1) -> None:
if attempt > 10:
return
if view.is_loading():
sublime.set_timeout(
lambda: self._poll_view_until_loaded(view, attempt + 1), 100
)
else:
self._on_view_loaded(view)
def _on_view_loaded(self, view: sublime.View) -> None:
view.run_command("insert_snippet", {"contents": CONFIGURATION_CONTENTS})
class AutoFormatOnSave(sublime_plugin.EventListener):
def format_on_save_mode(self, view: sublime.View) -> Mode:
settings = get_package_settings()
_mode: Union[str, bool] = settings.get("format_on_save", "off") # type: ignore
window = view.window()
if window:
# fmt: off
project_settings: Dict[str, Dict[str, Any]] = (
window.project_data() or {}
).get("settings", {}) # type: ignore
# fmt: on
_mode = project_settings.get("python-black", {}).get(
"format_on_save", _mode
)
if isinstance(_mode, str):
mode = Mode(_mode)
else:
mode = Mode.ON if _mode else Mode.OFF
return mode
def on_pre_save(self, view: sublime.View):
mode = self.format_on_save_mode(view)
if mode == Mode.ON:
view.run_command("black", {"use_selection": False})
sublime.status_message("black: Document has been automatically formatted")
elif mode == Mode.SMART:
view.run_command("black", {"use_selection": False, "smart_mode": True})
class BlackOutputCommand(sublime_plugin.TextCommand):
def run(self, edit, text):
self.view.insert(edit, 0, text)
self.view.end_edit(edit)
def is_visible(self, *args):
return False
class ToggleFormatOnSaveCommand(sublime_plugin.TextCommand):
def run(self, edit):
mode = get_mode()
if mode == Mode.SMART:
sublime.error_message("black: Unable to toggle in `smart` mode")
else:
new_mode = Mode.ON if mode == Mode.OFF else Mode.OFF
set_mode(new_mode)
def description(self):
return "Format On Save (Global)"
class SetFormatOnSaveToSmartCommand(sublime_plugin.TextCommand):
def run(self, edit):
set_mode(Mode.SMART)
def is_checked(self):
mode = get_mode()
return mode == Mode.SMART
def description(self):
return 'Set "Format On Save" to "Smart"'
class SetFormatOnSaveToOnCommand(sublime_plugin.TextCommand):
def run(self, edit):
set_mode(Mode.ON)
def is_checked(self):
mode = get_mode()
return mode == Mode.ON
def description(self):
return 'Set "Format On Save" to "On"'
class SetFormatOnSaveToOffCommand(sublime_plugin.TextCommand):
def run(self, edit):
set_mode(Mode.OFF)
def is_checked(self):
mode = get_mode()
return mode == Mode.OFF
def description(self):
return 'Set "Format On Save" to "Off"'