Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download
Views: 39561
1
#!/usr/bin/python
2
3
# Maximum number of files that user can open at once using the open command.
4
# This is here to avoid the user opening 100 files at once (say)
5
# via "open *" and killing their frontend.
6
MAX_FILES = 15
7
8
import json, os, sys
9
10
home = os.environ['HOME']
11
12
if 'TMUX' in os.environ:
13
prefix = '\x1bPtmux;\x1b'
14
postfix = '\x1b\\'
15
else:
16
prefix = ''
17
postfix = ''
18
19
def process(paths):
20
v = []
21
if len(paths) > MAX_FILES:
22
sys.stderr.write("You may open at most %s at once using the open command; truncating list\n"%MAX_FILES)
23
paths = paths[:MAX_FILES]
24
for path in paths:
25
if not path:
26
continue
27
if not os.path.exists(path) and any(c in path for c in '{?*'):
28
# If the path doesn't exist and does contain a shell glob character which didn't get expanded,
29
# then don't try to just create that file. See https://github.com/sagemathinc/cocalc/issues/1019
30
sys.stderr.write("no match for '%s', so not creating\n"%path)
31
continue
32
if not os.path.exists(path):
33
if '/' in path:
34
dir = os.path.dirname(path)
35
if not os.path.exists(dir):
36
sys.stderr.write("creating directory '%s'\n"%dir)
37
os.makedirs(dir)
38
if path[-1] != '/':
39
sys.stderr.write("creating file '%s'\n"%path)
40
import new_file
41
new_file.new_file(path) # see https://github.com/sagemathinc/cocalc/issues/1476
42
43
path = os.path.abspath(path)
44
45
# determine name relative to home directory
46
if path.startswith(home):
47
name = path[len(home)+1:]
48
else:
49
name = path
50
51
# Is it a file or directory?
52
if os.path.isdir(path):
53
v.append({'directory':name})
54
else:
55
v.append({'file':name})
56
57
if len(v) > 0:
58
mesg = {'event':'open', 'paths':v}
59
print prefix + '\x1b]49;%s\x07'%json.dumps(mesg,separators=(',',':')) + postfix
60
61
def main():
62
if len(sys.argv) == 1:
63
print "Usage: open [path names] ..."
64
print "Opens each file (or directory) in the Sagemath Cloud web-based editor from the shell."
65
print "If the named file doesn't exist, it is created."
66
else:
67
process(sys.argv[1:])
68
69
if __name__ == "__main__":
70
main()
71
72