Path: blob/master/src/smc_pyutil/smc_pyutil/smc_open.py
Views: 285
#!/usr/bin/python12# Maximum number of files that user can open at once using the open command.3# This is here to avoid the user opening 100 files at once (say)4# via "open *" and killing their frontend.5from __future__ import absolute_import6from __future__ import print_function7MAX_FILES = 1589# ROOT_SYMLINK is a symlink to / from somehow in the user's home directory.10# This symlink should get created as part of project startup, so that we can11# treat all paths in the filesystem as being contained in the user's home direoctory.12# This may be dumb but simplifies our code and is assumed in some places.13# ~$ ls -ls .smc/root14# 0 lrwxrwxrwx 1 user user 1 Oct 22 23:00 .smc/root -> /15ROOT_SYMLINK = '.smc/root'1617import json, os, sys1819home = os.environ['HOME']2021if 'TMUX' in os.environ:22prefix = '\x1bPtmux;\x1b'23postfix = '\x1b\\'24else:25prefix = ''26postfix = ''272829def process(paths):30v = []31if len(paths) > MAX_FILES:32sys.stderr.write(33"You may open at most %s at once using the open command; truncating list\n"34% MAX_FILES)35paths = paths[:MAX_FILES]36for path in paths:37if not path:38continue39if not os.path.exists(path) and any(c in path for c in '{?*'):40# If the path doesn't exist and does contain a shell glob character which didn't get expanded,41# then don't try to just create that file. See https://github.com/sagemathinc/cocalc/issues/101942sys.stderr.write("no match for '%s', so not creating\n" % path)43continue44if not os.path.exists(path):45if '/' in path:46dir = os.path.dirname(path)47if not os.path.exists(dir):48sys.stderr.write("creating directory '%s'\n" % dir)49os.makedirs(dir)50if path[-1] != '/':51sys.stderr.write("creating file '%s'\n" % path)52from . import new_file53new_file.new_file(54path55) # see https://github.com/sagemathinc/cocalc/issues/14765657if not path.startswith('/'):58# we use pwd instead of getcwd or os.path.abspath since we want this to59# work when used inside a directory that is a symlink! I could find60# no analogue of pwd directly in Python (getcwd is not it!).61path = os.path.join(os.popen('pwd').read().strip(), path)6263# Make name be the path to the file, **relative to home directory**64if path.startswith(home):65name = path[len(home) + 1:]66else:67# use the / symlink -- see https://github.com/sagemathinc/cocalc/issues/418868name = ROOT_SYMLINK + path6970# Is it a file or directory?71if os.path.isdir(path):72v.append({'directory': name})73else:74v.append({'file': name})7576if v:77mesg = {'event': 'open', 'paths': v}78ser = json.dumps(mesg, separators=(',', ':'))79print(prefix + '\x1b]49;%s\x07' % ser + postfix)808182def main():83if len(sys.argv) == 1:84print("Usage: open [path names] ...")85print(86"Opens each file (or directory) in the CoCalc web-based editor from the shell."87)88print("If the named file doesn't exist, it is created.")89else:90process(sys.argv[1:])919293if __name__ == "__main__":94main()959697