]> SALOME platform Git repositories - tools/sat.git/commitdiff
Salome HOME
remove print_value(log,label,value)
authorChristian Van Wambeke <christian.van-wambeke@cea.fr>
Wed, 4 Apr 2018 12:16:07 +0000 (14:16 +0200)
committerChristian Van Wambeke <christian.van-wambeke@cea.fr>
Wed, 4 Apr 2018 12:16:07 +0000 (14:16 +0200)
15 files changed:
commands/application.py
commands/environ.py
commands/find_duplicates.py
commands/generate.py
commands/launcher.py
commands/package.py
commands/patch.py
commands/run.py
commands/source.py
commands/template.py
commands/test.py
src/configManager.py
src/debug.py
src/test_module.py
src/utilsSat.py

index f14ff0d4218351284820e02136d4c851ac63190a..f61621b44f681010838b97d8a39209b54a685b2b 100644 (file)
 #  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
 
 """
-import os
-import stat
-import sys
-import shutil
-import subprocess
-import getpass
+Is a salomeTools command module
+see Command class docstring, also used for help
 """
 
-from src import ElementTree as etree
+import os
+import getpass
+import subprocess
 
+import src.ElementTree as ET
 import src.debug as DBG
 import src.returnCode as RCO
+import src.utilsSat as UTS
 from src.salomeTools import _BaseCommand
 
 ########################################################################
@@ -100,7 +100,7 @@ NOTICE:   this command will ssh to retrieve information to each machine in the l
     # if section APPLICATION.virtual_app does not exists create one
     if "virtual_app" not in runner.cfg.APPLICATION:
         msg = _("The section APPLICATION.virtual_app is not defined in the product.")
-        logger.info("red>" + msg + "<reset>" )
+        logger.error(UTS.red(msg)
         return RCO.ReturnCode("KO", msg)
 
     # get application dir
@@ -122,11 +122,9 @@ NOTICE:   this command will ssh to retrieve information to each machine in the l
                                          runner.cfg.APPLICATION.virtual_app.name + "_appdir")
     appli_dir = os.path.join(target_dir, application_name)
 
-    src.printcolors.print_value(logger,
-                                _("Application directory"),
-                                appli_dir,
-                                3)
-
+    fmt = "  %s = %s\n" # as "  label = value\n"
+    logger.info(fmt % (_("Application directory"), appli_dir))
+    
     # get catalog
     catalog, catalog_src = "", ""
     if options.catalog:
@@ -155,17 +153,9 @@ NOTICE:   this command will ssh to retrieve information to each machine in the l
     if len(catalog) > 0:
         catalog = os.path.realpath(catalog)
         if len(catalog_src) > 0:
-            src.printcolors.print_value(logger,
-                                        _("Resources Catalog"),
-                                        catalog_src,
-                                        3)
+            logger.info(fmt % (_("Resources Catalog"), catalog_src))
         else:
-            src.printcolors.print_value(logger,
-                                        _("Resources Catalog"),
-                                        catalog,
-                                        3)
-
-    logger.write("\n", 3, False)
+            logger.info(fmt % (_("Resources Catalog"), catalog))
 
     details = []
 
@@ -401,10 +391,11 @@ def get_SALOME_modules(config):
             l_modules.append(product)
     return l_modules
 
-##
-# Obsolescent way of creating the application.
-# This method will use appli_gen to create the application directory.
 def generate_launch_file(config, appli_dir, catalog, logger, l_SALOME_modules):
+    """
+    Obsolescent way of creating the application.
+    This method will use appli_gen to create the application directory.
+    """
     retcode = -1
 
     if len(catalog) > 0 and not os.path.exists(catalog):
@@ -459,19 +450,14 @@ def generate_launch_file(config, appli_dir, catalog, logger, l_SALOME_modules):
 
     return retcode
 
-
-
-##
-# Generates the catalog from a list of machines.
 def generate_catalog(machines, config, logger):
+    """Generates the catalog from a list of machines."""
     # remove empty machines
     machines = map(lambda l: l.strip(), machines)
     machines = filter(lambda l: len(l) > 0, machines)
 
-    src.printcolors.print_value(logger,
-                                _("Generate Resources Catalog"),
-                                ", ".join(machines),
-                                4)
+    logger.debug("  %s = %s" % _("Generate Resources Catalog"), ", ".join(machines))
+    
     cmd = '"cat /proc/cpuinfo | grep MHz ; cat /proc/meminfo | grep MemTotal"'
     user = getpass.getuser()
 
index 5e2f23bee4ecf165d3132a32fcb5ab97fadd27bc..a0c1333342449937ef94e512eae0b3cfd71508a4 100644 (file)
@@ -20,6 +20,7 @@
 
 import src.debug as DBG
 import src.returnCode as RCO
+import src.utilsSat as UTS
 from src.salomeTools import _BaseCommand
 
 # list of available shells with extensions
@@ -104,8 +105,6 @@ class Command(_BaseCommand):
     logger.write("\n", 3, False)
     #TODO return code
 
-##
-# Writes all the environment files
 def write_all_source_files(config,
                            logger,
                            out_dir=None,
@@ -136,12 +135,9 @@ def write_all_source_files(config,
         raise Exception(_("Target directory not found: %s") % out_dir)
 
     if not silent:
-        logger.write(_("Creating environment files for %s\n") % 
-                     src.printcolors.printcLabel(config.APPLICATION.name), 2)
-        src.printcolors.print_value(logger,
-                                    _("Target"),
-                                    src.printcolors.printcInfo(out_dir), 3)
-        logger.write("\n", 3, False)
+        logger.info(_("Creating environment files for %s\n") % \
+                     UTS.header(config.APPLICATION.name))
+        logger.info("  %s = %s\n\n" % (_("Target"), out_dir))
     
     shells_list = []
     all_shells = C_ALL_SHELL
index f728d93aa29a1dff563736a94bd68710d56e67f7..6a6fd7b9570ab80c9e6af6c6fd095fa1f3ef9bbe 100644 (file)
@@ -20,6 +20,7 @@
 
 import src.debug as DBG
 import src.returnCode as RCO
+import src.utilsSat as UTS
 from src.salomeTools import _BaseCommand
 
 
@@ -267,23 +268,6 @@ def format_list_of_str(l_str):
         return l_str
     return ",".join(l_str)
 
-def print_info(logger, info, level=2):
-    '''Format a display
-    
-    :param logger Logger: The logger instance
-    :param info List: the list of tuple to display
-    :param valMax float: the maximum value of the variable
-    :param level int: the verbose level that will be used
-    '''
-    smax = max(map(lambda l: len(l[0]), info))
-    for i in info:
-        sp = " " * (smax - len(i[0]))
-        src.printcolors.print_value(logger,
-                                    sp + i[0],
-                                    format_list_of_str(i[1]),
-                                    2)
-    logger.write("\n", level)
-
 class Progress_bar:
     "Create a progress bar in the terminal"
     
index 87d732c2ea03b9ba0c07336a6831a9ac941edcae..7fd0210b6a5765357c050964df4c3123dd0e3805 100644 (file)
@@ -20,6 +20,7 @@
 
 import src.debug as DBG
 import src.returnCode as RCO
+import src.utilsSat as UTS
 from src.salomeTools import _BaseCommand
 import src.pyconf as PYCONF
 
@@ -89,8 +90,9 @@ class Command(_BaseCommand):
     # Make the generator module visible by python
     sys.path.insert(0, yacsgen_dir)
 
-    src.printcolors.print_value(logger, _("YACSGEN dir"), yacsgen_dir, 3)
-    logger.write("\n", 2)
+    logger.info(" insert directory PATH %s = %s\n" % \
+                ("YACSGEN", UTS.blue(yacsgen_dir)
+
     products = runner.cfg.APPLICATION.products
     if options.products:
         products = options.products
@@ -171,11 +173,13 @@ def generate_component(config, compo, product_info, context, header, logger):
         cpplib = "lib" + compo + "CXX.so"
     cpp_path = product_info.install_dir
 
-    logger.write("%s\n" % header, 4, False)
-    src.printcolors.print_value(logger, "hxxfile", hxxfile, 4)
-    src.printcolors.print_value(logger, "cpplib", cpplib, 4)
-    src.printcolors.print_value(logger, "cpp_path", cpp_path, 4)
-
+    msg = ""
+    msg += "%s\n" % UTS.blue(header)
+    msg += "hxxfile  = %s\n" % hxxfile
+    msg += "cpplib   = %s\n" % cpplib
+    msg += "cpp_path = %s\n" % cpp_path
+    logger.debug(msg)
+    
     # create a product_info at runtime
     compo_info = PYCONF.Mapping(config)
     compo_info.name = compo
index aebe13aab6bd37e539fbd7bb711842a63850bbfa..018427afa4c83b9ea085238fb472694afae690e4 100644 (file)
@@ -202,8 +202,8 @@ def generate_catalog(machines, config, logger):
     machines = filter(lambda l: len(l) > 0, machines)
     
     # log something
-    src.printcolors.print_value(logger, _("Generate Resources Catalog"),
-                                ", ".join(machines), 4)
+    logger.debug("  %s = %s\n" % \
+                 (_("Generate Resources Catalog"),", ".join(machines))
     
     # The command to execute on each machine in order to get some information
     cmd = '"cat /proc/cpuinfo | grep MHz ; cat /proc/meminfo | grep MemTotal"'
index 6d4d536f354a971fb6c4db66f24d4cf63a57c55e..c3c6b90c66e3fa0e04a413fec3d6653e47b32ccf 100644 (file)
@@ -29,6 +29,7 @@ from commands.application import get_SALOME_modules
 
 import src.debug as DBG
 import src.returnCode as RCO
+import src.utilsSat as UTS
 from src.salomeTools import _BaseCommand
 import src.pyconf as PYCONF
 import src.utilsSat as UTS
@@ -254,7 +255,7 @@ class Command(_BaseCommand):
  
     path_targz = os.path.join(dir_name, archive_name + ".tgz")
     
-    src.printcolors.print_value(logger, "Package path", path_targz, 2)
+    logger.info("  Package path = %s\n" UTS.blue(path_targz))
 
     # Create a working directory for all files that are produced during the
     # package creation and that will be removed at the end of the command
@@ -371,8 +372,7 @@ class Command(_BaseCommand):
     shutil.rmtree(tmp_working_dir)
     
     # Print again the path of the package
-    logger.write("\n", 2)
-    src.printcolors.print_value(logger, "Package path", path_targz, 2)
+    logger.info("  Package path = %s\n" UTS.blue(path_targz))
     
     return res
 
index 0fd935dccea7cf09c4175de0f6206a3d3da67203..629252d50901c44f8bf7918d4a6b412426569ce6 100644 (file)
@@ -22,6 +22,7 @@ import subprocess
 
 import src.debug as DBG
 import src.returnCode as RCO
+import src.utilsSat as UTS
 from src.salomeTools import _BaseCommand
 import commands.prepare
 
@@ -69,15 +70,13 @@ class Command(_BaseCommand):
     options = self.getOptions()
 
     # check that the command has been called with an application
-    src.check_config_has_application( runner.cfg )
+    src.check_config_has_application( config )
 
     # Print some informations
-    logger.write('Patching sources of the application %s\n' % 
-                src.printcolors.printcLabel(runner.cfg.VARS.application), 1)
+    logger.info("Patching sources of the application %s\n" % \
+                UTS.blue(config.VARS.application))
 
-    src.printcolors.print_value(logger, 'workdir', 
-                                runner.cfg.APPLICATION.workdir, 2)
-    logger.write("\n", 2, False)
+    logger.info('  workdir = %s\n\n"', UTS.blue(config.APPLICATION.workdir))
 
     # Get the products list with products informations regarding the options
     products_infos = commands.prepare.get_products_list(options, runner.cfg, logger)
index 2acba8c888eff7ea5c6c01ae0db2169a6e9a35fc..fb73fc3c1e4b93b8c947c9fad7335ff1b08df6af 100644 (file)
@@ -22,6 +22,7 @@ import subprocess
 
 import src.debug as DBG
 import src.returnCode as RCO
+import src.utilsSat as UTS
 from src.salomeTools import _BaseCommand
 
 ########################################################################
@@ -89,9 +90,7 @@ Did you run the command 'sat launcher' ?\n""") % launcher_path
     command = launcher_path + " " + " ".join(args)
 
     # Print the command
-    src.printcolors.print_value(logger, _("Executed command"), command, 2)
-    logger.write(_("Launching ...\n"))
-    logger.flush()
+    logger.info(_("Executed command <blue>%s<reset> Launching ...\n") % command)
     
     # Run the launcher
     subprocess.call(command,
index 52366746eb391f4abc63ce4bcc788675f797e625..74f216b850dbfa99e622d67201c27752aaa000c7 100644 (file)
@@ -73,9 +73,7 @@ class Command(_BaseCommand):
     # Print some informations
     logger.write(_('Getting sources of the application %s\n') % \
                 src.printcolors.printcLabel(config.VARS.application), 1)
-    src.printcolors.print_value(logger, 'workdir', 
-                                config.APPLICATION.workdir, 2)
-    logger.write("\n", 2, False)
+    logger.info("  workdir = %s\n" % config.APPLICATION.workdir)
        
     # Get the products list with products informations regarding the options
     products_infos = self.get_products_list(options, config, logger)
index 3e360e380bfaef7664144602d9c4f2956af32d68..e6c1feffb684c7848771091d169b69fd03180fb3 100644 (file)
@@ -26,6 +26,7 @@ import re
 
 import src.debug as DBG
 import src.returnCode as RCO
+import src.utilsSat as UTS
 from src.salomeTools import _BaseCommand
 
 # Compatibility python 2/3 for input function
@@ -159,11 +160,12 @@ Optional: dictionary to generate the configuration for salomeTools.
     #        if rep.upper() != _("YES"):
     #            return 1
 
-    logger.write(_('Create sources from template\n'), 1)
-    src.printcolors.print_value(logger, 'destination', target_dir, 2)
-    src.printcolors.print_value(logger, 'name', options.name, 2)
-    src.printcolors.print_value(logger, 'template', options.template, 2)
-    logger.write("\n", 3, False)
+    msg = ""
+    msg += _('Create sources from template\n')
+    msg += '  destination = %s\n' % target_dir
+    msg += '  name = %\ns' % options.name
+    msg += '  template = %s\n' % options.template
+    logger.write(msg)
     
     conf_values = None
     if options.param is not None:
@@ -483,7 +485,7 @@ def prepare_from_template(config,
 
 def get_template_info(config, template_name, logger):
     sources = search_template(config, template_name)
-    src.printcolors.print_value(logger, _("Template"), sources)
+    logger.info("  Template = %s\n" %  sources)
 
     # read settings
     tmpdir = os.path.join(config.VARS.tmp_root, "tmp_template")
@@ -500,45 +502,45 @@ def get_template_info(config, template_name, logger):
         raise Exception(_("Settings file not found"))
     tsettings = TemplateSettings("NAME", settings_file, "target")
     
-    logger.write("\n", 3)
+    skip = "\n"*3
+    msg = skip
     if len(tsettings.info) == 0:
-        logger.write(src.printcolors.printcWarning(_(
-                                       "No information for this template.")), 3)
+        msg += UTS.red("No information for this template.")
     else:
-        logger.write(tsettings.info, 3)
+        msg += tsettings.info
 
-    logger.write("\n", 3)
-    logger.write("= Configuration", 3)
-    src.printcolors.print_value(logger,
-                                "file substitution key",
-                                tsettings.file_subst)
-    src.printcolors.print_value(logger,
-                                "subsitution key",
-                                tsettings.delimiter_char)
+    msg += "\n= Configuration\n"
+    msg += "  file substitution key = %s\n" % tsettings.file_subst
+    msg += "  substitution key = '%s'\n" % tsettings.delimiter_char)
     if len(tsettings.ignore_filters) > 0:
-        src.printcolors.print_value(logger,
-                                    "Ignore Filter",
-                                    ', '.join(tsettings.ignore_filters))
+        msg += " Ignore Filter = %s\n" % ', '.join(tsettings.ignore_filters)
 
-    logger.write("\n", 3)
-    logger.write("= Parameters", 3)
+    logger.info(msg)
+    
+    msg = skip
+    msg += "= Parameters\n"
     pnames = []
     for pp in tsettings.parameters:
         tt = TParam(pp, "NAME")
         pnames.append(tt.name)
-        src.printcolors.print_value(logger, "Name", tt.name)
-        src.printcolors.print_value(logger, "Prompt", tt.raw_prompt)
-        src.printcolors.print_value(logger, "Default value", tt.default)
-        logger.write("\n", 3)
+        msg += "  Name = %s\n" % tt.name
+        msg += "  Prompt = %s\n" % tt.raw_prompt
+        msg += "  Default value = %s\n" % tt.default
 
+    logger.info(msg)
+    
     retcode = 0
-    logger.write("= Verification\n", 3)
+    
+    msg = skip
+    msg += "= Verification\n",)
     if tsettings.file_subst not in pnames:
-        logger.write(
-                     "file substitution key not defined as a "
-                     "parameter: %s" % tsettings.file_subst, 3)
+        msg += "file substitution key not defined as a parameter: %s\n" % \
+                tsettings.file_subst
         retcode = 1
     
+    logger.info(msg)
+    
+    msg = ""
     reexp = tsettings.delimiter_char.replace("$", "\$") + "{(?P<name>\S[^}]*)"
     pathlen = len(tmpdir) + 1
     for root, __, files in os.walk(tmpdir):
@@ -552,16 +554,17 @@ def get_template_info(config, template_name, logger):
             zz = list(set(zz)) # reduce
             zz = filter(lambda l: l not in pnames, zz)
             if len(zz) > 0:
-                logger.write("Missing definition in %s: %s" % \
-                    ( src.printcolors.printcLabel(fpath[pathlen:]), ", ".join(zz) ), 3)
+                msg += "Missing definition in %s: %s\n" % \
+                      ( fpath[pathlen:], ", ".join(zz) )
                 retcode = 1
 
+    logger.info(msg)
+    
     if retcode == 0:
-        logger.write(src.printcolors.printc("OK"), 3)
+        logger.info("<OK>" + skip)
     else:
-        logger.write(src.printcolors.printc("KO"), 3)
+        logger.info("<KO>" + skip)
 
-    logger.write("\n", 3)
 
     # clean up tmp file
     shutil.rmtree(tmpdir)
index 974d48d1e456473bc2157b2a1d7baedb73d4e412..461f77c70a492fcbc9255bfaddc245e869be284d 100644 (file)
@@ -26,6 +26,7 @@ import gzip
 
 import src.debug as DBG
 import src.returnCode as RCO
+import src.utilsSat as UTS
 from src.salomeTools import _BaseCommand
 import src.ElementTree as etree
 from src.xmlManager import add_simple_node
@@ -226,10 +227,11 @@ Optional: set the display where to launch SALOME.
     elif with_application and "test_base" in runner.cfg.APPLICATION:
         test_base = runner.cfg.APPLICATION.test_base.name
 
-    src.printcolors.print_value(logger, _('Display'), os.environ['DISPLAY'], 2)
-    src.printcolors.print_value(logger, _('Timeout'),
-                                src.test_module.DEFAULT_TIMEOUT, 2)
-    src.printcolors.print_value(logger, _("Working dir"), base_dir, 3)
+    fmt = "  %s = %s\n"
+    msg  = fmt % (_('Display'), os.environ['DISPLAY'])
+    msg += fmt % (_('Timeout'), src.test_module.DEFAULT_TIMEOUT)
+    msg += fmt % (_("Working dir"), base_dir)
+    logger.info(msg)
 
     # create the test object
     test_runner = src.test_module.Test(runner.cfg,
index 91d5e139d781e156b3f80b76d0f9511737f00e76..60e221afc01cdd35f9ddc3a7767a7a3b7bdbfe09 100644 (file)
@@ -557,126 +557,99 @@ def show_product_info(config, name, logger):
     :param logger Logger: The logger instance to use for the display
     '''
     
-    logger.write(_("%s is a product\n") % src.printcolors.printcLabel(name), 2)
-    pinfo = src.product.get_product_config(config, name)
+    def msgAdd(label, value):
+        """
+        local short named macro 
+        appending show_product_info.msg variable
+        """
+        msg += "  %s = %s\n" % (label, value)
+        return
     
+    msg = "" # used msgAdd()
+    msg += _("%s is a product\n") % UTS.blue(name)
+    pinfo = src.product.get_product_config(config, name)
+
     if "depend" in pinfo:
-        src.printcolors.print_value(logger, 
-                                    "depends on", 
-                                    ', '.join(pinfo.depend), 2)
+        msgAdd("depends on", ', '.join(pinfo.depend))
 
     if "opt_depend" in pinfo:
-        src.printcolors.print_value(logger, 
-                                    "optional", 
-                                    ', '.join(pinfo.opt_depend), 2)
+        msgAdd("optional", ', '.join(pinfo.opt_depend))
 
     # information on pyconf
-    logger.write("\n", 2)
-    logger.write(src.printcolors.printcLabel("configuration:") + "\n", 2)
+    msg += UTS.label("configuration:\n")
     if "from_file" in pinfo:
-        src.printcolors.print_value(logger, 
-                                    "pyconf file path", 
-                                    pinfo.from_file, 
-                                    2)
+        msgAdd("pyconf file path", pinfo.from_file)
     if "section" in pinfo:
-        src.printcolors.print_value(logger, 
-                                    "section", 
-                                    pinfo.section, 
-                                    2)
+        msgAdd("section", pinfo.section)
 
     # information on prepare
-    logger.write("\n", 2)
-    logger.write(src.printcolors.printcLabel("prepare:") + "\n", 2)
+    msg += UTS.label("prepare:\n")
 
     is_dev = src.product.product_is_dev(pinfo)
     method = pinfo.get_source
     if is_dev:
         method += " (dev)"
-    src.printcolors.print_value(logger, "get method", method, 2)
+    msgAdd("get method", method)
 
     if method == 'cvs':
-        src.printcolors.print_value(logger, "server", pinfo.cvs_info.server, 2)
-        src.printcolors.print_value(logger, "base module",
-                                    pinfo.cvs_info.module_base, 2)
-        src.printcolors.print_value(logger, "source", pinfo.cvs_info.source, 2)
-        src.printcolors.print_value(logger, "tag", pinfo.cvs_info.tag, 2)
+        msgAdd("server", pinfo.cvs_info.server)
+        msgAdd("base module", pinfo.cvs_info.module_base)
+        msgAdd("source", pinfo.cvs_info.source)
+        msgAdd("tag", pinfo.cvs_info.tag)
 
     elif method == 'svn':
-        src.printcolors.print_value(logger, "repo", pinfo.svn_info.repo, 2)
+        msgAdd("repo", pinfo.svn_info.repo)
 
     elif method == 'git':
-        src.printcolors.print_value(logger, "repo", pinfo.git_info.repo, 2)
-        src.printcolors.print_value(logger, "tag", pinfo.git_info.tag, 2)
+        msgAdd("repo", pinfo.git_info.repo)
+        msgAdd("tag", pinfo.git_info.tag)
 
     elif method == 'archive':
-        src.printcolors.print_value(logger, 
-                                    "get from", 
-                                    check_path(pinfo.archive_info.archive_name), 
-                                    2)
+        msgAdd("get from", check_path(pinfo.archive_info.archive_name))
 
     if 'patches' in pinfo:
         for patch in pinfo.patches:
-            src.printcolors.print_value(logger, "patch", check_path(patch), 2)
+            msgAdd("patch", check_path(patch))
 
     if src.product.product_is_fixed(pinfo):
-        src.printcolors.print_value(logger, "install_dir", 
-                                    check_path(pinfo.install_dir), 2)
+        msgAdd("install_dir", check_path(pinfo.install_dir))
 
+    logger.info(msg) # return possible
     if src.product.product_is_native(pinfo) or src.product.product_is_fixed(pinfo):
         return
     
     # information on compilation
+    msg = "\n\n"
     if src.product.product_compiles(pinfo):
-        logger.write("\n", 2)
-        logger.write(src.printcolors.printcLabel("compile:") + "\n", 2)
-        src.printcolors.print_value(logger, 
-                                    "compilation method", 
-                                    pinfo.build_source, 
-                                    2)
-        
+        msg += "compile:\n"
+        msgAdd("compilation method", pinfo.build_source)
         if pinfo.build_source == "script" and "compil_script" in pinfo:
-            src.printcolors.print_value(logger, 
-                                        "Compilation script", 
-                                        pinfo.compil_script, 
-                                        2)
-        
+            msgAdd("Compilation script", pinfo.compil_script)
         if 'nb_proc' in pinfo:
-            src.printcolors.print_value(logger, "make -j", pinfo.nb_proc, 2)
-    
-        src.printcolors.print_value(logger, 
-                                    "source dir", 
-                                    check_path(pinfo.source_dir), 
-                                    2)
+            msgAdd("make -j", pinfo.nb_proc)
+        msgAdd("source dir", check_path(pinfo.source_dir))
         if 'install_dir' in pinfo:
-            src.printcolors.print_value(logger, 
-                                        "build dir", 
-                                        check_path(pinfo.build_dir), 
-                                        2)
-            src.printcolors.print_value(logger, 
-                                        "install dir", 
-                                        check_path(pinfo.install_dir), 
-                                        2)
+            msgAdd("build dir", check_path(pinfo.build_dir))
+            msgAdd("install dir", check_path(pinfo.install_dir))
         else:
-            logger.write("  %s\n" % src.printcolors.printcWarning(_("no install dir")) , 2)
+            msg += "  %s\n" % UTS.red(_("no install dir"))
     else:
-        logger.write("\n", 2)
-        msg = _("This product does not compile")
-        logger.write("%s\n" % msg, 2)
+        msg += "%s\n" % UTS.red(_("This product does not compile"))
 
+    logger.info(msg)
+    
     # information on environment
-    logger.write("\n", 2)
-    logger.write(src.printcolors.printcLabel("environ :") + "\n", 2)
+    msg = UTS.label("\nenviron:\n")
     if "environ" in pinfo and "env_script" in pinfo.environ:
-        src.printcolors.print_value(logger, 
-                                    "script", 
-                                    check_path(pinfo.environ.env_script), 
-                                    2)
-
-    zz = src.environment.SalomeEnviron(config, 
-                                       src.fileEnviron.ScreenEnviron(logger), 
-                                       False)
+        msgAdd("script", check_path(pinfo.environ.env_script))
+    logger.info(msg)
+    
+    zz = src.environment.SalomeEnviron(
+           config, src.fileEnviron.ScreenEnviron(logger), False)
     zz.set_python_libdirs()
+    
     zz.set_a_product(name, logger)
+    return
         
 def show_patchs(config, logger):
     """
index 9a9056d479976ca8bdc3664f6b69e1e08781cde6..f21b2b453076145aa23d79b3d6867ec108926b0e 100644 (file)
@@ -19,7 +19,7 @@
 
 """
 This file assume DEBUG functionalities use
-- print debug messages in sys.stderr for salomeTools
+- print salomeTools debug messages in sys.stderr
 - show pretty print debug representation from instances of SAT classes
   (pretty print src.pyconf.Config)
 
@@ -39,7 +39,8 @@ import pprint as PP
 _debug = [False] #support push/pop for temporary activate debug outputs
 
 _user = os.environ['USER']
-_developpers = ["christian", "wambeke", ] # crouzet, kloss ...
+# wambeke is christian at home
+_developpers = ["christian", "wambeke", "crouzet"] # crouzet, kloss ...
 
 
 def indent(text, amount=2, ch=' '):
index e874b75ff899a070af1404b780fe2aa0d4ca16a6..baf5a47088d24ddb3f3f4adf95a448c1841d9cec 100755 (executable)
@@ -36,6 +36,7 @@ import imp
 import subprocess
 
 import src.pyconf as PYCONF
+import src.utilsSat as UTS
 
 # directories not considered as test grids
 C_IGNORE_GRIDS = ['.git', '.svn', 'RESSOURCES']
@@ -208,11 +209,8 @@ class Test:
     ##
     # Configure tests base.
     def prepare_testbase(self, test_base_name):
-        src.printcolors.print_value(self.logger,
-                                    _("Test base"),
-                                    test_base_name,
-                                    3)
-        self.logger.write("\n", 3, False)
+        logger = self.logger
+        logger.info("  %s = %s\n" % (_("Test base"), test_base_name))
 
         # search for the test base
         test_base_info = None
@@ -231,8 +229,8 @@ class Test:
                 return 0
         
         if not test_base_info:
-            message = _("ERROR: test base '%s' not found\n") % test_base_name
-            self.logger.write("%s\n" % src.printcolors.printcError(message))
+            msg = _("test base '%s' not found\n") % test_base_name
+            logger.error(UTS.red(msg))
             return 1
 
         if test_base_info.get_sources == "dir":
@@ -739,15 +737,13 @@ class Test:
     ##
     # Runs test testbase.
     def run_testbase_tests(self):
+        logger = self.logger
         res_dir = os.path.join(self.currentDir, "RESSOURCES")
         os.environ['PYTHONPATH'] =  (res_dir + 
                                      os.pathsep + 
                                      os.environ['PYTHONPATH'])
         os.environ['TT_BASE_RESSOURCES'] = res_dir
-        src.printcolors.print_value(self.logger,
-                                    "TT_BASE_RESSOURCES",
-                                    res_dir,
-                                    4)
+        logger.debug("  %s = %s\n" % ("TT_BASE_RESSOURCES", res_dir)
         self.logger.write("\n", 4, False)
 
         self.logger.write(self.write_test_margin(0), 3)
index c89dbf978e77131565d400554886a70517d2ee3d..f4443ed4299c2d24e93c8a4205575a8407a08df9 100644 (file)
 
 """
 utilities for sat
-general useful simple methods 
+general useful simple methods
+all-in-one import srs.utilsSat as UTS
+
+usage:
+  >> import srs.utilsSat as UTS
+  >> UTS.ensure_path_exists(path)
 """
 
 import os
@@ -28,7 +33,9 @@ import errno
 import stat
 
 
-
+##############################################################################
+# file system utilities
+##############################################################################
 def ensure_path_exists(p):
     '''Create a path if not existing
     
@@ -37,153 +44,20 @@ def ensure_path_exists(p):
     if not os.path.exists(p):
         os.makedirs(p)
         
-def check_config_has_application( config, details = None ):
-    '''check that the config has the key APPLICATION. Else raise an exception.
-    
-    :param config class 'common.pyconf.Config': The config.
-    '''
-    if 'APPLICATION' not in config:
-        message = _("An APPLICATION is required. Use 'config --list' to get"
-                    " the list of available applications.\n")
-        if details :
-            details.append(message)
-        raise Exception( message )
-
-def check_config_has_profile( config, details = None ):
-    '''check that the config has the key APPLICATION.profile.
-       Else, raise an exception.
-    
-    :param config class 'common.pyconf.Config': The config.
-    '''
-    check_config_has_application(config)
-    if 'profile' not in config.APPLICATION:
-        message = _("A profile section is required in your application.\n")
-        if details :
-            details.append(message)
-        raise Exception( message )
-
-def config_has_application( config ):
-    return 'APPLICATION' in config
-
-def get_cfg_param(config, param_name, default):
-    '''Search for param_name value in config.
-       If param_name is not in config, then return default,
-       else, return the found value
-       
-    :param config class 'common.pyconf.Config': The config.
-    :param param_name str: the name of the parameter to get the value
-    :param default str: The value to return if param_name is not in config
-    :return: see initial description of the function
-    :rtype: str
-    '''
-    if param_name in config:
-        return config[param_name]
-    return default
-
-def print_info(logger, info):
-    '''Prints the tuples that are in info variable in a formatted way.
-    
-    :param logger Logger: The logging instance to use for the prints.
-    :param info list: The list of tuples to display
-    '''
-    # find the maximum length of the first value of the tuples in info
-    smax = max(map(lambda l: len(l[0]), info))
-    # Print each item of info with good indentation
-    for i in info:
-        sp = " " * (smax - len(i[0]))
-        printcolors.print_value(logger, sp + i[0], i[1], 2)
-    logger.write("\n", 2)
-
-def get_base_path(config):
-    '''Returns the path of the products base.
-    
-    :param config Config: The global Config instance.
-    :return: The path of the products base.
-    :rtype: str
-    '''
-    if "base" not in config.LOCAL:
-        local_file_path = os.path.join(config.VARS.salometoolsway,
-                                      "data",
-                                      "local.pyconf")
-        msg = _("Please define a base path in the file %s") % local_file_path
-        raise Exception(msg)
-        
-    base_path = os.path.abspath(config.LOCAL.base)
-    
-    return base_path
-
-def get_launcher_name(config):
-    '''Returns the name of salome launcher.
-    
-    :param config Config: The global Config instance.
-    :return: The name of salome launcher.
-    :rtype: str
-    '''
-    check_config_has_application(config)
-    if 'profile' in config.APPLICATION and 'launcher_name' in config.APPLICATION.profile:
-        launcher_name = config.APPLICATION.profile.launcher_name
-    else:
-        launcher_name = 'salome'
-
-    return launcher_name
-
-def get_log_path(config):
-    '''Returns the path of the logs.
-    
-    :param config Config: The global Config instance.
-    :return: The path of the logs.
-    :rtype: str
+def replace_in_file(filein, strin, strout):
+    '''Replace <strin> by <strout> in file <filein>
     '''
-    if "log_dir" not in config.LOCAL:
-        local_file_path = os.path.join(config.VARS.salometoolsway,
-                                      "data",
-                                      "local.pyconf")
-        msg = _("Please define a log_dir in the file %s") % local_file_path
-        raise Exception(msg)
-      
-    log_dir_path = os.path.abspath(config.LOCAL.log_dir)
-    
-    return log_dir_path
-
-def get_salome_version(config):
-    if hasattr(config.APPLICATION, 'version_salome'):
-        Version = config.APPLICATION.version_salome
-    else:
-        KERNEL_info = product.get_product_config(config, "KERNEL")
-        VERSION = os.path.join(
-                            KERNEL_info.install_dir,
-                            "bin",
-                            "salome",
-                            "VERSION")
-        if not os.path.isfile(VERSION):
-            return None
-            
-        fVERSION = open(VERSION)
-        Version = fVERSION.readline()
-        fVERSION.close()
-        
-    VersionSalome = int(only_numbers(Version))    
-    return VersionSalome
-
-def only_numbers(str_num):
-    return ''.join([nb for nb in str_num if nb in '0123456789'] or '0')
-
-def read_config_from_a_file(filePath):
-        try:
-            cfg_file = pyconf.Config(filePath)
-        except pyconf.ConfigError as e:
-            raise Exception(_("Error in configuration file: %(file)s\n  %(error)s") %
-                { 'file': filePath, 'error': str(e) } )
-        return cfg_file
-
-def get_tmp_filename(cfg, name):
-    if not os.path.exists(cfg.VARS.tmp_root):
-        os.makedirs(cfg.VARS.tmp_root)
-
-    return os.path.join(cfg.VARS.tmp_root, name)
+    shutil.move(filein, filein + "_old")
+    fileout= filein
+    filein = filein + "_old"
+    fin = open(filein, "r")
+    fout = open(fileout, "w")
+    for line in fin:
+        fout.write(line.replace(strin, strout))
 
-##
+##############################################################################
 # Utils class to simplify path manipulations.
+##############################################################################
 class Path:
     def __init__(self, path):
         self.path = str(path)
@@ -325,7 +199,216 @@ def handleRemoveReadonly(func, path, exc):
         func(path)
     else:
         raise
+        
+##############################################################################
+# pyconf config utilities
+##############################################################################
+def check_config_has_application( config, details = None ):
+    '''check that the config has the key APPLICATION. Else raise an exception.
+    
+    :param config class 'common.pyconf.Config': The config.
+    '''
+    if 'APPLICATION' not in config:
+        message = _("An APPLICATION is required. Use 'config --list' to get"
+                    " the list of available applications.\n")
+        if details :
+            details.append(message)
+        raise Exception( message )
+
+def check_config_has_profile( config, details = None ):
+    '''check that the config has the key APPLICATION.profile.
+       Else, raise an exception.
+    
+    :param config class 'common.pyconf.Config': The config.
+    '''
+    check_config_has_application(config)
+    if 'profile' not in config.APPLICATION:
+        message = _("A profile section is required in your application.\n")
+        if details :
+            details.append(message)
+        raise Exception( message )
 
+def config_has_application( config ):
+    return 'APPLICATION' in config
+
+def get_cfg_param(config, param_name, default):
+    '''Search for param_name value in config.
+       If param_name is not in config, then return default,
+       else, return the found value
+       
+    :param config class 'common.pyconf.Config': The config.
+    :param param_name str: the name of the parameter to get the value
+    :param default str: The value to return if param_name is not in config
+    :return: see initial description of the function
+    :rtype: str
+    '''
+    if param_name in config:
+        return config[param_name]
+    return default
+
+def get_base_path(config):
+    '''Returns the path of the products base.
+    
+    :param config Config: The global Config instance.
+    :return: The path of the products base.
+    :rtype: str
+    '''
+    if "base" not in config.LOCAL:
+        local_file_path = os.path.join(config.VARS.salometoolsway,
+                                      "data",
+                                      "local.pyconf")
+        msg = _("Please define a base path in the file %s") % local_file_path
+        raise Exception(msg)
+        
+    base_path = os.path.abspath(config.LOCAL.base)
+    
+    return base_path
+
+def get_launcher_name(config):
+    '''Returns the name of salome launcher.
+    
+    :param config Config: The global Config instance.
+    :return: The name of salome launcher.
+    :rtype: str
+    '''
+    check_config_has_application(config)
+    if 'profile' in config.APPLICATION and 'launcher_name' in config.APPLICATION.profile:
+        launcher_name = config.APPLICATION.profile.launcher_name
+    else:
+        launcher_name = 'salome'
+
+    return launcher_name
+
+def get_log_path(config):
+    '''Returns the path of the logs.
+    
+    :param config Config: The global Config instance.
+    :return: The path of the logs.
+    :rtype: str
+    '''
+    if "log_dir" not in config.LOCAL:
+        local_file_path = os.path.join(config.VARS.salometoolsway,
+                                      "data",
+                                      "local.pyconf")
+        msg = _("Please define a log_dir in the file %s") % local_file_path
+        raise Exception(msg)
+      
+    log_dir_path = os.path.abspath(config.LOCAL.log_dir)
+    
+    return log_dir_path
+
+def get_salome_version(config):
+    if hasattr(config.APPLICATION, 'version_salome'):
+        Version = config.APPLICATION.version_salome
+    else:
+        KERNEL_info = product.get_product_config(config, "KERNEL")
+        VERSION = os.path.join(
+                            KERNEL_info.install_dir,
+                            "bin",
+                            "salome",
+                            "VERSION")
+        if not os.path.isfile(VERSION):
+            return None
+            
+        fVERSION = open(VERSION)
+        Version = fVERSION.readline()
+        fVERSION.close()
+        
+    VersionSalome = int(only_numbers(Version))    
+    return VersionSalome
+
+def only_numbers(str_num):
+    return ''.join([nb for nb in str_num if nb in '0123456789'] or '0')
+
+def read_config_from_a_file(filePath):
+    try:
+        cfg_file = pyconf.Config(filePath)
+    except pyconf.ConfigError as e:
+        raise Exception(_("Error in configuration file: %(file)s\n  %(error)s") %
+            { 'file': filePath, 'error': str(e) } )
+    return cfg_file
+
+def get_tmp_filename(config, name):
+    if not os.path.exists(config.VARS.tmp_root):
+        os.makedirs(config.VARS.tmp_root)
+
+    return os.path.join(config.VARS.tmp_root, name)
+
+def get_property_in_product_cfg(product_cfg, pprty):
+    if not "properties" in product_cfg:
+        return None
+    if not pprty in product_cfg.properties:
+        return None
+    return product_cfg.properties[pprty]
+
+##############################################################################
+# logger and color utilities
+##############################################################################
+def formatTuples(tuples):
+    '''format the tuples variable in a tabulated way.
+    
+    :param tuples list: The list of tuples to format
+    :return: The tabulated text. (lines '   label = value')
+    '''
+    # find the maximum length of the first value of the tuples in info
+    smax = max(map(lambda l: len(l[0]), tuples))
+    # Print each item of tuples with good indentation
+    msg = ""
+    for i in info:
+        sp = " " * (smax - len(i[0]))
+        msg += sp + "%s = %s\n" % i[0:1] # tuples, may be longer
+    if len(info) > 1: msg += "\n" # for long list
+    return msg
+    
+def formatValue(label, value, suffix=""):
+    """format 'label = value' with the info color
+    
+    :param label int: the label to print.
+    :param value str: the value to print.
+    :param suffix str: the suffix to add at the end.
+    """
+    msg = "  %s = %s %s" % (label, value, suffix)
+    return msg
+    
+def print_info(logger, tuples):
+    '''format the tuples variable in a tabulated way.
+    
+    :param logger Logger: The logging instance to use for the prints.
+    :param tuples list: The list of tuples to display
+    '''
+    msg = formatTuples(tuples)
+    logger.info(msg)
+    
+_colors = "BLACK RED GREEN YELLOW BLUE MAGENTA CYAN WHITE".lower().split(" ")
+
+def black(msg):
+    return "<black>"+msg+"<reset>"
+
+def red(msg):
+    return "<red>"+msg+"<reset>"
+
+def greem(msg):
+    return "<green>"+msg+"<reset>"
+
+def yellow(msg):
+    return "<yellow>"+msg+"<reset>"
+
+def blue(msg):
+    return "<blue>"+msg+"<reset>"
+
+def magenta(msg):
+    return "<magenta>"+msg+"<reset>"
+
+def cyan(msg):
+    return "<cyan>"+msg+"<reset>"
+
+def white(msg):
+    return "<white>"+msg+"<reset>"
+
+
+##############################################################################
+# list and dict utilities
+##############################################################################
 def deepcopy_list(input_list):
     """ Do a deep copy of a list
     
@@ -352,6 +435,20 @@ def remove_item_from_list(input_list, item):
         res.append(elem)
     return res
 
+def merge_dicts(*dict_args):
+    '''
+    Given any number of dicts, shallow copy and merge into a new dict,
+    precedence goes to key value pairs in latter dicts.
+    '''
+    result = {}
+    for dictionary in dict_args:
+        result.update(dictionary)
+    return result
+    
+    
+##############################################################################
+# date utilities
+##############################################################################
 def parse_date(date):
     """Transform YYYYMMDD_hhmmss into YYYY-MM-DD hh:mm:ss.
     
@@ -369,30 +466,5 @@ def parse_date(date):
                                  date[13:])
     return res
 
-def merge_dicts(*dict_args):
-    '''
-    Given any number of dicts, shallow copy and merge into a new dict,
-    precedence goes to key value pairs in latter dicts.
-    '''
-    result = {}
-    for dictionary in dict_args:
-        result.update(dictionary)
-    return result
 
-def replace_in_file(filein, strin, strout):
-    '''Replace <strin> by <strout> in file <filein>
-    '''
-    shutil.move(filein, filein + "_old")
-    fileout= filein
-    filein = filein + "_old"
-    fin = open(filein, "r")
-    fout = open(fileout, "w")
-    for line in fin:
-        fout.write(line.replace(strin, strout))
 
-def get_property_in_product_cfg(product_cfg, pprty):
-    if not "properties" in product_cfg:
-        return None
-    if not pprty in product_cfg.properties:
-        return None
-    return product_cfg.properties[pprty]