From 789db939110ed4f193729eb93f9e8ee26e7178eb Mon Sep 17 00:00:00 2001 From: Fabien Benureau Date: Sun, 6 Dec 2015 08:41:33 +0100 Subject: [PATCH] Add platform-specific open and edit commands at init The main motivation is to provide sensible default to make the commnand "just work" without needing to fiddle with the configuration --- pubs/commands/init_cmd.py | 2 ++ pubs/config/__init__.py | 1 + pubs/config/conf.py | 36 ++++++++++++++++++++++++++++++++++++ 3 files changed, 39 insertions(+) diff --git a/pubs/commands/init_cmd.py b/pubs/commands/init_cmd.py index 0bfaa0c..6329e0e 100644 --- a/pubs/commands/init_cmd.py +++ b/pubs/commands/init_cmd.py @@ -41,6 +41,8 @@ def command(conf, args): conf['main']['pubsdir'] = pubsdir conf['main']['docsdir'] = docsdir + conf['main']['open_cmd'] = config.default_open_cmd() + conf['main']['edit_cmd'] = config.default_edit_cmd() config.save_conf(conf) Repository(conf, create=True) diff --git a/pubs/config/__init__.py b/pubs/config/__init__.py index e9d8caa..5de91fb 100644 --- a/pubs/config/__init__.py +++ b/pubs/config/__init__.py @@ -1 +1,2 @@ from .conf import get_confpath, load_default_conf, load_conf, save_conf, check_conf +from .conf import default_open_cmd, default_edit_cmd diff --git a/pubs/config/conf.py b/pubs/config/conf.py index 259e7eb..aefeda2 100644 --- a/pubs/config/conf.py +++ b/pubs/config/conf.py @@ -1,4 +1,6 @@ import os +import platform +import shutil import configobj import validate @@ -54,3 +56,37 @@ def save_conf(conf, path=None): path = get_confpath(verify=False) with open(path, 'wb') as f: conf.write(outfile=f) + +def default_open_cmd(): + """Chooses the default command to open documents""" + if platform.system() == 'Darwin': + return 'open' + elif platform.system() == 'Linux': + return 'xdg-open' + elif platform.system() == 'Windows': + return 'start' + else: + return None + +def which(cmd): + try: + return shutil.which(cmd) # available in python 3.3 + except AttributeError: + for path in ['.'] + os.environ["PATH"].split(os.pathsep): + filepath = os.path.join(path.strip('"'), cmd) + if os.path.isfile(path) and os.access(path, os.X_OK): + return filepath + return None + +def default_edit_cmd(): + """Find an available editor""" + if 'EDITOR' in os.environ: + return os.environ['EDITOR'] + elif platform.system() == 'Darwin' or 'Linux': + for editor in ['vim', 'nano', 'emacs', 'vi']: + if which(editor) is not None: + return editor + elif platform.system() == 'Windows': + return 'Notepad.exe | Out-Null' # wait for notepad to close + else: + return None