changeset 1003:52ec79aa5bbe

memory: fixes the method fixLocalDir for pid_dir and log_dir to use local_dir as default
author souliane <souliane@mailoo.org>
date Wed, 30 Apr 2014 19:54:21 +0200
parents 291eb8216f6e
children 191f440d11b4
files src/core/constants.py src/memory/memory.py src/sat.sh
diffstat 3 files changed, 67 insertions(+), 56 deletions(-) [+]
line wrap: on
line diff
--- a/src/core/constants.py	Wed Apr 30 16:34:09 2014 +0200
+++ b/src/core/constants.py	Wed Apr 30 19:54:21 2014 +0200
@@ -17,7 +17,7 @@
 # You should have received a copy of the GNU Affero General Public License
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
-import os.path
+from os.path import expanduser, abspath
 try:
     import __pyjamas__  # do not import xdg when building Libervia
     BaseDirectory = None
@@ -30,6 +30,7 @@
     ## Application ##
     APP_NAME = u'Salut à Toi'
     APP_NAME_SHORT = u'SàT'
+    APP_NAME_FILE = u'sat'
     APP_NAME_FULL = u'%s (%s)' % (APP_NAME_SHORT, APP_NAME)
     APP_VERSION = u'0.4.1D'  # Please add 'D' at the end for dev versions
     APP_URL = 'http://salut-a-toi.org'
@@ -54,21 +55,16 @@
 
         ## Configuration ##
         DEFAULT_CONFIG = {
-            'media_dir': '/usr/share/sat/media',
-            'pid_dir': '/tmp',
-            'log_dir': BaseDirectory.save_data_path('sat'),
+            'media_dir': '/usr/share/' + APP_NAME_FILE + '/media',
+            'local_dir': BaseDirectory.save_data_path(APP_NAME_FILE),
+            'pid_dir': '%(local_dir)s',
+            'log_dir': '%(local_dir)s',
         }
 
-        # XXX: tmp update code, will be removed in the future
-        # When you remove this, please add that in DEFAULT_CONFIG:
-        # 'local_dir': BaseDirectory.save_data_path('sat'),
-        # and also remove sat.memory.memory.Memory.__fixLocalDir
-        DEFAULT_LOCAL_DIR = BaseDirectory.save_data_path('sat')
-
         # List of the configuration filenames sorted by ascending priority
-        CONFIG_FILES = [(os.path.expanduser(path) + 'sat.conf') for path in
+        CONFIG_FILES = [abspath(expanduser(path) + APP_NAME_FILE + '.conf') for path in
                         ['/etc/', '~/', '~/.', '', '.'] +
-                        ['%s/' % path for path in list(BaseDirectory.load_config_paths('sat'))]
+                        ['%s/' % path for path in list(BaseDirectory.load_config_paths(APP_NAME_FILE))]
                        ]
 
 
@@ -89,7 +85,7 @@
 
 
     ## Misc ##
-    SAVEFILE_DATABASE = "sat.db"
+    SAVEFILE_DATABASE = APP_NAME_FILE + ".db"
     IQ_SET = '/iq[@type="set"]'
     ENV_PREFIX = 'SAT_' # Prefix used for environment variables
 
--- a/src/memory/memory.py	Wed Apr 30 16:34:09 2014 +0200
+++ b/src/memory/memory.py	Wed Apr 30 19:54:21 2014 +0200
@@ -107,6 +107,50 @@
         return self._sessions.iterkeys()
 
 
+# XXX: tmp update code, will be removed in the future
+# When you remove this, please add the default value for
+# 'local_dir' in sat.core.constants.Const.DEFAULT_CONFIG
+def fixLocalDir(silent=True):
+    """Retro-compatibility with the previous local_dir default value.
+
+    @param silent (boolean): toggle logging output (must be True when called from sat.sh)
+    """
+    user_config = SafeConfigParser()
+    try:
+        user_config.read(C.CONFIG_FILES)
+    except:
+        pass  # file is readable but its structure if wrong
+    try:
+        current_value = user_config.get('DEFAULT', 'local_dir')
+    except (NoOptionError, NoSectionError):
+        current_value = ''
+    if current_value:
+        return  # nothing to do
+    old_default = '~/.sat'
+    if os.path.isfile(os.path.expanduser(old_default) + '/' + C.SAVEFILE_DATABASE):
+        if not silent:
+            log.warning(_("A database has been found in the default local_dir for previous versions (< 0.5)"))
+        config = SafeConfigParser()
+        target_file = None
+        for file_ in C.CONFIG_FILES[::-1]:
+            # we will eventually update the existing file with the highest priority, if it's a user personal file...
+            if not silent:
+                log.debug(_("Testing file %s") % file_)
+            if os.path.isfile(file_):
+                if file_.startswith(os.path.expanduser('~')):
+                    config.read([file_])
+                    target_file = file_
+                break
+        if not target_file:
+            # ... otherwise we create a new config file for that user
+            target_file = BaseDirectory.save_config_path('sat') + '/sat.conf'
+        config.set('', 'local_dir', old_default)
+        with open(target_file, 'wb') as configfile:
+            config.write(configfile)  # for the next time that user launches sat
+        if not silent:
+            log.warning(_("Auto-update: local_dir set to %(path)s in the file %(config_file)s") % {'path': old_default, 'config_file': target_file})
+
+
 class Memory(object):
     """This class manage all persistent informations"""
 
@@ -118,8 +162,8 @@
                                   #     /!\ an entity is not necessarily in roster
         self.subscriptions = {}
         self.disco = Discovery(host)
+        fixLocalDir(False)  # XXX: tmp update code, will be removed in the future
         self.config = self.parseMainConf()
-        self.__fixLocalDir()
         database_file = os.path.expanduser(os.path.join(self.getConfig('', 'local_dir'), C.SAVEFILE_DATABASE))
         self.storage = SqliteStorage(database_file, host.__version__)
         PersistentDict.storage = self.storage
@@ -140,37 +184,6 @@
             log.error(_("Can't read main config !"))
         return config
 
-    # XXX: tmp update code, will be removed in the future
-    # When you remove this, please also remove sat.core.constants.Const.DEFAULT_LOCAL_DIR
-    # and add the default value for 'local_dir' in sat.core.constants.Const.DEFAULT_CONFIG
-    def __fixLocalDir(self):
-        """Retro-compatibility with the previous local_dir default value."""
-        if self.getConfig('', 'local_dir'):
-            return  # nothing to do
-        old_default = '~/.sat'
-        if os.path.isfile(os.path.expanduser(old_default) + '/' + C.SAVEFILE_DATABASE):
-            log.warning(_("A database has been found in the default local_dir for previous versions (< 0.5)"))
-            config = SafeConfigParser()
-            target_file = None
-            for file_ in C.CONFIG_FILES[::-1]:
-                # we will eventually update the existing file with the highest priority, if it's a user personal file...
-                if os.path.isfile(file_):
-                    if file_.startswith(os.path.expanduser('~')):
-                        config.read([file_])
-                        target_file = file_
-                    break
-            if not target_file:
-                # ... otherwise we create a new config file for that user
-                target_file = BaseDirectory.save_config_path('sat') + '/sat.conf'
-            config.set('', 'local_dir', old_default)
-            with open(target_file, 'wb') as configfile:
-                config.write(configfile)  # for the next time that user launches sat
-            log.warning(_("Auto-update: local_dir set to %(path)s in the file %(config_file)s") % {'path': old_default, 'config_file': file_})
-            default = old_default
-        else:  # use the new default local_dir
-            default = C.DEFAULT_LOCAL_DIR
-        self.config.set('', 'local_dir', default)  # for the currently running instance
-
     def getConfig(self, section, name):
         """Get the main configuration option
         @param section: section of the config file (None or '' for DEFAULT)
--- a/src/sat.sh	Wed Apr 30 16:34:09 2014 +0200
+++ b/src/sat.sh	Wed Apr 30 19:54:21 2014 +0200
@@ -1,8 +1,6 @@
 #!/bin/sh
 
 DEBUG=""
-NAME="sat"
-FULL_NAME="Salut à Toi"
 PYTHON="python2"
 
 kill_process() {
@@ -23,14 +21,17 @@
 
 #We use python to parse config files
 eval `"$PYTHON" << PYTHONEND
-from sat.core.constants import Const
+from sat.core.constants import Const as C
+from sat.memory.memory import fixLocalDir
 from ConfigParser import SafeConfigParser
 from os.path import expanduser, join
 import sys
 
-config = SafeConfigParser(defaults=Const.DEFAULT_CONFIG)
+fixLocalDir()  # XXX: tmp update code, will be removed in the future
+
+config = SafeConfigParser(defaults=C.DEFAULT_CONFIG)
 try:
-    config.read(Const.CONFIG_FILES)
+    config.read(C.CONFIG_FILES)
 except:
     print ("echo \"/!\\ Can't read main config ! Please check the syntax\";")
     print ("exit 1")
@@ -40,21 +41,22 @@
 env.append("PID_DIR='%s'" % join(expanduser(config.get('DEFAULT', 'pid_dir')),''))
 env.append("LOG_DIR='%s'" % join(expanduser(config.get('DEFAULT', 'log_dir')),''))
 
+env.append("APP_NAME_FILE='%s'" % C.APP_NAME_FILE)
 print ";".join(env)
 PYTHONEND
 `
-
-PID_FILE="$PID_DIR$NAME.pid"
-LOG_FILE="$LOG_DIR$NAME.log"
+APP_NAME="Salut à Toi"  # FIXME: the import from Python constants fails because of the à
+PID_FILE="$PID_DIR$APP_NAME_FILE.pid"
+LOG_FILE="$LOG_DIR$APP_NAME_FILE.log"
 
 # if there is one argument which is "stop", then we kill SàT
 if [ $# -eq 1 ];then
     if [ $1 = "stop" ];then
-        kill_process $PID_FILE "$FULL_NAME"
+        kill_process $PID_FILE "$APP_NAME"
         exit 0
     fi
     if [ $1 = "debug" ];then
-        echo "Launching $FULL_NAME in debug mode"
+        echo "Launching $APP_NAME in debug mode"
         DEBUG="--debug"
     fi
 fi
@@ -62,7 +64,7 @@
 DAEMON="n"
 MAIN_OPTIONS="-${DAEMON}oy"
 TAP_PATH="./"
-TAP_FILE="$NAME.tac"
+TAP_FILE="$APP_NAME_FILE.tac"
 
 #Don't change the next line
 AUTO_OPTIONS=""