]> kaliko git repositories - mpd-sima.git/blobdiff - sima/launch.py
Mainly use literal for list/dict and f-strings when possible
[mpd-sima.git] / sima / launch.py
index 4cdcae03ef49d8e5ff6120e6d388b36274661221..784d23784d480fd3323a210aa44ca93974b99641 100644 (file)
@@ -1,5 +1,5 @@
 # -*- coding: utf-8 -*-
-# Copyright (c) 2013, 2014, 2015, 2020,2021 kaliko <kaliko@azylum.org>
+# Copyright (c) 2013, 2014, 2015, 2020, 2021 kaliko <kaliko@azylum.org>
 #
 #  This file is part of sima
 #
@@ -26,6 +26,7 @@ import sys
 
 from importlib import __import__ as sima_import
 from os.path import isfile
+from os import rename
 ##
 
 # third parties components
@@ -38,6 +39,7 @@ from .lib.simadb import SimaDB
 from .utils.config import ConfMan
 from .utils.startopt import StartOpt
 from .utils.utils import exception_log, SigHup, MPDSimaException
+from .utils.blcli import BLCli
 # core plugins
 from .plugins.core.history import History
 from .plugins.core.mpdoptions import MpdOptions
@@ -49,19 +51,19 @@ def load_plugins(sima, source):
     """Handles internal/external plugins
         sima:   sima.core.Sima instance
         source: ['internal', 'contrib']
-    """
+    """# pylint: disable=logging-not-lazy,logging-format-interpolation
     if not sima.config.get('sima', source):
         return
     logger = logging.getLogger('sima')
     # TODO: Sanity check for "sima.config.get('sima', source)" ?
     for plugin in sima.config.get('sima', source).split(','):
         plugin = plugin.strip(' \n')
-        module = 'sima.plugins.{0}.{1}'.format(source, plugin.lower())
+        module = f'sima.plugins.{source}.{plugin.lower()}'
         try:
             mod_obj = sima_import(module, fromlist=[plugin])
         except ImportError as err:
-            logger.error('Failed to load "{}" plugin\'s module: '.format(plugin) +
-                         '{0} ({1})'.format(module, err))
+            logger.error(f'Failed to load "{plugin}" plugin\'s module: ' +
+                         f'{module} ({err})')
             sima.shutdown()
             sys.exit(1)
         try:
@@ -85,22 +87,34 @@ def start(sopt, restart=False):
     logger = logging.getLogger('sima')
     logfile = config.get('log', 'logfile', fallback=None)
     verbosity = config.get('log', 'verbosity')
-    set_logger(verbosity, logfile)
+    if sopt.options.get('command'):  # disable file logging
+        set_logger(verbosity)
+    else:
+        set_logger(verbosity, logfile)
     logger.debug('Command line say: %s', sopt.options)
 
     # Create database if not present
     db_file = config.get('sima', 'db_file')
     if not isfile(db_file):
         logger.debug('Creating database in "%s"', db_file)
-        open(db_file, 'a').close()  # TODO: to remove with new simadb in v0.18
+        SimaDB(db_path=db_file).create_db()
+    # Migration from v0.17.0
+    dbinfo = SimaDB(db_path=db_file).get_info()
+    if not dbinfo:  # v0.17.0 → v0.18+ migration
+        logger.warning('Backing up database!')
+        rename(db_file, db_file + '-old-version-backup')
+        logger.info('Creating an new database in "%s"', db_file)
         SimaDB(db_path=db_file).create_db()
 
     if sopt.options.get('command'):
         cmd = sopt.options.get('command')
+        if cmd.startswith('bl-'):
+            BLCli(config, sopt.options)
+            sys.exit(0)
         if cmd == "generate-config":
             config.write(sys.stdout, space_around_delimiters=True)
             sys.exit(0)
-        logger.info('Running "%s" and exit' % cmd)
+        logger.info('Running "%s" and exit', cmd)
         if cmd == "config-test":
             logger.info('Config location: "%s"', cfg_mgmt.conf_file)
             from .utils.configtest import config_test
@@ -109,12 +123,10 @@ def start(sopt, restart=False):
         if cmd == "create-db":
             if not isfile(db_file):
                 logger.info('Creating database in "%s"', db_file)
-                open(db_file, 'a').close()  # TODO: to remove with new simadb in v0.18
                 SimaDB(db_path=db_file).create_db()
-                if sopt.options.get('create_db', None):
-                    logger.info('Done, bye...')
             else:
                 logger.info('Database already there, not overwriting %s', db_file)
+            logger.info('Done, bye...')
             sys.exit(0)
         if cmd == "purge-history":
             db_file = config.get('sima', 'db_file')
@@ -136,7 +148,8 @@ def start(sopt, restart=False):
     for cplgn in core_plugins:
         logger.debug('Register core %(name)s (%(doc)s)', cplgn.info())
         sima.register_core_plugin(cplgn)
-    logger.debug('core loaded, prioriy: %s', ' > '.join(map(str, sima.core_plugins)))
+    logger.debug('core loaded, prioriy: %s',
+                 ' > '.join(map(str, sima.core_plugins)))
 
     #  Loading internal plugins
     load_plugins(sima, 'internal')
@@ -176,11 +189,12 @@ def run(sopt, restart=False):
     except Exception:  # Unhandled exception
         exception_log()
 
+
 # Script starts here
 def main():
     """Entry point"""
     nfo = dict({'version': info.__version__,
-                'prog': 'sima'})
+                'prog': 'mpd-sima'})
     # StartOpt gathers options from command line call (in StartOpt().options)
     sopt = StartOpt(nfo)
     run(sopt)