Salome HOME
Finalise the preparation commands
[tools/sat.git] / commands / config.py
index 3de5e9547e8bae1910aa7806f55d7773d1c50a81..9d35e542d92ce2c29e2529114d2ba6aade204a35 100644 (file)
@@ -21,6 +21,7 @@ import platform
 import datetime
 import shutil
 import gettext
+import sys
 
 import src
 
@@ -31,15 +32,19 @@ gettext.install('salomeTools', os.path.join(satdir, 'src', 'i18n'))
 # Define all possible option for config command :  sat config <options>
 parser = src.options.Options()
 parser.add_option('v', 'value', 'string', 'value',
-                   _("print the value of CONFIG_VARIABLE."))
+    _("print the value of CONFIG_VARIABLE."))
 parser.add_option('e', 'edit', 'boolean', 'edit',
-                   _("edit the product configuration file."))
+    _("edit the product configuration file."))
 parser.add_option('l', 'list', 'boolean', 'list',
-                  _("list all available applications."))
+    _("list all available applications."))
 parser.add_option('c', 'copy', 'boolean', 'copy',
     _("""copy a config file to the personnal config files directory.
 \tWARNING the included files are not copied.
 \tIf a name is given the new config file takes the given name."""))
+parser.add_option('n', 'no_label', 'boolean', 'no_label',
+    _("do not print labels, Works only with --value and --list."))
+parser.add_option('s', 'schema', 'boolean', 'schema',
+    _("Internal use."))
 
 class ConfigOpener:
     '''Class that helps to find an application pyconf 
@@ -72,16 +77,16 @@ class ConfigOpener:
 class ConfigManager:
     '''Class that manages the read of all the configuration files of salomeTools
     '''
-    def __init__(self, dataDir=None):
+    def __init__(self, datadir=None):
         pass
 
-    def _create_vars(self, application=None, command=None, dataDir=None):
+    def _create_vars(self, application=None, command=None, datadir=None):
         '''Create a dictionary that stores all information about machine,
            user, date, repositories, etc...
         
         :param application str: The application for which salomeTools is called.
         :param command str: The command that is called.
-        :param dataDir str: The repository that contain external data 
+        :param datadir str: The repository that contain external data 
                             for salomeTools.
         :return: The dictionary that stores all information.
         :rtype: dict
@@ -93,10 +98,10 @@ class ConfigManager:
         var['srcDir'] = os.path.join(var['salometoolsway'], 'src')
         var['sep']= os.path.sep
         
-        # dataDir has a default location
-        var['dataDir'] = os.path.join(var['salometoolsway'], 'data')
-        if dataDir is not None:
-            var['dataDir'] = dataDir
+        # datadir has a default location
+        var['datadir'] = os.path.join(var['salometoolsway'], 'data')
+        if datadir is not None:
+            var['datadir'] = datadir
 
         var['personalDir'] = os.path.join(os.path.expanduser('~'),
                                            '.salomeTools')
@@ -162,14 +167,14 @@ class ConfigManager:
         return over
 
     def get_config(self, application=None, options=None, command=None,
-                    dataDir=None):
+                    datadir=None):
         '''get the config from all the configuration files.
         
         :param application str: The application for which salomeTools is called.
         :param options class Options: The general salomeToos
                                       options (--overwrite or -l5, for example)
         :param command str: The command that is called.
-        :param dataDir str: The repository that contain 
+        :param datadir str: The repository that contain 
                             external data for salomeTools.
         :return: The final config.
         :rtype: class 'src.pyconf.Config'
@@ -184,7 +189,7 @@ class ConfigManager:
         # =====================================================================
         # create VARS section
         var = self._create_vars(application=application, command=command, 
-                                dataDir=dataDir)
+                                datadir=datadir)
         # add VARS to config
         cfg.VARS = src.pyconf.Mapping(cfg)
         for variable in var:
@@ -216,9 +221,9 @@ class ConfigManager:
         # =====================================================================
         # Load SITE config file
         # search only in the data directory
-        src.pyconf.streamOpener = ConfigOpener([cfg.VARS.dataDir])
+        src.pyconf.streamOpener = ConfigOpener([cfg.VARS.datadir])
         try:
-            site_cfg = src.pyconf.Config(open(os.path.join(cfg.VARS.dataDir, 
+            site_cfg = src.pyconf.Config(open(os.path.join(cfg.VARS.datadir, 
                                                            'site.pyconf')))
         except src.pyconf.ConfigError as e:
             raise src.SatException(_("Error in configuration file: "
@@ -271,31 +276,31 @@ class ConfigManager:
                 exec('cfg.' + rule) 
         
         # =====================================================================
-        # Load softwares config files in SOFTWARE section
+        # Load product config files in PRODUCTS section
        
         # The directory containing the softwares definition
-        softsDir = os.path.join(cfg.VARS.dataDir, 'softwares')
+        products_dir = os.path.join(cfg.VARS.datadir, 'products')
         
-        # Loop on all files that are in softsDir directory 
+        # Loop on all files that are in softsDir directory
         # and read their config
-        for fName in os.listdir(softsDir):
+        for fName in os.listdir(products_dir):
             if fName.endswith(".pyconf"):
-                src.pyconf.streamOpener = ConfigOpener([softsDir])
+                src.pyconf.streamOpener = ConfigOpener([products_dir])
                 try:
-                    soft_cfg = src.pyconf.Config(open(
-                                                os.path.join(softsDir, fName)))
+                    prod_cfg = src.pyconf.Config(open(
+                                                os.path.join(products_dir, fName)))
                 except src.pyconf.ConfigError as e:
                     raise src.SatException(_(
-                        "Error in configuration file: %(soft)s\n  %(error)s") % \
-                        {'soft' :  fName, 'error': str(e) })
+                        "Error in configuration file: %(prod)s\n  %(error)s") % \
+                        {'prod' :  fName, 'error': str(e) })
                 except IOError as error:
                     e = str(error)
                     raise src.SatException( e );
                 
-                merger.merge(cfg, soft_cfg)
+                merger.merge(cfg.PRODUCTS, prod_cfg)
 
         # apply overwrite from command line if needed
-        for rule in self.get_command_line_overrides(options, ["SOFTWARE"]):
+        for rule in self.get_command_line_overrides(options, ["PRODUCTS"]):
             exec('cfg.' + rule) # this cannot be factorized because of the exec
 
         
@@ -344,15 +349,15 @@ class ConfigManager:
         user_cfg.addMapping('USER', src.pyconf.Mapping(user_cfg), "")
 
         #
-        user_cfg.USER.addMapping('workDir', os.path.expanduser('~'),
+        user_cfg.USER.addMapping('workdir', os.path.expanduser('~'),
             "This is where salomeTools will work. "
             "You may (and probably do) change it.\n")
         user_cfg.USER.addMapping('cvs_user', config.VARS.user,
             "This is the user name used to access salome cvs base.\n")
         user_cfg.USER.addMapping('svn_user', config.VARS.user,
             "This is the user name used to access salome svn base.\n")
-        user_cfg.USER.addMapping('output_level', 3,
-            "This is the default output_level you want."
+        user_cfg.USER.addMapping('output_verbose_level', 3,
+            "This is the default output_verbose_level you want."
             " 0=>no output, 5=>debug.\n")
         user_cfg.USER.addMapping('publish_dir', 
                                  os.path.join(os.path.expanduser('~'),
@@ -409,6 +414,10 @@ def print_value(config, path, show_label, logger, level=0, show_full_path=False)
     :param show_full_path :
     '''            
     
+    # Make sure that the path does not ends with a point
+    if path.endswith('.'):
+        path = path[:-1]
+    
     # display all the path or not
     if show_full_path:
         vname = path
@@ -449,6 +458,41 @@ def print_value(config, path, show_label, logger, level=0, show_full_path=False)
     else: # case where val is just a str
         logger.write("%s\n" % val)
 
+def get_config_children(config, args):
+    '''Gets the names of the children of the given parameter.
+       Useful only for completion mechanism
+    
+    :param config Config: The configuration where to read the values
+    :param args: The path in the config from which get the keys
+    '''
+    vals = []
+    rootkeys = config.keys()
+    
+    if len(args) == 0:
+        # no parameter returns list of root keys
+        vals = rootkeys
+    else:
+        parent = args[0]
+        pos = parent.rfind('.')
+        if pos < 0:
+            # Case where there is only on key as parameter.
+            # For example VARS
+            vals = [m for m in rootkeys if m.startswith(parent)]
+        else:
+            # Case where there is a part from a key
+            # for example VARS.us  (for VARS.user)
+            head = parent[0:pos]
+            tail = parent[pos+1:]
+            try:
+                a = config.getByPath(head)
+                if dir(a).__contains__('keys'):
+                    vals = map(lambda x: head + '.' + x, [m for m in a.keys() if m.startswith(tail)])
+            except:
+                pass
+
+    for v in sorted(vals):
+        sys.stdout.write("%s\n" % v)
+
 def description():
     '''method that is called when salomeTools is called with --help option.
     
@@ -464,15 +508,20 @@ def run(args, runner, logger):
     '''
     # Parse the options
     (options, args) = parser.parse_args(args)
+
+    # Only useful for completion mechanism : print the keys of the config
+    if options.schema:
+        get_config_children(runner.cfg, args)
+        return
     
     # case : print a value of the config
     if options.value:
         if options.value == ".":
             # if argument is ".", print all the config
             for val in sorted(runner.cfg.keys()):
-                print_value(runner.cfg, val, True, logger)
+                print_value(runner.cfg, val, not options.no_label, logger)
         else:
-            print_value(runner.cfg, options.value, True, logger, 
+            print_value(runner.cfg, options.value, not options.no_label, logger, 
                         level=0, show_full_path=False)
     
     # case : edit user pyconf file or application file
@@ -542,7 +591,8 @@ def run(args, runner, logger):
         # search in all directories that can have pyconf applications
         for path in runner.cfg.SITE.config.config_path:
             # print a header
-            logger.write("------ %s\n" % src.printcolors.printcHeader(path))
+            if not options.no_label:
+                logger.write("------ %s\n" % src.printcolors.printcHeader(path))
 
             if not os.path.exists(path):
                 logger.write(src.printcolors.printcError(_(
@@ -556,7 +606,8 @@ def run(args, runner, logger):
                     appliname = f[:-len('.pyconf')]
                     if appliname not in lproduct:
                         lproduct.append(appliname)
-                        if path.startswith(runner.cfg.VARS.personalDir):
+                        if path.startswith(runner.cfg.VARS.personalDir) \
+                                    and not options.no_label:
                             logger.write("%s*\n" % appliname)
                         else:
                             logger.write("%s\n" % appliname)