3 # Copyright (C) 2010-2013 CEA/DEN
5 # This library is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU Lesser General Public
7 # License as published by the Free Software Foundation; either
8 # version 2.1 of the License.
10 # This library is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 # Lesser General Public License for more details.
15 # You should have received a copy of the GNU Lesser General Public
16 # License along with this library; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
27 '''Class to manage the environment context
29 def __init__(self, environ=None):
30 '''Initialization. If the environ argument is passed, the environment
31 will be add to it, else it is the external environment.
35 if environ is not None:
36 self.environ = environ
38 self.environ = os.environ
41 """easy non exhaustive quick resume for debug print
44 res["environ"]=self.environ
45 return self.__class__.__name__ + str(res)[0:-1] + " ...etc...}"
47 def _expandvars(self, value):
48 '''replace some $VARIABLE into its actual value in the environment
50 :param value str: the string to be replaced
51 :return: the replaced variable
55 # The string.Template class is a string class
56 # for supporting $-substitutions
57 zt = string.Template(value)
59 value = zt.substitute(self.environ)
60 except KeyError as exc:
61 raise src.SatException(_("Missing definition "
62 "in environment: %s") % str(exc))
65 def append_value(self, key, value, sep=os.pathsep):
66 '''append value to key using sep
68 :param key str: the environment variable to append
69 :param value str: the value to append to key
70 :param sep str: the separator string
72 # check if the key is already in the environment
73 if key in self.environ:
74 value_list = self.environ[key].split(sep)
75 # Check if the value is already in the key value or not
76 if not value in value_list:
77 value_list.append(value)
79 value_list.append(value_list.pop(value_list.index(value)))
80 self.set(key, sep.join(value_list))
84 def append(self, key, value, sep=os.pathsep):
85 '''Same as append_value but the value argument can be a list
87 :param key str: the environment variable to append
88 :param value str or list: the value(s) to append to key
89 :param sep str: the separator string
91 if isinstance(value, list):
93 self.append_value(key, v, sep)
95 self.append_value(key, value, sep)
97 def prepend_value(self, key, value, sep=os.pathsep):
98 '''prepend value to key using sep
100 :param key str: the environment variable to prepend
101 :param value str: the value to prepend to key
102 :param sep str: the separator string
104 if key in self.environ:
105 value_list = self.environ[key].split(sep)
106 if not value in value_list:
107 value_list.insert(0, value)
109 value_list.insert(0, value_list.pop(value_list.index(value)))
110 self.set(key, sep.join(value_list))
114 def prepend(self, key, value, sep=os.pathsep):
115 '''Same as prepend_value but the value argument can be a list
117 :param key str: the environment variable to prepend
118 :param value str or list: the value(s) to prepend to key
119 :param sep str: the separator string
121 if isinstance(value, list):
123 self.prepend_value(key, v, sep)
125 self.prepend_value(key, value, sep)
127 def is_defined(self, key):
128 '''Check if the key exists in the environment
130 :param key str: the environment variable to check
132 return key in self.environ.keys()
134 def set(self, key, value):
135 '''Set the environment variable "key" to value "value"
137 :param key str: the environment variable to set
138 :param value str: the value
140 self.environ[key] = self._expandvars(value)
143 '''Get the value of the environment variable "key"
145 :param key str: the environment variable
147 if key in self.environ:
148 return self.environ[key]
152 def command_value(self, key, command):
153 '''Get the value given by the system command "command"
154 and put it in the environment variable key
156 :param key str: the environment variable
157 :param command str: the command to execute
159 value = subprocess.Popen(command,
161 stdout=subprocess.PIPE,
162 env=self.environ).communicate()[0]
163 self.environ[key] = value
167 """Class to manage the environment of SALOME.
170 def __init__(self, cfg, environ, forBuild=False, for_package=None):
173 :param cfg Config: the global config
174 :param environ Environ: the Environ instance where
175 to store the environment variables
176 :param forBuild bool: If true, it is a launch environment,
178 :param for_package str: If not None, produce a relative environment
179 designed for a package.
181 self.environ = environ
183 self.forBuild = forBuild
184 self.for_package = for_package
188 """easy non exhaustive quick resume for debug print"""
190 res["environ"]=str(self.environ)
191 res["forBuild"]=self.forBuild
192 return self.__class__.__name__ + str(res)[0:-1] + " ...etc...}"
194 def append(self, key, value, sep=os.pathsep):
195 '''append value to key using sep
197 :param key str: the environment variable to append
198 :param value str: the value to append to key
199 :param sep str: the separator string
201 return self.environ.append(key, value, sep)
203 def prepend(self, key, value, sep=os.pathsep):
204 '''prepend value to key using sep
206 :param key str: the environment variable to prepend
207 :param value str: the value to prepend to key
208 :param sep str: the separator string
210 return self.environ.prepend(key, value, sep)
212 def is_defined(self, key):
213 '''Check if the key exists in the environment
215 :param key str: the environment variable to check
217 return self.environ.is_defined(key)
220 '''Get the value of the environment variable "key"
222 :param key str: the environment variable
224 return self.environ.get(key)
226 def set(self, key, value):
227 '''Set the environment variable "key" to value "value"
229 :param key str: the environment variable to set
230 :param value str: the value
232 # check if value needs to be evaluated
233 if value is not None and value.startswith("`") and value.endswith("`"):
234 res = subprocess.Popen("echo %s" % value,
236 stdout=subprocess.PIPE).communicate()
237 value = res[0].strip()
239 return self.environ.set(key, value)
242 """Write the environment to out
244 :param out file: the stream where to write the environment
246 for k in self.environ.environ.keys():
251 out.write("%s=%s\n" % (k, value))
253 def add_line(self, nb_line):
254 """Add empty lines to the out stream (in case of file generation)
256 :param nb_line int: the number of empty lines to add
258 if 'add_line' in dir(self.environ):
259 self.environ.add_line(nb_line)
261 def add_comment(self, comment):
262 """Add a commentary to the out stream (in case of file generation)
264 :param comment str: the commentary to add
266 if 'add_comment' in dir(self.environ):
267 self.environ.add_comment(comment)
269 def add_warning(self, warning):
270 """Add a warning to the out stream (in case of file generation)
272 :param warning str: the warning to add
274 if 'add_warning' in dir(self.environ):
275 self.environ.add_warning(warning)
277 def finish(self, required):
278 """Add a final instruction in the out file (in case of file generation)
280 :param required bool: Do nothing if required is False
282 if 'finish' in dir(self.environ):
283 self.environ.add_line(1)
284 self.environ.add_comment("clean all the path")
285 self.environ.finish(required)
287 def set_python_libdirs(self):
288 """Set some generic variables for python library paths
290 ver = self.get('PYTHON_VERSION')
291 self.set('PYTHON_LIBDIR0', os.path.join('lib',
294 self.set('PYTHON_LIBDIR1', os.path.join('lib64',
298 self.python_lib0 = self.get('PYTHON_LIBDIR0')
299 self.python_lib1 = self.get('PYTHON_LIBDIR1')
301 def get_names(self, lProducts):
302 """Get the products name to add in SALOME_MODULES environment variable
303 It is the name of the product, except in the case where the is a
304 component name. And it has to be in SALOME_MODULES variable only
305 if the product has the property has_salome_hui = "yes"
307 :param lProducts list: List of products to potentially add
309 lProdHasGui = [p for p in lProducts if 'properties' in
310 src.product.get_product_config(self.cfg, p) and
312 src.product.get_product_config(self.cfg, p).properties and
313 src.product.get_product_config(self.cfg,
314 p).properties.has_salome_gui=='yes']
316 for ProdName in lProdHasGui:
317 pi = src.product.get_product_config(self.cfg, ProdName)
318 if 'component_name' in pi:
319 lProdName.append(pi.component_name)
321 lProdName.append(ProdName)
324 def set_application_env(self, logger):
325 """Sets the environment defined in the APPLICATION file.
327 :param logger Logger: The logger instance to display messages
330 # Set the variables defined in the "environ" section
331 if 'environ' in self.cfg.APPLICATION:
332 self.add_comment("APPLICATION environment")
333 for p in self.cfg.APPLICATION.environ:
334 self.set(p, self.cfg.APPLICATION.environ[p])
337 # If there is an "environ_script" section, load the scripts
338 if 'environ_script' in self.cfg.APPLICATION:
339 for pscript in self.cfg.APPLICATION.environ_script:
340 self.add_comment("script %s" % pscript)
341 sname = pscript.replace(" ", "_")
342 self.run_env_script("APPLICATION_%s" % sname,
343 self.cfg.APPLICATION.environ_script[pscript],
347 # If there is profile (SALOME), then define additional variables
348 if ('profile' in self.cfg.APPLICATION and
349 "product" in self.cfg.APPLICATION.profile):
350 profile_product = self.cfg.APPLICATION.profile.product
351 product_info_profile = src.product.get_product_config(self.cfg,
353 profile_share_salome = os.path.join(product_info_profile.install_dir,
356 self.set( "SUITRoot", profile_share_salome )
357 self.set( "SalomeAppConfig",
358 os.path.join(profile_share_salome,
360 profile_product.lower() ) )
363 def set_salome_minimal_product_env(self, product_info, logger):
364 """Sets the minimal environment for a SALOME product.
365 xxx_ROOT_DIR and xxx_SRC_DIR
367 :param product_info Config: The product description
368 :param logger Logger: The logger instance to display messages
371 root_dir = product_info.name + "_ROOT_DIR"
372 if not self.is_defined(root_dir):
373 if 'install_dir' in product_info and product_info.install_dir:
374 self.set(root_dir, product_info.install_dir)
375 elif not self.silent:
376 logger.write(" " + _("No install_dir for product %s\n") %
377 product_info.name, 5)
379 if not self.for_package:
380 # set source dir, unless no source dir
381 if not src.product.product_is_fixed(product_info):
382 src_dir = product_info.name + "_SRC_DIR"
383 if not self.is_defined(src_dir):
384 self.set(src_dir, product_info.source_dir)
386 def set_salome_generic_product_env(self, pi):
387 """Sets the generic environment for a SALOME product.
389 :param pi Config: The product description
391 # Construct XXX_ROOT_DIR
392 env_root_dir = self.get(pi.name + "_ROOT_DIR")
393 l_binpath_libpath = []
395 # create additional ROOT_DIR for CPP components
396 if 'component_name' in pi:
397 compo_name = pi.component_name
398 if compo_name + "CPP" == pi.name:
399 compo_root_dir = compo_name + "_ROOT_DIR"
400 envcompo_root_dir = os.path.join(
401 self.cfg.TOOLS.common.install_root, compo_name )
402 self.set(compo_root_dir , envcompo_root_dir)
403 bin_path = os.path.join(envcompo_root_dir, 'bin', 'salome')
404 lib_path = os.path.join(envcompo_root_dir, 'lib', 'salome')
405 l_binpath_libpath.append( (bin_path, lib_path) )
408 if (src.get_cfg_param(pi, 'product_type', 'SALOME').upper()
409 not in [ "SALOME", "SMESH_PLUGIN", "SAMPLE" ]):
412 # Construct the paths to prepend to PATH and LD_LIBRARY_PATH and
414 bin_path = os.path.join(env_root_dir, 'bin', appliname)
415 lib_path = os.path.join(env_root_dir, 'lib', appliname)
416 l_binpath_libpath.append( (bin_path, lib_path) )
418 for bin_path, lib_path in l_binpath_libpath:
419 if not self.forBuild:
420 self.prepend('PATH', bin_path)
421 if src.architecture.is_windows():
422 self.prepend('PATH', lib_path)
424 self.prepend('LD_LIBRARY_PATH', lib_path)
426 l = [ bin_path, lib_path,
427 os.path.join(env_root_dir, self.python_lib0, appliname),
428 os.path.join(env_root_dir, self.python_lib1, appliname)
430 self.prepend('PYTHONPATH', l)
432 def set_cpp_env(self, product_info):
433 """Sets the generic environment for a SALOME cpp product.
435 :param product_info Config: The product description
437 # Construct XXX_ROOT_DIR
438 env_root_dir = self.get(product_info.name + "_ROOT_DIR")
439 l_binpath_libpath = []
441 # Construct the paths to prepend to PATH and LD_LIBRARY_PATH and
443 bin_path = os.path.join(env_root_dir, 'bin')
444 lib_path = os.path.join(env_root_dir, 'lib')
445 l_binpath_libpath.append( (bin_path, lib_path) )
447 for bin_path, lib_path in l_binpath_libpath:
448 if not self.forBuild:
449 self.prepend('PATH', bin_path)
450 if src.architecture.is_windows():
451 self.prepend('PATH', lib_path)
453 self.prepend('LD_LIBRARY_PATH', lib_path)
455 l = [ bin_path, lib_path,
456 os.path.join(env_root_dir, self.python_lib0),
457 os.path.join(env_root_dir, self.python_lib1)
459 self.prepend('PYTHONPATH', l)
461 def load_cfg_environment(self, cfg_env):
462 """Loads environment defined in cfg_env
464 :param cfg_env Config: A config containing an environment
466 # Loop on cfg_env values
467 for env_def in cfg_env:
468 val = cfg_env[env_def]
470 # if it is env_script, do not do anything (reserved keyword)
471 if env_def == "env_script":
474 # if it is a dict, do not do anything
475 if isinstance(val, src.pyconf.Mapping):
478 # if it is a list, loop on its values
479 if isinstance(val, src.pyconf.Sequence):
480 # transform into list of strings
486 # "_" means that the value must be prepended
487 if env_def.startswith("_"):
488 # separator exception for PV_PLUGIN_PATH
489 if env_def[1:] == 'PV_PLUGIN_PATH':
490 self.prepend(env_def[1:], val, ';')
492 self.prepend(env_def[1:], val)
493 elif env_def.endswith("_"):
494 # separator exception for PV_PLUGIN_PATH
495 if env_def[:-1] == 'PV_PLUGIN_PATH':
496 self.append(env_def[:-1], val, ';')
498 self.append(env_def[:-1], val)
500 self.set(env_def, val)
502 def set_a_product(self, product, logger):
503 """Sets the environment of a product.
505 :param product str: The product name
506 :param logger Logger: The logger instance to display messages
509 # Get the informations corresponding to the product
510 pi = src.product.get_product_config(self.cfg, product)
513 pi.install_dir = os.path.join("out_dir_Path",
517 # Do not define environment if the product is native
518 if src.product.product_is_native(pi):
522 logger.write(_("Setting environment for %s\n") % product, 4)
525 self.add_comment('setting environ for ' + product)
527 # Set an additional environment for SALOME products
528 if src.product.product_is_salome(pi):
529 # set environment using definition of the product
530 self.set_salome_minimal_product_env(pi, logger)
531 self.set_salome_generic_product_env(pi)
533 if src.product.product_is_cpp(pi):
534 # set a specific environment for cpp modules
535 self.set_salome_minimal_product_env(pi, logger)
538 if src.product.product_is_generated(pi):
539 if "component_name" in pi:
540 # hack the source and install directories in order to point
541 # on the generated product source install directories
542 install_dir_save = pi.install_dir
543 source_dir_save = pi.source_dir
545 pi.install_dir = os.path.join(self.cfg.APPLICATION.workdir,
548 pi.source_dir = os.path.join(self.cfg.APPLICATION.workdir,
551 pi.name = pi.component_name
552 self.set_salome_minimal_product_env(pi, logger)
553 self.set_salome_generic_product_env(pi)
555 # Put original values
556 pi.install_dir = install_dir_save
557 pi.source_dir = source_dir_save
560 # Put the environment define in the configuration of the product
562 self.load_cfg_environment(pi.environ)
563 if self.forBuild and "build" in pi.environ:
564 self.load_cfg_environment(pi.environ.build)
565 if not self.forBuild and "launch" in pi.environ:
566 self.load_cfg_environment(pi.environ.launch)
567 # if product_info defines a env_scripts, load it
568 if 'env_script' in pi.environ:
569 self.run_env_script(pi, logger)
574 def run_env_script(self, product_info, logger=None):
575 """Runs an environment script.
577 :param product_info Config: The product description
578 :param logger Logger: The logger instance to display messages
580 env_script = product_info.environ.env_script
581 # Check that the script exists
582 if not os.path.exists(env_script):
583 raise src.SatException(_("Environment script not found: %s") %
586 if not self.silent and logger is not None:
587 logger.write(" ** load %s\n" % env_script, 4)
589 # import the script and run the set_env function
592 pyproduct = imp.load_source(product_info.name + "_env_script",
594 pyproduct.set_env(self, product_info.install_dir,
595 product_info.version)
597 __, exceptionValue, exceptionTraceback = sys.exc_info()
598 print(exceptionValue)
600 traceback.print_tb(exceptionTraceback)
601 traceback.print_exc()
603 def run_simple_env_script(self, script_path, logger=None):
604 """Runs an environment script. Same as run_env_script, but with a
605 script path as parameter.
607 :param script_path str: a path to an environment script
608 :param logger Logger: The logger instance to display messages
610 # Check that the script exists
611 if not os.path.exists(script_path):
612 raise src.SatException(_("Environment script not found: %s") %
615 if not self.silent and logger is not None:
616 logger.write(" ** load %s\n" % script_path, 4)
618 script_basename = os.path.basename(script_path)
619 if script_basename.endswith(".py"):
620 script_basename = script_basename[:-len(".py")]
622 # import the script and run the set_env function
625 pyproduct = imp.load_source(script_basename + "_env_script",
627 pyproduct.load_env(self)
629 __, exceptionValue, exceptionTraceback = sys.exc_info()
630 print(exceptionValue)
632 traceback.print_tb(exceptionTraceback)
633 traceback.print_exc()
635 def set_products(self, logger, src_root=None):
636 """Sets the environment for all the products.
638 :param logger Logger: The logger instance to display messages
639 :param src_root src: the application working directory
642 self.add_comment('setting environ for all products')
644 # Set the application working directory
646 src_root = self.cfg.APPLICATION.workdir
647 self.set('SRC_ROOT', src_root)
651 if "APPLI" in self.cfg and "application_name" in self.cfg.APPLI:
652 appli_name = self.cfg.APPLI.application_name
653 self.set("SALOME_APPLI_ROOT",
654 os.path.join(self.cfg.APPLICATION.workdir, appli_name))
656 # Make sure that the python lib dirs are set after python
657 if "Python" in self.cfg.APPLICATION.products:
658 self.set_a_product("Python", logger)
659 self.set_python_libdirs()
661 # The loop on the products
662 for product in self.cfg.APPLICATION.products.keys():
663 if product == "Python":
665 self.set_a_product(product, logger)
668 def set_full_environ(self, logger, env_info):
669 """Sets the full environment for products
670 specified in env_info dictionary.
672 :param logger Logger: The logger instance to display messages
673 :param env_info list: the list of products
675 # set product environ
676 self.set_application_env(logger)
678 self.set_python_libdirs()
681 for product in env_info:
682 self.set_a_product(product, logger)
685 """Class to dump the environment to a file.
687 def __init__(self, config, logger, out_dir, src_root, env_info=None):
690 :param cfg Config: the global config
691 :param logger Logger: The logger instance to display messages
692 :param out_dir str: The directory path where t put the output files
693 :param src_root str: The application working directory
694 :param env_info str: The list of products to add in the files.
698 self.out_dir = out_dir
699 self.src_root= src_root
701 self.env_info = env_info
703 def write_env_file(self, filename, forBuild, shell):
704 """Create an environment file.
706 :param filename str: the file path
707 :param forBuild bool: if true, the build environment
708 :param shell str: the type of file wanted (.sh, .bat)
709 :return: The path to the generated file
713 self.logger.write(_("Create environment file %s\n") %
714 src.printcolors.printcLabel(filename), 3)
716 # create then env object
717 env_file = open(os.path.join(self.out_dir, filename), "w")
718 tmp = src.fileEnviron.get_file_environ(env_file,
721 env = SalomeEnviron(self.config, tmp, forBuild)
722 env.silent = self.silent
724 # Set the environment
725 if self.env_info is not None:
726 env.set_full_environ(self.logger, self.env_info)
728 # set env from the APPLICATION
729 env.set_application_env(self.logger)
731 # The list of products to launch
732 lProductsName = env.get_names(self.config.APPLICATION.products.keys())
733 env.set( "SALOME_MODULES", ','.join(lProductsName))
736 env.set_products(self.logger,
737 src_root=self.src_root)
739 # add cleanup and close
745 def write_cfgForPy_file(self,
749 """Append to current opened aFile a cfgForPy
750 environment (SALOME python launcher).
752 :param filename str: the file path
753 :param additional_env dict: a dictionary of additional variables
754 to add to the environment
755 :param for_package str: If not None, produce a relative environment
756 designed for a package.
759 self.logger.write(_("Create configuration file %s\n") %
760 src.printcolors.printcLabel(filename.name), 3)
762 # create then env object
763 tmp = src.fileEnviron.get_file_environ(filename,
766 # environment for launch
767 env = SalomeEnviron(self.config,
770 for_package=for_package)
771 env.silent = self.silent
773 if self.env_info is not None:
774 env.set_full_environ(self.logger, self.env_info)
776 # set env from PRODUCT
777 env.set_application_env(self.logger)
779 # The list of products to launch
780 lProductsName = env.get_names(self.config.APPLICATION.products.keys())
781 env.set( "SALOME_MODULES", ','.join(lProductsName))
784 env.set_products(self.logger,
785 src_root=self.src_root)
787 # Add the additional environment if it is not empty
788 if len(additional_env) != 0:
789 for variable in additional_env:
790 env.set(variable, additional_env[variable])
792 # add cleanup and close
796 """Definition of a Shell.
798 def __init__(self, name, extension):
801 :param name str: the shell name
802 :param extension str: the shell extension
805 self.extension = extension
807 def load_environment(config, build, logger):
808 """Loads the environment (used to run the tests, for example).
810 :param config Config: the global config
811 :param build bool: build environement if True
812 :param logger Logger: The logger instance to display messages
814 environ = SalomeEnviron(config, Environ(os.environ), build)
815 environ.set_application_env(logger)
816 environ.set_products(logger)