# 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
########################################################################
# 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
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:
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 = []
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):
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()
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
logger.write("\n", 3, False)
#TODO return code
-##
-# Writes all the environment files
def write_all_source_files(config,
logger,
out_dir=None,
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
import src.debug as DBG
import src.returnCode as RCO
+import src.utilsSat as UTS
from src.salomeTools import _BaseCommand
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"
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
# 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
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
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"'
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
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
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
import src.debug as DBG
import src.returnCode as RCO
+import src.utilsSat as UTS
from src.salomeTools import _BaseCommand
import commands.prepare
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)
import src.debug as DBG
import src.returnCode as RCO
+import src.utilsSat as UTS
from src.salomeTools import _BaseCommand
########################################################################
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,
# 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)
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
# 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:
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")
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):
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)
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
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,
: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):
"""
"""
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)
_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=' '):
import subprocess
import src.pyconf as PYCONF
+import src.utilsSat as UTS
# directories not considered as test grids
C_IGNORE_GRIDS = ['.git', '.svn', 'RESSOURCES']
##
# 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
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":
##
# 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)
"""
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
import stat
-
+##############################################################################
+# file system utilities
+##############################################################################
def ensure_path_exists(p):
'''Create a path if not existing
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)
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
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.
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]