Config command has an option to edit the config file
authorFrederic Massart <fred@moodle.com>
Wed, 9 Apr 2014 12:25:46 +0000 (20:25 +0800)
committerFrederic Massart <fred@moodle.com>
Wed, 9 Apr 2014 12:25:46 +0000 (20:25 +0800)
config-dist.json
lib/commands/config.py
lib/commands/doctor.py
lib/config.py
lib/exceptions.py
lib/tools.py

index 65e9a01..f2bdc64 100644 (file)
     "recess": "/usr/local/bin/recess",
     // Path to lessc
     "lessc": "/usr/local/bin/lessc",
+    // Path to your favourite editor
+    "editor": "/usr/bin/vim",
 
     // Debug level of MDK. 'debug', 'info', 'warning', 'error' or 'critical'.
     "debug": "info",
index 054aebf..c37cb43 100644 (file)
@@ -22,7 +22,10 @@ along with this program.  If not, see <http://www.gnu.org/licenses/>.
 http://github.com/FMCorz/mdk
 """
 
+import logging
 from lib.command import Command
+from lib.tools import launchEditor, yesOrNo
+from lib.config import ConfigObject, ConfigFileCouldNotBeLoaded
 
 
 class ConfigCommand(Command):
@@ -34,6 +37,12 @@ class ConfigCommand(Command):
                 'help': 'the action to perform',
                 'metavar': 'action',
                 'sub-commands': {
+                    'edit': (
+                        {
+                            'help': 'opens the config file in an editor'
+                        },
+                        []
+                    ),
                     'flatlist': (
                         {
                             'help': 'flat list of the settings'
@@ -110,6 +119,32 @@ class ConfigCommand(Command):
         if args.action == 'list':
             self.dictDisplay(self.C.get(), 0)
 
+        elif args.action == 'edit':
+            f = self.C.userFile
+            success = None
+
+            while True:
+                tmpfile = launchEditor(filepath=f, suffix='.json')
+                co = ConfigObject()
+                try:
+                    co.loadFromFile(tmpfile)
+                except ConfigFileCouldNotBeLoaded:
+                    success = False
+                    logging.error('I could not load the file, you probably screwed up the JSON...')
+                    if yesOrNo('Would you like to continue editing? If not the changes will be discarded.'):
+                        f = tmpfile
+                        continue
+                    else:
+                        break
+                else:
+                    success = True
+                    break
+
+            if success:
+                with open(tmpfile, 'r') as new:
+                    with open(self.C.userFile, 'w') as current:
+                        current.write(new.read())
+
         elif args.action == 'flatlist':
             self.flatDisplay(self.C.get())
 
index 2ffda9c..42b0b79 100644 (file)
@@ -214,7 +214,7 @@ class DoctorCommand(Command):
         print 'Checking dependencies'
 
         hasErrors = False
-        for k in ['git', 'php', 'java', 'recess', 'lessc']:
+        for k in ['git', 'php', 'java', 'recess', 'lessc', 'editor']:
             path = self.C.get(k)
             if not path or not os.path.isfile(path):
                 print '  The path to \'%s\' is invalid: %s' % (k, path)
index 1836096..4c8032a 100644 (file)
@@ -26,7 +26,6 @@ import os
 import json
 import re
 import copy
-from exceptions import ConfigFileCouldNotBeLoaded, ConfigFileNotFound, ConfigFileCouldNotBeSaved
 
 
 class ConfigObject(object):
@@ -289,3 +288,15 @@ class Conf(Config):
         """Set a new setting"""
         super(Conf, self).set(name, value)
         self.save()
+
+
+class ConfigFileNotFound(Exception):
+    pass
+
+
+class ConfigFileCouldNotBeLoaded(Exception):
+    pass
+
+
+class ConfigFileCouldNotBeSaved(Exception):
+    pass
index 91cdeaa..f0e7ddb 100644 (file)
@@ -35,18 +35,6 @@ class BackupDBEngineNotSupported(Exception):
     pass
 
 
-class ConfigFileNotFound(Exception):
-    pass
-
-
-class ConfigFileCouldNotBeLoaded(Exception):
-    pass
-
-
-class ConfigFileCouldNotBeSaved(Exception):
-    pass
-
-
 class ConflictInScriptName(Exception):
     pass
 
index 264cba3..523e4fb 100644 (file)
@@ -32,7 +32,10 @@ import threading
 import getpass
 import logging
 import hashlib
+import tempfile
+from lib.config import Conf
 
+C = Conf()
 
 def yesOrNo(q):
     while True:
@@ -85,7 +88,6 @@ def getMDLFromCommitMessage(message):
 def get_current_user():
     """Attempt to get the currently logged in user"""
     username = 'root'
-    import os
     try:
         username = os.getlogin()
     except OSError:
@@ -97,6 +99,21 @@ def get_current_user():
     return username
 
 
+def launchEditor(filepath=None, suffix='.tmp'):
+    """Launchs up an editor
+
+    If filepath is passed, the content of the file is used to populate the editor.
+
+    This returns the path to the saved file.
+    """
+    with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmpfile:
+        with open(filepath, 'r') as f:
+            tmpfile.write(f.read())
+            tmpfile.flush()
+        subprocess.call([C.get('editor'), tmpfile.name])
+    return tmpfile.name
+
+
 def md5file(filepath):
     """Return the md5 sum of a file
     This is terribly memory inefficient!"""