-
Notifications
You must be signed in to change notification settings - Fork 465
/
codelite-remote
509 lines (413 loc) · 14.9 KB
/
codelite-remote
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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
#!/usr/bin/env python3
import sys
import os
import json
import re
import argparse
import subprocess
import logging
import time
# global configuration object
configuration = {}
# ----------------------------------------------------------------------------------------------------------------------------------
# Sample usage:
#
# {"command":"ls", "file_extensions":[".cpp",".hpp",".h"], "root_dir":"/c/src/codelite"}
# {"command":"ls", "file_extensions":[".cpp",".hpp",".h"], "root_dir":"C:/src/codelite"}
# {"command":"find", "file_extensions": [".cpp",".hpp",".h"], "root_dir": "/c/src/codelite/LiteEditor", "find_what": "frame", "whole_word": false, "icase": true}
# {"command":"write_file", "path": "/tmp/myfile.txt", "content": "hello world"}
# {"command":"exec", "cmd": "/usr/bin/passwd", "wd": "/c/src/codelite/AutoSave", "env": [{"name":"PATH", "value":"/c/src/codelite/Runtime"}]}
# {"command": "locate", "path": "/usr/bin", "name": "clangd", "ext": "", "versions": [15,14,13,12,11,10,9,8,7,6]}
# {"command": "find_path", "path": "$HOME/devl/codelite/LiteEditor/.git"}
# {"command": "list_lsps"}
#
# Command line usage:
# python3 codelite-remote.py --context builder
#
# ----------------------------------------------------------------------------------------------------------------------------------
def print_message_terminator():
print(">>codelite-remote-msg-end<<")
def _load_config_file(filepath):
"""
attempt to load a configuration file
Returns
-------
true on success
"""
if not os.path.exists(filepath):
return False
config_content = open(filepath, "r").read()
try:
global configuration
configuration = json.loads(config_content)
logging.info(
"successfully loaded configuration file: {}".format(filepath)
)
return True
except json.decoder.JSONDecodeError as e:
logging.error("Failed to load configuration file: {}".format(filepath))
logging.error(e)
return False
def _create_empty_config_file_if_not_exists(directory):
"""
create empty configuration file with a given path
"""
config_file = "{}/codelite-remote.json".format(directory)
if os.path.exists(config_file):
return
# create a default configuration file
logging.info("creating empty configuration file: {}".format(config_file))
try:
# Create the directory in the path
os.makedirs(directory, exist_ok=True)
logging.info("successfully created directory {}".format(directory))
except OSError as error:
logging.debug("directory {} already exists".format(directory))
fp = open(config_file, "w")
fp.write("{}")
fp.close()
def load_configuration():
# We first try to load the configuration file for the current workspace
# by default this will be the `WORKSPACE_PATH/.codelite`
curdir = os.path.dirname(__file__)
local_config_file = "{}/codelite-remote.json".format(curdir)
# try to load the local configuration first
config_loaded = _load_config_file(local_config_file)
if not config_loaded:
# we could not find a local configuration file -
# try loading the global one (`~/.codelite/codelite-remote.json`)
# if a global configuration file does not exist, create an empty one
home_dir = os.path.expandvars("$HOME/.codelite")
global_config_file = "{}/codelite-remote.json".format(home_dir)
_create_empty_config_file_if_not_exists(home_dir)
config_loaded = _load_config_file(global_config_file)
return config_loaded
def write_file(cmd):
try:
fp = open(cmd["path"], "w")
fp.write(cmd["content"])
fp.close()
except Exception as e:
logging.error("write_file error: {}".format(e))
print_message_terminator()
def run_command(command, working_directory=None, env=None):
try:
completed_proc = subprocess.run(
args=command,
cwd=working_directory,
shell=True,
env=env,
stdin=subprocess.PIPE,
)
except Exception as e:
print(f"error: command `{command}` exited with error. {e}")
def run_command_and_return_output(command, working_directory=None, env=None):
try:
return True, subprocess.check_output(
args=command,
cwd=working_directory,
shell=True,
env=env,
stderr=subprocess.STDOUT,
).decode("utf-8")
except Exception as e:
return False, f"error: {e}"
def expand_vars(s):
expanded = os.path.expanduser(s)
expanded = os.path.expandvars(expanded)
return expanded
def on_exec(cmd):
"""
Execute command and print its output
"""
# preare the environment
env_dict = dict(os.environ.copy())
user_env = cmd["env"]
for env_entry in user_env:
name = env_entry["name"]
value = expand_vars(env_entry["value"])
if env_dict.get(name, -1) == -1:
env_dict[name] = value
else:
env_dict[name] = "{}:{}".format(value, env_dict[name])
working_directory = expand_vars(cmd["wd"])
command = expand_vars(cmd["cmd"])
run_command(command, working_directory=working_directory, env=env_dict)
# always print the terminating message
print_message_terminator()
def get_list_files_commands(cmd):
where = cmd["root_dir"]
extensions = cmd["file_extensions"]
exclude_pattern = None
if hasattr(cmd, "exclude_patterns"):
exclude_pattern = cmd["exclude_patterns"]
command = f"find {where} -type f "
first_ext = True
for ext in extensions:
if not first_ext:
command += " -o "
else:
first_ext = False
command += f'-name "{ext}" '
# add exclude patterns
if exclude_pattern and len(exclude_pattern) > 0:
command += "|"
for exclude_pat in exclude_pattern:
command += f'grep -v "{exclude_pat}"|'
# strip the last "|"
command = command[:-1]
command += "| sort"
return command
def get_files(cmd):
files = set()
find_cmd = get_list_files_commands(cmd)
success, find_output = run_command_and_return_output(find_cmd)
if success == False:
return None
files_arr = find_output.splitlines()
current_batch: str = ""
for i in range(0, len(files_arr)):
current_batch += f'"{files_arr[i]}" '
if i % 17 == 16:
current_batch = current_batch.rstrip()
files.add(current_batch)
current_batch = ""
current_batch = current_batch.strip()
if len(current_batch) > 0:
files.add(current_batch)
if len(files) == 0:
return None
else:
return files
def on_find_files(cmd):
"""
Find list of files with a given extension and from a given root directory
Example command:
{"command":"ls", "file_extensions":["*.cpp","*.hpp","*.h"], "exclude_patterns": ["*build/*"], "root_dir":"$HOME/devl/codelite"}
"""
# build the find command
command = get_list_files_commands(cmd)
run_command(command)
print_message_terminator()
def get_grep_command(cmd):
command = "grep --line-number --with-filename "
if cmd["whole_word"] == True:
command += "-w "
if cmd["icase"] == True:
command += "-i "
find_what = cmd["find_what"]
command += f'"{find_what}" '
command += "%FILE%"
return command
def on_find_in_files(cmd):
"""
Find list of files with a given extension and from a given root directory
Example command:
{"command":"find","file_extensions":["*.cpp","*.hpp","*.h"],"root_dir":"/home/eran/devl/codelite","find_what":"wxStringSet_t","icase": true,"whole_word": false}
"""
files = get_files(cmd)
if files:
# get list of files and run grep on each one of them
grep_command = get_grep_command(cmd)
for file in files:
c = grep_command.replace("%FILE%", file)
run_command(c)
print_message_terminator()
def on_replace_in_files(cmd):
"""
Replace `find_what` with `replace_with` in `root_dir` files that match pattern `file_extensions`
Example command:
{"command":"replace","file_extensions":["*.cpp","*.hpp","*.h"],"root_dir":"$HOME/devl/codelite","find_what":"wxStringSet_t","icase": true,"whole_word": false, "replace_with": "std::unordered_set<wxString>"}
"""
files = get_files(cmd)
if files:
# build sed command
find_what: str = cmd["find_what"]
replace_with: str = cmd["replace_with"]
ignore_case = cmd["icase"]
whole_word = cmd["whole_word"]
# escape special chars
find_what = find_what.replace("/", "\\/")
replace_with = replace_with.replace("/", "\\/")
# escape double quotes
find_what = find_what.replace('"', '\\"')
replace_with = replace_with.replace('"', '\\"')
if whole_word:
whold_word_delim_start = "([^\\w]|^)"
whold_word_delim_end = "([^\\w]|$)"
find_what = (
f"{whold_word_delim_start}{find_what}{whold_word_delim_end}"
)
base_command = (
f'sed -E -i.bak "s/{find_what}/\\1{replace_with}\\2/g'
)
else:
base_command = f'sed -E -i.bak "s/{find_what}/{replace_with}/g'
if ignore_case:
base_command += "I"
base_command += '"'
for file in files:
sed_command = f"{base_command} {file}"
run_command(sed_command)
# print the modified files
arr_files = file.split(" ")
for f in arr_files:
f = f.replace('"', "")
print(f)
# remove the backup file created
backup_file = f"{f}.bak"
if os.path.exists(backup_file):
os.remove(backup_file)
print_message_terminator()
def locate_in_path(name, path, versions_arr, ext):
"""
Attempting to locate "name" in a given path
with versions suffix (optionally)
Returns
-------
full path on success, empty string otherwise
"""
## first try with suffix
for version_number in versions_arr:
fullpath = "{}/{}-{}".format(path, name, version_number)
if len(ext) > 0:
fullpath = "{}.{}".format(fullpath, ext)
if os.path.exists(fullpath):
return fullpath
# If we got here, we could not get a match with suffix
# so try without it
fullpath = f"{path}/{name}"
if len(ext) > 0:
fullpath = f"{fullpath}.{ext}"
logging.debug("Checking path: {}".format(fullpath))
if os.path.isfile(fullpath) or os.path.islink(fullpath):
logging.debug("found: {}".format(fullpath))
return fullpath
return ""
def on_list_lsps(lsps_array):
# use the global configuration file
global configuration
if (
"Language Server Plugin" in configuration
and "servers" in configuration["Language Server Plugin"]
):
# print the servers array
print(json.dumps(configuration["Language Server Plugin"]["servers"]))
else:
# print an empty array
print("[]")
print_message_terminator()
def on_find_path(cmd):
"""
find a directory or a file with a given name
if the path does not exist, check the parent folder until we hit root /
"""
path = cmd["path"]
path = os.path.expanduser(path)
path = os.path.expandvars(path)
# check for this folder and start going up
dir_part, dir_name = os.path.split(path)
dirs = dir_part.split("/")
while len(dirs) > 0:
fullpath = "{}/{}".format("/".join(dirs), dir_name)
logging.debug("checking for dir {}".format(fullpath))
if os.path.exists(fullpath):
print("{}".format(fullpath))
break
# remove last element
dirs.pop(len(dirs) - 1)
print_message_terminator()
def locate(cmd):
"""
attempt to locate file with possible version number
"""
# {"command": "locate", "path": "/c/LLVM/bin", "name": "clangd", "ext": "exe", "versions": ["15","14"]}
path = cmd["path"]
path = os.path.expanduser(path)
path = os.path.expandvars(path)
# append $PATH content
path = "{}{}{}".format(path, os.path.pathsep, os.path.expandvars("$PATH"))
paths = path.split(os.path.pathsep)
name = cmd["name"]
ext = cmd["ext"]
versions_arr = cmd["versions"]
logging.debug(
"locate: searching for: {}, using paths: {}".format(name, paths)
)
for p in paths:
fullpath = locate_in_path(name, p, versions_arr, ext)
if len(fullpath) > 0:
logging.debug("locate: match found: {}".format(fullpath))
print(fullpath)
break
logging.debug("locate: No match found :(")
print_message_terminator()
def main_loop():
"""
accept input from the user and process the command
"""
parser = argparse.ArgumentParser(description="codelite-remote helper")
parser.add_argument(
"--context",
dest="context",
help="execution context string",
required=True,
)
args = parser.parse_args()
# load the configruration file
# it should be located next to this file
curdir = os.path.dirname(__file__)
log_file = "{}/codelite-remote.{}.log".format(curdir, args.context.lower())
# configure the log module
logging.basicConfig(
filename=log_file,
format="%(asctime)s: {}: %(levelname)s: %(message)s".format(
args.context.upper()
),
level=logging.ERROR,
)
logging.info("started")
logging.info("current working directory is set to: {}".format(curdir))
load_configuration()
# interactive mode
handlers = {
"ls": on_find_files,
"find": on_find_in_files,
"exec": on_exec,
"write_file": write_file,
"locate": locate,
"find_path": on_find_path,
"list_lsps": on_list_lsps,
"replace": on_replace_in_files,
}
logging.info("codelite-remote started")
error_count = 0
while True:
try:
text = input()
text = text.strip()
if text == "exit" or text == "bye" or text == "quit" or text == "q":
logging.info("Bye!")
exit(0)
if len(text) == 0:
continue
# split the command line by spaces
logging.info("processing command: {}".format(text))
command = json.loads(text)
func = handlers.get(command["command"], None)
if func is not None:
func(command)
else:
logging.error("unknown command '{}'".format(command["command"]))
except Exception as e:
error_count += 1
print(e)
logging.warning(e)
if error_count == 10:
logging.error("Too many errors. Exiting!")
exit(1)
break
def main():
main_loop()
if __name__ == "__main__":
main()