-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
1398 lines (1024 loc) · 47.3 KB
/
main.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
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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os #temp file removal and path splitting
import math #pretty size calcs and string collapsing
import shlex #shell arg escaping
import string #random string creation
import random #random string creation
import sublime
import tempfile
import threading #stderr consuming
import subprocess #popen
import sublime_plugin
from enum import Enum
"""
* Hey there!
* Welcome to my plugin.
* This file contains all of the python code for both the view handlers and input pallet command handlers.
* Here's how I recommend reading/learning this code.
*
* The bottom of this file contains the ViewEventListener and TextCommand which is where the magic happens.
* I'd start there.
* The ViewEventListener handles saving and modifying the view while the TextCommand handles loading the view's contents.
*
* The middle of this file has the Input Pallet stuff which is best read starting with the serverInputHandler and then the pathInputHandler.
* The other InputHandlers are for the extra actions (glob, new, and options).
* Right below the handlers is the open_file_over_ssh command which can be run manually (e.g. from a keybinding) for personal automation.
*
* The top of this file includes ssh and popen args which contain the multiplexing information.
* The custom SshShell class below those functions handles the Input Pallet's persistent ssh connection.
"""
SETTINGS_FILE = "OpenFileOverSSH.sublime-settings"
isWindows = (sublime.platform() == "windows")
viewToShell = {} #Maps view.id() to an SshShell. Allows multiple files to be opened using the same SshShell
#gets the required startup info for Popen
def getStartupInfo():
#On Windows, the command shell is opened while the Popen command is running and this fixes that
startupinfo = None
if isWindows:
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
return startupinfo
#makes the appropriate ssh args using the settings file and arguments
def getSshArgs(*, port=None):
settings = sublime.load_settings(SETTINGS_FILE)
args = ["-T"] #Non-interactive mode. While non-interactive will be the default, we'll get an unable to allocate tty error message without this
if port not in (None, 0, ""):
args.extend(["-p", str(port)])
if not settings.get("useOpenSshConfigArgs", True):
return args
#no user input
args.extend(["-o", "BatchMode=yes"]) #Batch mode is StrictHostKeyChecking=yes (as opposed to ask) and PreferredAuthentications=publickey, i.e. no user input
#host keys
keyChecking = settings.get("hostKeyChecking", None)
if keyChecking != None:
if isinstance(keyChecking, bool) or keyChecking in ["yes", "no", "accept-new"]:
args.extend(["-o", f"StrictHostKeyChecking={keyChecking}"])
if not keyChecking or keyChecking == "no":
args.extend(["-o", "UserKnownHostsFile=/dev/null"]) #don't save keys if key checking is disabled
else:
print(f"OpenFileOverSSH: Unrecognized hostKeyChecking setting ({keyChecking}), falling back to default")
#timeout
timeout = settings.get("timeout", 7)
if timeout != None:
if not (isinstance(timeout, int) or isinstance(timeout, str) and timeout.isdecimal()):
print(f"OpenFileOverSSH: Unrecognized timeout setting ({timeout}), falling back to default")
timeout = 7
args.extend(["-o", f"ConnectTimeout={timeout}"]) #not specifying this uses system tcp timeout
#multiplexing
persist = settings.get("multiplexing", "5m" if not isWindows else False) #OpenSSH_for_Windows (as of 8/2024) does not support multiplexing
if persist not in [None, False, 0, "0"]:
if isinstance(persist, bool) and persist: #True == 1 so must check if its a bool
persist = "5m"
if not (isinstance(persist, int) or isinstance(persist, str) and (persist.isdecimal() or persist[-1] in ["m", "s"] and persist[:-1].isdecimal())):
print(f"OpenFileOverSSH: Unrecognized multiplexing setting ({persist}), falling back to default")
persist = "5m"
#Using %C to both escape special characters and obfuscate the connection details
#Auto creates a new master socket if it doesn't exist
args.extend(["-o", "ControlPath=~/.ssh/SOFOS_cm-%C", "-o", "ControlMaster=auto", "-o", f"ControlPersist={persist}"])
return args
#makes an error string for an ssh error. sshStderr can be string or bytes
def makeErrorText(title, sshRetCode, sshStderr):
if isinstance(sshStderr, bytes) or isinstance(sshStderr, bytearray):
sshStderr = sshStderr.decode()
error = sshStderr and sshStderr.replace("\r", "").rstrip("\n") #ssh's output to stderr has line endings of CRLF per ssh specs. Remove trailing new line too
errType = "ssh" if sshRetCode == 255 or sshRetCode == None else "posix signal" if sshRetCode < 0 else "remote"
if error:
msg = f"{title}.\n\nCode: {sshRetCode} ({errType})\nError: {error}"
lower = error.casefold()
if errType == "ssh":
if "host key verification failed" in lower:
msg += "\n\nSSH to this server with your terminal to verify the host key or change the hostKeyChecking setting."
if "permission denied" in lower:
msg += "\n\nYou must setup ssh public key authentication with this server for this plugin to work."
if "timed out" in lower:
msg += "\n\nThe timeout time can be changed in this plugin's settings if needed."
if "getsockname failed: bad file descriptor" in lower and isWindows:
msg += "\n\nThis is likely from SSH not supporting multiplexing on windows. You can disable multiplexing in the settings file."
return msg
else:
return f"{title}.\nAn unknown {errType} error occurred.\nError Code: {sshRetCode}"
#handles the input pallet's ssh shell
class SshShell():
"""
* all methods of this class including the constructor are blocking accept for isAlive()
* after the constructor returns, ssh has either errored or is connected to remote and ready to receive commands
"""
setupCmds = [
"export LC_TIME=POSIX" #set ls -l to output a standardized time format
]
def __init__(self, userAndServer, port=None):
self.shell = subprocess.Popen(["ssh", *getSshArgs(port=port), userAndServer], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=getStartupInfo())
_, code, _ = self.runCmd("; ".join(self.setupCmds)) #read past all login information and run the setupCmds; will block until completed or error
"""
* Theoretically if ret is false, isAlive should also be false.
* However on windows this is not always the case.
* For example, on initial ssh error (host key, password auth, multiplexing) in windows:
* ret is false because the read() returned EOF
* isAlive() is true (because ssh hasn't exited yet??)
* if this isn't caught, the next write()/flush() will error with broken pipe (which is EINVAL on python windows)
* Leave it up to windows to make code complicated :(
"""
if self.isAlive() and code != 255:
self.thread = threading.Thread(target=self.shell.stderr.read, daemon=True) #consume sterr so a full pipe doesn't block our process
self.thread.start()
self.error = None
else:
self.error = self.shell.stderr.read().decode().replace("\r", "").rstrip("\n") #ssh's output to stderr has line endings of CRLF per ssh specs. Remove trailing new line too
if self.isAlive(): #ensure the process is dead (in case we got here through ret being False); this is needed because isAlive is used to check for errors
self.close(timeout=0.25)
@staticmethod
def quote(str): #shlex.quote but an empty string stays empty
return str and shlex.quote(str)
@property
def retCode(self):
return self.shell.returncode
@classmethod
def _genSeekingStr(cls):
return "A random string for seeking" + ("".join([random.choice(string.ascii_uppercase + string.digits) for _ in range(30)]))
def isAlive(self):
return self.shell.poll() == None
def runCmd(self, cmd, splitLines=True, decode=True, *, throwOnSshErr=False): #returns: (stdout, retCode, stderr)
"""
* As of right now, stderr will usually be None to indicate unable to read stderr
*
* Until this function can actually return stderr, throwOnSshErr will be available
* When True, this function will display an error message and raise an exception if an Ssh Error (i.e. connection dropped) occurs
* Use this to avoid needing to error check in calling code
"""
#write
seekingString = self._genSeekingStr()
if cmd != "":
cmd += "; "
cmd += f"printf \"\\n$?\\n{seekingString}\\n\"\n" #printf "\n retCode \n seekingStr \n"
seekingString = seekingString.encode()
try:
self.shell.stdin.write(cmd.encode())
self.shell.stdin.flush()
except (BrokenPipeError, OSError) as e: #will catch closed pipe errors if ssh has terminated (BrokenPipeError on unix, OSError EINVAL on windows)
self.shell.poll() #set returncode if its available (on windows its prolly not)
if throwOnSshErr:
sublime.error_message(makeErrorText("Lost connection to the server (write)", self.retCode or 255, str(e)))
raise Exception("Ssh Connection Drop")
stderr = "Connection lost: " + str(e)
return ([] if splitLines else "" if decode else b"", self.retCode or 255, stderr if decode else stderr.encode())
#read
lines = []
while True:
line = self.shell.stdout.readline()
if len(line) == 0: #EOF i.e. error
self.shell.poll()
if throwOnSshErr:
sublime.error_message(makeErrorText("Lost connection to the server (read)", self.retCode or 255, "Encountered EOF"))
raise Exception("Ssh Connection Drop")
stderr = "Connection lost: encountered EOF during read"
return ([] if splitLines else "" if decode else b"", self.retCode or 255, stderr if decode else stderr.encode())
if line[:-1] == seekingString:
break;
if splitLines:
line = line.rstrip(b"\n")
if decode:
line = line.decode()
lines.append(line)
#return
retCode = int(lines.pop())
if len(lines[-1]) == (not splitLines): #remove the extra \n added with printf
lines.pop()
elif not splitLines:
lines[-1] = lines[-1][:-1]
return (lines if splitLines else ("" if decode else b"").join(lines), retCode, None)
def close(self, timeout=None):
#close/kill ssh
if self.isAlive():
try:
self.shell.stdin.write(b"exit\n")
self.shell.stdin.flush()
except (BrokenPipeError, OSError):
pass
try:
self.shell.stdin.close() #will also close the ssh process
except (BrokenPipeError, OSError):
pass
try:
self.shell.wait(timeout)
except TimeoutExpired:
print("OpenFileOverSSH: ssh exit timed out, killing...")
self.ssh.terminate()
try:
self.shell.wait(timeout)
except TimeoutExpired:
self.shell.kill()
self.shell.wait()
if self.retCode != 0:
print("OpenFileOverSSH: ssh finished with return code %d" % self.shell.returncode)
#clean up
try:
self.thread.join() #join thread to free up resources
except AttributeError: #no thread to join
pass
def __del__(self):
self.close()
#shared arguments for command pallet handlers. Acts as a dictionary with special path and session settings features
class Argz(dict):
settings = sublime.load_settings(SETTINGS_FILE)
SESS_SETTINGS_DATA = [
("pathChecking", True),
("hiddenFiles", "showHiddenFiles", False),
("actions", ["glob", "new"])
]
def __init__(self, **kargs):
self.kargs = kargs
super().__init__(**kargs) #extend dict
#session settings
self.settings = {}
for item in self.SESS_SETTINGS_DATA:
pref = self.__class__.settings.get(item[0 if len(item) == 2 else 1])
self.settings[item[0]] = pref if pref != None else item[-1]
self.settings["actions"] = [action.lower() for action in self.settings["actions"]]
self._path = [] #array of tuples or strings containing path components (folders or files); each item is one InputHandler
self._strPath = "" #string representation of path
self._flatLen = 0 #length of flattened _path
self._oldPath = self.__class__.settings.setdefault("path", [])[:] #auto completion flat path
@property
def _flatPath(self): #flattened self._path
return self._oldPath[:self._flatLen]
def reset(self):
self.clear() #clear the dictionary
self.__init__(**self.kargs)
"""
* This class is all about path and strPath
* strPath could just be created from path every time using a flatten method,
* but instead this uses caching and does not allow direct editing of path
* Use path: append, pop, and peek to interact with path
* Use completion and completionsToPastPath for path auto completion
* Use savePath to write the flattened path to SETTINGS_FILE for use in next session's auto completion
"""
@property
def strPath(self):
return self._strPath
def pathAppend(self, val):
self._path.append(val)
try:
self._strPath += "".join(val)
except TypeError: #val is not a string
pass
val = list(val) if isinstance(val, tuple) else [val,]
if self._oldPath[self._flatLen:self._flatLen+len(val)] != val: #keep _oldPath up to date with current selections if they differ from previous ones
self._oldPath[self._flatLen:] = val
if self._oldPath == self.__class__.settings["path"][:len(self._oldPath)]: #if _oldPath starts to match settings[path] again, go back to using settings[path]
self._oldPath = self.__class__.settings["path"][:]
self._flatLen += len(val)
def pathPop(self):
popped = self._path.pop()
try:
self._strPath = self._strPath[:-len("".join(popped))]
except TypeError:
pass
self._flatLen -= len(popped) if isinstance(popped, tuple) else 1
return popped
def pathPeek(self):
return self._path[-1] if self._path else None
@property
def completion(self): #returns the default next path component, which is the previously selected path (either from a past session or a pathPop())
try:
return self._oldPath[self._flatLen]
except IndexError:
return None
def completionsToPastPath(self): #returns the tuple needed for the current path to equal the previous session's path, or None if no such append()-able tuple exists
new = self._flatPath
old = self.__class__.settings["path"]
if new == old[:len(new)]:
return tuple(old[len(new):])
return None
def savePath(self):
self.__class__.settings["path"] = self._flatPath
sublime.save_settings(SETTINGS_FILE)
#input pallet server input
class serverInputHandler(sublime_plugin.TextInputHandler):
def __init__(self, argz):
super().__init__()
self.argz = argz
self.ssh = None
self.settings = sublime.load_settings(SETTINGS_FILE)
@staticmethod
def checkSyntax(text): #false (0): invalid, 1: user/server, 2: server, 3: port, 4: folder path, 5: file path
if not (
len(text) >= 2 and
text.count(":") == 1 or text.count(":") == 2 and text[text.index(":")+1:text.rindex(":")].isdecimal() and
("@" not in text or text.count("@") == 1 and text[0] != "@" and text.index("@") < text.index(":") - 1)
):
return False
if text[-1] == ":":
return 3 if text.count(":") > 1 else 1 if "@" in text else 2
else:
return 4 if text[-1] == "/" else 5
#gray placeholder text
def placeholder(self):
return "[email protected]:"
#previous value
def initial_text(self):
return self.settings.get("server", "")
#syntax check
def preview(self, text):
type = self.checkSyntax(text)
if not type:
return "Invalid Server Syntax"
ret = "Server Input Valid"
if type == 2:
ret += " for Default Username"
elif type == 3:
ret += " with Specific Port"
elif type == 4:
ret += "; Open File Browser at Folder"
elif type == 5:
ret += "; Open/Create File"
return ret
#check server
def validate(self, text):
type = self.checkSyntax(text)
if not type:
return False
if type == 5:
self.ssh = None #ensure there is no shell e.g. if the user connects to a different server before a type 5
return True
server = text[:text.index(":")]
port = text[text.index(":")+1:text.rindex(":")] #empty string if no port
ssh = SshShell(server, port)
if not ssh.isAlive(): #check if not dead
#the dialog looks kinda ugly, but I can't think of a better way
sublime.error_message(makeErrorText(f"Could not connect to {server}", ssh.retCode, ssh.error))
return False
if type == 4 and self.argz.settings["pathChecking"]:
path = text[text.rindex(":") + 1:]
echoCode = "printf \"$?\\n\""
[e, d], x, _ = ssh.runCmd(f"test -e {ssh.quote(path.rstrip('/'))}; {echoCode}; test -d {ssh.quote(path)}; {echoCode}; test -x {ssh.quote(path)}")
if e == "1": #greater than 1 means test errored
msg = "No such file or directory"
elif d == "1":
msg = "Not a directory"
elif x == 1:
msg = "Permission denied"
else:
msg = None
if msg:
sublime.error_message(f"Unable to access (open) '{path}'\n({msg})")
return False
self.ssh = ssh #only save if it'll be used i.e. let the shell close now if it's not used
return True
#save value
def confirm(self, text):
self.settings.set("server", text)
sublime.save_settings(SETTINGS_FILE)
if "server" in self.argz:
self.argz.reset() #makes the most sense to have connecting to a server start a new session
sep = text.index(":")
sep2 = text.rindex(":")
self.argz["server"] = text[:sep]
self.argz["port"] = text[sep+1:sep2]
self.argz["sshShell"] = self.ssh
if text[-1] == "/": #type 3
self.argz.pathAppend(tuple(comp + "/" for comp in text[sep2 + 1:].split("/")[:-1]))
elif text[-1] != ":": #type 4
self.argz["paths"] = [text[sep2 + 1:]]
#close ssh
def cancel(self):
if self.ssh:
self.ssh.close()
#file selection
def next_input(self, args):
return pathInputHandler(self.argz) if not "paths" in self.argz else None
#input pallet action glob input
class globInputHandler(sublime_plugin.TextInputHandler):
def __init__(self, argz):
super().__init__()
self.argz = argz
self.ssh = argz["sshShell"]
self.settings = sublime.load_settings(SETTINGS_FILE)
@staticmethod
def isSyntaxOk(text):
globs = text.split(" ")
for glob in globs:
if not "*" in glob:
return False #every space-separated pattern must have a *
return True
def getMatchingPaths(self, text):
path = self.ssh.quote(self.argz.strPath)
globs = [path + glob for glob in text.split()]
return [path for path in self.ssh.runCmd(f"/bin/ls -1Lpd -- {' '.join(globs)}", throwOnSshErr=True)[0] if not path.endswith("/")] #will return full paths
#gray placeholder text
def placeholder(self):
return "*.c h*.h"
#previous value
def initial_text(self):
return self.settings.get("glob", "")
#syntax check
def preview(self, text):
if not self.isSyntaxOk(text):
return "Invalid Glob Syntax"
return "Glob Input Valid"
#check matches
def validate(self, text):
if self.isSyntaxOk(text):
if len(self.getMatchingPaths(text)) > 0:
return True
sublime.error_message("No files were found matching the pattern{} '{}'".format("s" if len(text.split(" ")) > 1 else "", text)) #the dialog looks ugly, but I can't think of a better way
return False
#update values
def confirm(self, text):
self.argz.savePath()
self.settings.set("glob", text)
sublime.save_settings(SETTINGS_FILE)
self.argz["paths"] = self.getMatchingPaths(text)
#pop()
def cancel(self):
self.argz.pathPop() #pop off the * that got us here
#all done
def next_input(self, args):
return None
#input pallet action new file input
class newInputHandler(sublime_plugin.TextInputHandler):
def __init__(self, argz):
super().__init__()
self.argz = argz
self.ssh = argz["sshShell"]
@staticmethod
def splitPath(text): #returns (path, file, folders)
if len(text) == 0:
return (None, None, None)
path = text.split("/")
file = path[-1]
folders = path[:-1]
if "" in folders: #disallow multiple or initial slashes
return (None, file, None)
path = tuple(folder + "/" for folder in folders) + (file,)
folders = "".join(path[:-1])
return (path, file, folders)
def fileExists(self, file):
path = self.ssh.quote(self.argz.strPath + file)
return len(self.ssh.runCmd("/bin/ls -d -- " + path, throwOnSshErr=True)[0]) > 0
#gray placeholder text
def placeholder(self):
return "newFolder/newFile.txt"
#path check
def preview(self, text):
path, file, folders = self.splitPath(text)
if path == None:
return None if file == None else "Invalid Path"
#New File {} in New Folder(s) {}
text = ""
if len(file) > 0:
text = f"New File {{{file}}}" + (" in " if len(folders) > 0 else "")
if len(folders) > 0:
text += f"New Folder{'s' if len(path) > 2 else ''} {{{folders}}}"
return text
#check new file/folder
def validate(self, text):
path = self.splitPath(text)[0]
if path != None:
path = path[0].rstrip("/")
if not self.fileExists(path):
return True
#It technically doesn't matter if the file/folder already exists cause it'll get opened correctly; but since the user is expecting to make a new file/folder I'll let them know.
sublime.error_message(f"The file/folder {{{path}}} already exists.")
return False
#update values
def confirm(self, text):
#because we create the new folder in this function, that makes re-editing this input handler difficult
# which means that bringing the user into the newly created folder doesn't work because the user might try to go back up the input handler stack
#so instead of dealing with that, I'll just pop this handler off the stack and let the user select the new folders themselves
#I will however set the previous selections (in the settings file) to the new folders so at least they'll be the defaults
path, file, folders = self.splitPath(text)
self.argz.pathPop() #remove the new file that got us here
#make the folders
if len(folders) > 0:
self.ssh.runCmd("mkdir -p -- " + self.ssh.quote(self.argz.strPath + folders), throwOnSshErr=True)
self.argz.pathAppend(path[:-1]) #add the new folders to the path
#open the file
if len(file) > 0:
self.argz.pathAppend(pathInputHandler.Action.NEW) #make it look like the user selected new in the new (or old) folder(s)
self.argz.savePath()
self.argz["paths"] = [self.argz.strPath + file]
else:
self.argz.savePath() #set the previous selection(s) to the new folders
self.argz.pathPop() #remove the new folders in the current path
#pop()
def cancel(self):
self.argz.pathPop() #pop off the New File that got us here
#all done
def next_input(self, args):
file = self.splitPath(args["new"])[1]
return None if len(file) > 0 else sublime_plugin.BackInputHandler()
#input pallet action session options
class optionsInputHandler(sublime_plugin.ListInputHandler):
"""
* This seems like overkill for toggling hidden files (it's only real use) but it has to be something like this.
* Toggling hidden files has to trigger another call to list_items() which Sublime does not provide an api for.
* list_items() is only called when a handler is first shown or when the next handler is popped off the stack.
* So this options handler will be that handler that is popped off the stack.
*
* Another option would be to push a duplicate listInputHandler on the stack when hidden files are toggled.
* Unfortunately this messes up the handler stack with a duplicate handler that causes issues when popping particularly with the .. directory.
"""
class Option(str, Enum):
#action has to be a string function name because optionsInputHandler doesn't exist as a type yet.
#...forward declaration issues. Literally the one bad thing about python...rip
HIDDEN = (
"Toggle Hidden Files",
"dot files",
".",
lambda settings: f"{'Hide' if settings['hiddenFiles'] else 'Show'} Hidden Files (dot files)",
"toggleHiddenFiles"
)
PCHECKING = (
"Toggle Path Checking",
"error time",
"✓",
lambda settings: f"Show Errors {'After' if settings['pathChecking'] else 'Before'} Selection",
"togglePathChecking"
)
def __new__(cls, text, annotation, kLetter, preview, action):
obj = str.__new__(cls, text)
obj._value_ = text
obj.annotation = annotation
obj.kLetter = kLetter
obj.preview = preview
obj.action = action
return obj
ACTIONS = ("glob", "new", "lastDir", "pwd", "sysI") #addable actions
@staticmethod
def toggleHiddenFiles(settings):
settings["hiddenFiles"] = not settings["hiddenFiles"]
@staticmethod
def togglePathChecking(settings):
settings["pathChecking"] = not settings["pathChecking"]
def __init__(self, argz):
super().__init__()
self.settings = argz.settings
#show all Options
def list_items(self):
kColor = pathInputHandler.Kind.ACTION[0]
kOther = pathInputHandler.Kind.ACTION[2:]
arr = [sublime.ListInputItem(option.value, option.value, annotation=option.annotation, kind=(kColor, option.kLetter) + kOther) for option in self.Option]
for i, action in enumerate(self.ACTIONS):
if action.lower() not in self.settings["actions"]:
arr.append(sublime.ListInputItem(f"Add {action}", i, annotation="enable action", kind=pathInputHandler.Kind.ACTION))
return arr
#display preview
def preview(self, value):
if isinstance(value, str):
preview = self.Option(value).preview
return preview(self.settings) if callable(preview) else preview
if isinstance(value, int):
return f"Enable the {self.ACTIONS[value]} action"
#run action
def confirm(self, value):
if isinstance(value, str):
try:
getattr(self, self.Option(value).action)(self.settings)
except AttributeError:
print(f"OpenFileOverSSH: Bad Option function name: {self.Option(value).action}")
else:
self.settings["actions"].append(self.ACTIONS[value].lower())
#pop back
def next_input(self, args):
return sublime_plugin.BackInputHandler()
#input pallet path input
class pathInputHandler(sublime_plugin.ListInputHandler):
parentDir = "../"
class Kind(tuple, Enum):
FILE = (sublime.KindId.COLOR_YELLOWISH, "f", "")
FOLDER = (sublime.KindId.COLOR_CYANISH, "F", "")
ACTION = (sublime.KindId.COLOR_PURPLISH, "-", "")
INFO = (sublime.KindId.COLOR_PURPLISH, "ⓘ", "")
CONFUSED = (sublime.KindId.COLOR_ORANGISH, "?", "")
ERROR = (sublime.KindId.COLOR_REDISH, "!", "")
#ListInputItem value must be a sublime.Value so this class helps store InputHandlers in the ListInputItem
class Action(int, Enum):
NOOP = 0, "", None
GLOB = 1, "Open Multiple Files with a Glob", globInputHandler
NEW = 2, "Make a New File or Folder Here", newInputHandler
OPTIONS = 3, lambda self: f"Edit Session Options such as {'hiding' if self.argz.settings['hiddenFiles'] else 'showing'} hidden files", optionsInputHandler
def __new__(cls, val, preview, handler):
obj = int.__new__(cls, val)
obj._value_ = val
obj.preview = preview
obj.handler = handler
return obj
def __init__(self, argz):
super().__init__()
self.argz = argz
self.ssh = argz["sshShell"]
@staticmethod
def isPath(value):
#its assumed tuples only contains strings (i.e. no actions in tuples)
return isinstance(value, (str, tuple, list)) #a tuple is not a sublime.Value (JSON) so tuples get converted to lists
@staticmethod
def isFolder(pathVal):
strPath = pathVal[-1] if isinstance(pathVal, (tuple, list)) else pathVal
return strPath.endswith("/")
@staticmethod
def prettySize(bytes):
if bytes == 0:
return "0"
sizes = ("B", "K", "M", "G", "T", "P", "E", "Z", "Y") #future proof lol
i = int(math.floor(math.log(bytes, 1024))) #uses powers of 2 e.g. MiB
p = math.pow(1024, i)
s = bytes / p
return f"{int(round(s)) if s.is_integer() else round(s, 1)}{sizes[i]}"
@staticmethod
def collapse(str, maxLen, splitChar=None): #turns "text,text,text" into "text,...,text"
if len(str) <= maxLen:
return str #only str
if maxLen <= 3:
return "." * maxLen #only dots
maxLen -= 3
if not splitChar or str.find(splitChar) == -1:
return str[:math.ceil(maxLen/2)] + "..." + str[len(str) - (maxLen//2):] #even split favoring start
start = str[:str.find(splitChar) + 1]
if len(start) >= maxLen:
return str[:maxLen] + "..." #only start
end = str[str.rfind(splitChar):]
if len(start) + len(end) >= maxLen:
return start + "..." + end[-(maxLen - len(start)):] #include end but favor start
return str[:maxLen - len(end) + 1] + "..." + end #start and onward but including end (maybe should be even split?)
#ls, actions, and initial selection
def list_items(self):
#setup
lessXSI = self.argz.get("lessXSI")
path = self.ssh.quote(self.argz.strPath)
cmd = f"/bin/ls -1Lp {'-lgo' if not lessXSI else ''} {'-a' if self.argz.settings['hiddenFiles'] else ''} -- {path}"
files, retCode, err = self.ssh.runCmd(cmd)
if not lessXSI:
files = files[1:] #skip the total line
items = []
hasFile = False
self.error = None
#check ls
if retCode != 0 and len(files) == 0: #ls can fail on one file, return a failed code, and list the other files normally. Usually caught by lsConfused logic
self.error = err or self.ssh.runCmd(f"{cmd} 2>&1", False)[0]
msg = f"ERROR: Failed to list files in {path if path else '~'} : "
lower = self.error.casefold()
if retCode == 255 or retCode < 0:
sublime.error_message(makeErrorText("Lost connection to the server", retCode, self.error))
msg += "Connection lost"
elif "not a directory" in lower:
msg += "Not a directory"
elif "no such file or directory" in lower:
msg += "No such file or directory"
elif "permission denied" in lower:
msg += "Permission denied"
elif ("unrecognized option" in lower or "invalid option" in lower) and not lessXSI:
self.argz["lessXSI"] = True
return self.list_items()
else:
msg += "Unrecognized error"
print("OpenFileOverSSH: ls failed:", self.error)
self.error = f"Exit code {retCode}; " + self.error
return [sublime.ListInputItem(msg, None, annotation="Error", kind=self.Kind.ERROR)]
#do
for file in files:
#split
fileInfo = file.split(maxsplit=6) if not lessXSI else [""]*6 + [file] #perms, links, bytes, dt1, dt2, dt3, name; requires LC_TIME=POSIX
lsConfused = False
#check
if len(fileInfo) == 5 and fileInfo[1] == fileInfo[2] == fileInfo[3] == "?":
lsConfused = True
elif len(fileInfo) != 7:
if not self.error:
print(f"OpenFileOverSSH: Unrecognized ls output:\n{chr(10).join(files)}") #char(10) is \n cause can't use a \ in an f string expr
self.error = f"Unrecognized file info (skipping): {file} : {fileInfo}"
print(f"OpenFileOverSSH: {self.error}")
continue
#parse
file = fileInfo[-1]
if file == "./":
continue #pointless to select current directory
isFolder = self.isFolder(file)
if isFolder: #folder
try:
size = int(fileInfo[1]) - 2 #number of sub-directories
except ValueError:
size = "?"
annotation = f"->{size}"
kind = self.Kind.FOLDER
else: #file
try:
annotation = self.prettySize(int(fileInfo[2]))
except ValueError:
annotation = fileInfo[2]
kind = self.Kind.FILE
hasFile = True
if lsConfused: #confused e.g. link with deleted source (will trigger the file branch above)
kind = self.Kind.CONFUSED
#item
items.append(sublime.ListInputItem(file, file, annotation=annotation if not lessXSI else "", kind=kind))
#warning
if self.error:
items.insert(0, sublime.ListInputItem("WARNING: A Parsing Error Occurred and some Entries are Missing or Wrong", None, annotation="Warning", kind=self.Kind.ERROR))
#actions
if self.argz.pathPeek() == None:
items.append(sublime.ListInputItem("/", ("/",), annotation="Root Dir", kind=self.Kind.ACTION)) #tuple to disable ../ popping
for action in self.argz.settings["actions"]: #I could make a dictionary mapping strings to functions....or just do this
if action == "glob":
if hasFile:
items.append(sublime.ListInputItem("*", self.Action.GLOB, annotation="Pattern", kind=self.Kind.ACTION))
elif action == "new":
items.append(sublime.ListInputItem("New", self.Action.NEW, annotation="Create", kind=self.Kind.ACTION))
elif action == "lastdir":
comps = self.argz.completionsToPastPath()
comps = comps[:-1] if comps and not (self.isPath(comps[-1]) and self.isFolder(comps[-1])) else comps #remove file/action if needed
if comps:
comps = comps if len(comps) > 1 else comps[0] #de-tuple if needed for ../ handling