-
Notifications
You must be signed in to change notification settings - Fork 18
/
utils.py
264 lines (198 loc) · 7.77 KB
/
utils.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (C) 2022 Andy Stewart
#
# Author: Andy Stewart <[email protected]>
# Maintainer: Andy Stewart <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import functools
import logging
import pathlib
import platform
import sys
from PyQt6.QtCore import QObject, pyqtSignal
from typing import Optional
from urllib.parse import urlparse
import sexpdata
from epc.client import EPCClient
try:
import orjson as json_parser
except:
import json as json_parser
epc_client: Optional[EPCClient] = None
# initialize logging, default to STDERR and INFO level
logger = logging.getLogger("holo-layer")
logger.setLevel(logging.INFO)
logger.addHandler(logging.StreamHandler())
def init_epc_client(emacs_server_port):
global epc_client
if epc_client is None:
try:
epc_client = EPCClient(("127.0.0.1", emacs_server_port), log_traceback=True)
except ConnectionRefusedError:
import traceback
logger.error(traceback.format_exc())
def close_epc_client():
if epc_client is not None:
epc_client.close()
def handle_arg_types(arg):
if type(arg) is str and arg.startswith("'"):
arg = sexpdata.Symbol(arg.partition("'")[2])
return sexpdata.Quoted(arg)
def eval_in_emacs(method_name, *args):
args = [sexpdata.Symbol(method_name)] + list(map(handle_arg_types, args)) # type: ignore
sexp = sexpdata.dumps(args)
logger.debug("Eval in Emacs: %s", sexp)
# Call eval-in-emacs elisp function.
epc_client.call("eval-in-emacs", [sexp]) # type: ignore
def message_emacs(message: str):
"""Message to Emacs with prefix."""
eval_in_emacs("message", "[Holo-Layer] " + message)
def epc_arg_transformer(arg):
"""Transform elisp object to python object
1 => 1
"string" => "string"
(list :a 1 :b 2) => {"a": 1, "b": 2}
(list :a 1 :b (list :c 2)) => {"a": 1, "b": {"c": 2}}
(list 1 2 3) => [1 2 3]
(list 1 2 (list 3 4)) => [1 2 [3 4]]
"""
if type(arg) != list:
return arg
# NOTE: Empty list elisp can be treated as both empty python dict/list
# Convert empty elisp list to empty python dict due to compatibility.
# check if we can tranform arg to python dict instance
type_dict_p = len(arg) % 2 == 0
if type_dict_p:
for v in arg[::2]:
if type(v) != sexpdata.Symbol or not v.value().startswith(":"):
type_dict_p = False
break
if type_dict_p:
# transform [Symbol(":a"), 1, Symbol(":b"), 2] to dict(a=1, b=2)
ret = dict()
for i in range(0, len(arg), 2):
ret[arg[i].value()[1:]] = epc_arg_transformer(arg[i + 1])
return ret
else:
return list(map(epc_arg_transformer, arg))
def convert_emacs_bool(symbol_value, symbol_is_boolean):
if symbol_is_boolean == "t":
return symbol_value is True
else:
return symbol_value
def get_emacs_vars(args):
return list(map(lambda result: convert_emacs_bool(result[0], result[1]) if result != [] else False,
epc_client.call_sync("get-emacs-vars", args))) # type: ignore
def get_emacs_var(var_name):
symbol_value, symbol_is_boolean = epc_client.call_sync("get-emacs-var", [var_name]) # type: ignore
return convert_emacs_bool(symbol_value, symbol_is_boolean)
def get_emacs_func_result(method_name, *args):
"""Call eval-in-emacs elisp function synchronously and return the result."""
result = epc_client.call_sync(method_name, args) # type: ignore
return result
def get_command_result(command_string, cwd):
import subprocess
process = subprocess.Popen(command_string, cwd=cwd, shell=True, text=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
encoding="utf-8")
ret = process.wait()
return "".join((process.stdout if ret == 0 else process.stderr).readlines()).strip() # type: ignore
def generate_request_id():
import random
return abs(random.getrandbits(16))
# modified from Lib/pathlib.py
def _make_uri_win32(path):
from urllib.parse import quote_from_bytes as urlquote_from_bytes
# Under Windows, file URIs use the UTF-8 encoding.
drive = path.drive
if len(drive) == 2 and drive[1] == ':':
# It's a path on a local drive => 'file:///c:/a/b'
rest = path.as_posix()[2:].lstrip('/')
return 'file:///%s%%3A/%s' % (
drive[0], urlquote_from_bytes(rest.encode('utf-8')))
else:
# It's a path on a network drive => 'file://host/share/a/b'
return 'file:' + urlquote_from_bytes(path.as_posix().encode('utf-8'))
def path_to_uri(path):
path = pathlib.Path(path)
if get_os_name() != "windows":
uri = path.as_uri()
else:
if not path.is_absolute():
raise ValueError("relative path can't be expressed as a file URI")
# encode uri to 'file:///c%3A/project/xxx.js' like vscode does
uri = _make_uri_win32(path)
return uri
def uri_to_path(uri):
from urllib.parse import unquote
# parse first, '#' may be part of filepath(encoded)
parsed = urlparse(uri)
# for example, ts-ls return 'file:///c%3A/lib/ref.js'
path = unquote(parsed.path)
if sys.platform == "win32":
path = path[1:]
return path
def path_as_key(path):
key = path
# NOTE: (buffer-file-name) return "d:/Case/a.go", gopls return "file:///D:/Case/a.go"
if sys.platform == "win32":
path = pathlib.Path(path).as_posix()
key = path.lower()
return key
def add_to_path_dict(path_dict, filepath, value):
path_dict[path_as_key(filepath)] = value
def is_in_path_dict(path_dict, path):
path_key = path_as_key(path)
return path_key in path_dict
def remove_from_path_dict(path_dict, path):
del path_dict[path_as_key(path)]
def get_from_path_dict(path_dict, filepath):
return path_dict[path_as_key(filepath)]
def log_time(message):
import datetime
logger.info("\n--- [{}] {}".format(datetime.datetime.now().time(), message))
@functools.lru_cache(maxsize=None)
def get_emacs_version():
return get_emacs_func_result("get-emacs-version")
def get_os_name():
return platform.system().lower()
def parse_json_content(content):
return json_parser.loads(content)
class PostGui(QObject):
through_thread = pyqtSignal(object, object)
def __init__(self, inclass=True):
super(PostGui, self).__init__()
self.through_thread.connect(self.on_signal_received)
self.inclass = inclass
def __call__(self, func):
self._func = func
from functools import wraps
@wraps(func)
def obj_call(*args, **kwargs):
self.emit_signal(args, kwargs)
return obj_call
def emit_signal(self, args, kwargs):
self.through_thread.emit(args, kwargs)
def on_signal_received(self, args, kwargs):
try:
if self.inclass:
obj, args = args[0], args[1:]
self._func(obj, *args, **kwargs)
else:
self._func(*args, **kwargs)
except Exception:
import traceback
traceback.print_exc()