Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/smc_pyutil/smc_pyutil/smc_close.py
Views: 285
1
#!/usr/bin/python
2
# This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
3
# License: AGPLv3 s.t. "Commons Clause" – read LICENSE.md for details
4
5
from __future__ import absolute_import, print_function
6
MAX_FILES = 100
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
20
def process(paths):
21
v = []
22
if len(paths) > MAX_FILES:
23
sys.stderr.write(
24
"You may close at most %s at once using the open command; truncating list\n"
25
% MAX_FILES)
26
paths = paths[:MAX_FILES]
27
for path in paths:
28
if not path:
29
continue
30
if not os.path.exists(path) and any(c in path for c in '{?*'):
31
# If the path doesn't exist and does contain a shell glob character which didn't get expanded,
32
# then don't try to just create that file. See https://github.com/sagemathinc/cocalc/issues/1019
33
sys.stderr.write("no match for '%s', so not closing\n" % path)
34
continue
35
if not os.path.exists(path):
36
# Doesn't exist, so doesn't matter
37
continue
38
39
if not path.startswith('/'):
40
# we use pwd instead of getcwd or os.path.abspath since we want this to
41
# work when used inside a directory that is a symlink! I could find
42
# no analogue of pwd directly in Python (getcwd is not it!).
43
path = os.path.join(os.popen('pwd').read().strip(), 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 v:
58
mesg = {'event': 'close', 'paths': v}
59
ser = json.dumps(mesg, separators=(',', ':'))
60
print(prefix + '\x1b]49;%s\x07' % ser + postfix)
61
62
63
def main():
64
if len(sys.argv) == 1:
65
print("Usage: close [path names] ...")
66
print(
67
"Closes each file (or directory) in the CoCalc web-based editor from the shell."
68
)
69
print("If the named file doesn't exist, it is created.")
70
else:
71
process(sys.argv[1:])
72
73
74
if __name__ == "__main__":
75
main()
76
77