Path: blob/master/src/smc_pyutil/smc_pyutil/smc_close.py
Views: 285
#!/usr/bin/python1# This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.2# License: AGPLv3 s.t. "Commons Clause" – read LICENSE.md for details34from __future__ import absolute_import, print_function5MAX_FILES = 10067import json, os, sys89home = os.environ['HOME']1011if 'TMUX' in os.environ:12prefix = '\x1bPtmux;\x1b'13postfix = '\x1b\\'14else:15prefix = ''16postfix = ''171819def process(paths):20v = []21if len(paths) > MAX_FILES:22sys.stderr.write(23"You may close at most %s at once using the open command; truncating list\n"24% MAX_FILES)25paths = paths[:MAX_FILES]26for path in paths:27if not path:28continue29if not os.path.exists(path) and any(c in path for c in '{?*'):30# If the path doesn't exist and does contain a shell glob character which didn't get expanded,31# then don't try to just create that file. See https://github.com/sagemathinc/cocalc/issues/101932sys.stderr.write("no match for '%s', so not closing\n" % path)33continue34if not os.path.exists(path):35# Doesn't exist, so doesn't matter36continue3738if not path.startswith('/'):39# we use pwd instead of getcwd or os.path.abspath since we want this to40# work when used inside a directory that is a symlink! I could find41# no analogue of pwd directly in Python (getcwd is not it!).42path = os.path.join(os.popen('pwd').read().strip(), path)4344# determine name relative to home directory45if path.startswith(home):46name = path[len(home) + 1:]47else:48name = path4950# Is it a file or directory?51if os.path.isdir(path):52v.append({'directory': name})53else:54v.append({'file': name})5556if v:57mesg = {'event': 'close', 'paths': v}58ser = json.dumps(mesg, separators=(',', ':'))59print(prefix + '\x1b]49;%s\x07' % ser + postfix)606162def main():63if len(sys.argv) == 1:64print("Usage: close [path names] ...")65print(66"Closes each file (or directory) in the CoCalc web-based editor from the shell."67)68print("If the named file doesn't exist, it is created.")69else:70process(sys.argv[1:])717273if __name__ == "__main__":74main()757677