changeset 930:cbf4122baae7

core, memory: use XDG recommended paths as the defaults for the config and local directories
author souliane <souliane@mailoo.org>
date Sun, 23 Mar 2014 22:43:43 +0100
parents 059b56cbd247
children 3b30e9f83d88
files src/core/constants.py src/core/sat_main.py src/memory/memory.py src/sat.sh
diffstat 4 files changed, 55 insertions(+), 16 deletions(-) [+]
line wrap: on
line diff
--- a/src/core/constants.py	Mon Mar 24 15:18:53 2014 +0100
+++ b/src/core/constants.py	Sun Mar 23 22:43:43 2014 +0100
@@ -17,6 +17,9 @@
 # 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 xdg import BaseDirectory
+
 
 class Const(object):
     APP_NAME = u'Salut à Toi'
@@ -25,10 +28,23 @@
     APP_VERSION = u'0.4.1D' # Please add 'D' at the end for dev versions
 
     DEFAULT_CONFIG = {
-        'local_dir': '~/.sat',
         'media_dir': '/usr/share/sat/media',
+        'pid_dir': '/tmp',
+        'log_dir': BaseDirectory.save_data_path('sat'),
     }
 
+    # 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 \
+                    ['/etc/', '~/', '~/.', '', '.'] + \
+                    ['%s/' % path for path in list(BaseDirectory.load_config_paths('sat'))]
+                    ]
+
     NO_SECURITY_LIMIT = -1
     INDIVIDUAL = "individual"
     GENERAL = "general"
--- a/src/core/sat_main.py	Mon Mar 24 15:18:53 2014 +0100
+++ b/src/core/sat_main.py	Sun Mar 23 22:43:43 2014 +0100
@@ -97,11 +97,6 @@
         self.plugins = {}
 
         self.memory = Memory(self)
-
-        local_dir = self.memory.getConfig('', 'local_dir')
-        if not os.path.exists(local_dir):
-            os.makedirs(local_dir)
-
         self.trigger = TriggerManager()  # trigger are used to change SàT behaviour
 
         try:
--- a/src/memory/memory.py	Mon Mar 24 15:18:53 2014 +0100
+++ b/src/memory/memory.py	Sun Mar 23 22:43:43 2014 +0100
@@ -21,6 +21,7 @@
 
 import os.path
 import csv
+from xdg import BaseDirectory
 from ConfigParser import SafeConfigParser, NoOptionError, NoSectionError
 from uuid import uuid4
 from logging import debug, info, warning, error
@@ -117,6 +118,7 @@
         self.server_features = {}  # used to store discovery's informations
         self.server_identities = {}
         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
@@ -130,13 +132,41 @@
 
     def parseMainConf(self):
         """look for main .ini configuration file, and parse it"""
-        _config = SafeConfigParser(defaults=C.DEFAULT_CONFIG)
+        config = SafeConfigParser(defaults=C.DEFAULT_CONFIG)
         try:
-            _config.read(map(os.path.expanduser, ['/etc/sat.conf', '~/sat.conf', '~/.sat.conf', 'sat.conf', '.sat.conf']))
+            config.read(C.CONFIG_FILES)
         except:
             error(_("Can't read main config !"))
+        return 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):
+            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)
+            warning(_("Auto-update: local_dir set to %(path)s in the file %(config_file)s") % {'path': old_default, 'config_file': file_})
+        else:  # use the new default local_dir
+            self.config.set('', 'local_dir', C.DEFAULT_LOCAL_DIR)
 
     def getConfig(self, section, name):
         """Get the main configuration option
--- a/src/sat.sh	Mon Mar 24 15:18:53 2014 +0100
+++ b/src/sat.sh	Sun Mar 23 22:43:43 2014 +0100
@@ -19,31 +19,29 @@
 
 #We use python to parse config files
 eval `"$PYTHON" << PYTHONEND
+from sat.core.constants import Const
 from ConfigParser import SafeConfigParser
 from os.path import expanduser, join
 import sys
 
-config = SafeConfigParser(defaults={'local_dir':'~/.sat',
-									'pid_dir':'/tmp',
-									'log_dir':'%(local_dir)s'})
+config = SafeConfigParser(defaults=Const.DEFAULT_CONFIG)
 try:
-	config.read(map(expanduser, ['/etc/sat.conf', '~/sat.conf', '~/.sat.conf', 'sat.conf', '.sat.conf']))
+    config.read(Const.CONFIG_FILES)
 except:
 	print ("echo \"/!\\ Can't read main config ! Please check the syntax\";")
 	print ("exit 1")
 	sys.exit()
 
 env=[]
-env.append("LOCAL_DIR='%s'" % join(expanduser(config.get('DEFAULT', 'local_dir')),''))
 env.append("PID_DIR='%s'" % join(expanduser(config.get('DEFAULT', 'pid_dir')),''))
-env.append("LOG_DIR='%s'" % join(expanduser(config.get('DEFAULT', 'pid_dir')),''))
+env.append("LOG_DIR='%s'" % join(expanduser(config.get('DEFAULT', 'log_dir')),''))
 
 print ";".join(env)
 PYTHONEND
 `
 
 PID_FILE="$PID_DIR$NAME.pid"
-LOG_FILE="$LOCAL_DIR$NAME.log"
+LOG_FILE="$LOG_DIR$NAME.log"
 DAEMON="n"
 MAIN_OPTIONS="-${DAEMON}oy"
 TAP_PATH="./"