-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugin.py
242 lines (207 loc) · 7.53 KB
/
plugin.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
import json
import os
import platform
import shutil
import tarfile
import tempfile
import urllib.error
import urllib.request
import zipfile
from io import UnsupportedOperation
import sublime
from LSP.plugin import (
AbstractPlugin,
ClientConfig,
WorkspaceFolder,
register_plugin,
unregister_plugin,
)
from LSP.plugin.core.typing import Any, Callable, Dict, List, Mapping, Optional
GITHUB_DL_URL = (
"https://github.com/valentjn/ltex-ls/releases/download/" + "{0}/ltex-ls-{0}{1}"
) # Format with Release-Tag
GITHUB_RELEASES_API_URL = (
"https://api.github.com/repos/valentjn/ltex-" + "ls/releases/latest"
)
SERVER_FOLDER_NAME = "ltex-ls-{}" # Format with Release-Tag
LATEST_TESTED_RELEASE = "16.0.0" # Latest testet LTEX-LS release
LATEST_GITHUB_RELEASE = None
STORAGE_FOLDER_NAME = "LSP-ltex-ls"
SETTINGS_FILENAME = "LSP-ltex-ls.sublime-settings"
def fetch_latest_release() -> None:
"""
Fetches a the latest release via GitHub API.
:returns: Nothing.
:rtype: None
"""
global LATEST_GITHUB_RELEASE
if not LATEST_GITHUB_RELEASE:
try:
with urllib.request.urlopen(GITHUB_RELEASES_API_URL) as f:
data = json.loads(f.read().decode("utf-8"))
LATEST_GITHUB_RELEASE = data["tag_name"]
except urllib.error.URLError:
pass
fetch_latest_release()
def code_action_insert_settings(server_setting_key: str, value: dict):
"""
Adds a server setting initiated via custom ltex-la codeAction.
Merges the settings if already present.
This function is used for the addToDictionary,... custom commands
:param server_setting_key: The key of the server setting
(in "settings" block)
:type server_setting_key: str
:param value: A dict of "language": [settings] pairs
:type value: dict
"""
settings = sublime.load_settings(SETTINGS_FILENAME)
server_settings = settings.get("settings")
exception_dict = server_settings.get(server_setting_key, {})
for k, val in value.items():
language_setting = exception_dict.get(k, [])
# Remove duplicates
new_language_setting = list(set(language_setting + val))
exception_dict[k] = new_language_setting
server_settings[server_setting_key] = exception_dict
settings.set("settings", server_settings)
sublime.save_settings(SETTINGS_FILENAME)
pass
class LTeXLs(AbstractPlugin):
@classmethod
def name(cls) -> str:
return "ltex-ls"
@classmethod
def basedir(cls) -> str:
"""
The directry of this plugin in Package Storage.
:param cls: The class
:type cls: type
:returns: The path this plugins base directory
:rtype: str
"""
return os.path.join(cls.storage_path(), STORAGE_FOLDER_NAME)
@classmethod
def serverversion(cls) -> str:
"""
Returns the version of ltex-ls to use. Can be None if
no version is set in settings and no connection is available and
and no server is available offline.
:param cls: The class
:type cls: type
:returns: The version of ltex-ls to use. Can be None.
:rtype: str
"""
settings = sublime.load_settings(SETTINGS_FILENAME)
version = settings.get("version")
if version:
return version
# Use latest tested release by default but allow overwriting the
# behavior.
if settings.get("allow_untested") and LATEST_GITHUB_RELEASE:
return LATEST_GITHUB_RELEASE
return LATEST_TESTED_RELEASE
@classmethod
def serverdir(cls) -> str:
"""
The directory of the server. In here are the "bin" and "lib"
folders.
:param cls: The class
:type cls: type
:returns: The server directory if a version can be determined.
Else None
:rtype: str
"""
return os.path.join(
cls.basedir(), SERVER_FOLDER_NAME.format(cls.serverversion())
)
@classmethod
def needs_update_or_installation(cls) -> bool:
return not os.path.isdir(str(cls.serverdir()))
@classmethod
def additional_variables(cls) -> Optional[Dict[str, str]]:
return {
"script": "ltex-ls.bat" if platform.system() == "Windows" else "ltex-ls",
"serverdir": cls.serverdir(),
"serverversion": cls.serverversion(),
}
@classmethod
def install_or_update(cls) -> None:
if not cls.serverversion():
return
if os.path.isdir(cls.basedir()):
shutil.rmtree(cls.basedir())
os.makedirs(cls.basedir())
with tempfile.TemporaryDirectory() as tempdir:
archive_path = os.path.join(tempdir, "server.tar.gz")
suffix = ".tar.gz" # platform-independent release
if os.getenv("JAVA_HOME") is None:
p = sublime.platform()
if p == "osx":
suffix = "-mac-x64.tar.gz"
elif p == "linux":
suffix = "-linux-x64.tar.gz"
elif p == "windows":
suffix = "-windows-x64.zip"
sublime.status_message("ltex-ls: downloading")
urllib.request.urlretrieve(
GITHUB_DL_URL.format(cls.serverversion(), suffix), archive_path
)
sublime.status_message("ltex-ls: extracting")
if suffix.endswith("tar.gz"):
archive = tarfile.open(archive_path, "r:gz")
elif suffix.endswith(".zip"):
archive = zipfile.ZipFile(archive_path)
else:
raise UnsupportedOperation()
archive.extractall(tempdir)
archive.close()
shutil.move(
os.path.join(tempdir, SERVER_FOLDER_NAME.format(cls.serverversion())),
cls.basedir(),
)
sublime.status_message(
"ltex-ls: installed ltex-ls {}".format(cls.serverversion())
)
@classmethod
def can_start(
cls,
window: sublime.Window,
initiating_view: sublime.View,
workspace_folders: List[WorkspaceFolder],
configuration: ClientConfig,
) -> Optional[str]:
if not cls.serverdir():
return "Download failed or version could not be determined."
return None
# Handle custom commands
def on_pre_server_command(
self, command: Mapping[str, Any], done_callback: Callable[[], None]
) -> bool:
session = self.weaksession()
if not session:
return False
cmd = command["command"]
handled = False
if cmd == "_ltex.addToDictionary":
code_action_insert_settings(
"ltex.dictionary", command["arguments"][0]["words"]
)
handled = True
if cmd == "_ltex.hideFalsePositives":
code_action_insert_settings(
"ltex.hiddenFalsePositives", command["arguments"][0]["falsePositives"]
) # noqa
handled = True
if cmd == "_ltex.disableRules":
code_action_insert_settings(
"ltex.disabledRules", command["arguments"][0]["ruleIds"]
)
handled = True
if handled:
sublime.set_timeout_async(done_callback)
return True
return False
def plugin_loaded() -> None:
register_plugin(LTeXLs)
def plugin_unloaded() -> None:
unregister_plugin(LTeXLs)