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.
175 enable_simple_env_script = True):
178 :param cfg Config: the global config
179 :param environ Environ: the Environ instance where
180 to store the environment variables
181 :param forBuild bool: If true, it is a launch environment,
183 :param for_package str: If not None, produce a relative environment
184 designed for a package.
186 self.environ = environ
188 self.forBuild = forBuild
189 self.for_package = for_package
190 self.enable_simple_env_script = enable_simple_env_script
194 """easy non exhaustive quick resume for debug print"""
196 res["environ"]=str(self.environ)
197 res["forBuild"]=self.forBuild
198 return self.__class__.__name__ + str(res)[0:-1] + " ...etc...}"
200 def append(self, key, value, sep=os.pathsep):
201 '''append value to key using sep
203 :param key str: the environment variable to append
204 :param value str: the value to append to key
205 :param sep str: the separator string
207 return self.environ.append(key, value, sep)
209 def prepend(self, key, value, sep=os.pathsep):
210 '''prepend value to key using sep
212 :param key str: the environment variable to prepend
213 :param value str: the value to prepend to key
214 :param sep str: the separator string
216 return self.environ.prepend(key, value, sep)
218 def is_defined(self, key):
219 '''Check if the key exists in the environment
221 :param key str: the environment variable to check
223 return self.environ.is_defined(key)
226 '''Get the value of the environment variable "key"
228 :param key str: the environment variable
230 return self.environ.get(key)
232 def set(self, key, value):
233 '''Set the environment variable "key" to value "value"
235 :param key str: the environment variable to set
236 :param value str: the value
238 # check if value needs to be evaluated
239 if value is not None and value.startswith("`") and value.endswith("`"):
240 res = subprocess.Popen("echo %s" % value,
242 stdout=subprocess.PIPE).communicate()
243 value = res[0].strip()
245 return self.environ.set(key, value)
248 """Write the environment to out
250 :param out file: the stream where to write the environment
252 for k in self.environ.environ.keys():
257 out.write("%s=%s\n" % (k, value))
259 def add_line(self, nb_line):
260 """Add empty lines to the out stream (in case of file generation)
262 :param nb_line int: the number of empty lines to add
264 if 'add_line' in dir(self.environ):
265 self.environ.add_line(nb_line)
267 def add_comment(self, comment):
268 """Add a commentary to the out stream (in case of file generation)
270 :param comment str: the commentary to add
272 if 'add_comment' in dir(self.environ):
273 self.environ.add_comment(comment)
275 def add_warning(self, warning):
276 """Add a warning to the out stream (in case of file generation)
278 :param warning str: the warning to add
280 if 'add_warning' in dir(self.environ):
281 self.environ.add_warning(warning)
283 def finish(self, required):
284 """Add a final instruction in the out file (in case of file generation)
286 :param required bool: Do nothing if required is False
288 if 'finish' in dir(self.environ):
289 self.environ.add_line(1)
290 self.environ.add_comment("clean all the path")
291 self.environ.finish(required)
293 def set_python_libdirs(self):
294 """Set some generic variables for python library paths
296 ver = self.get('PYTHON_VERSION')
297 self.set('PYTHON_LIBDIR0', os.path.join('lib',
300 self.set('PYTHON_LIBDIR1', os.path.join('lib64',
304 self.python_lib0 = self.get('PYTHON_LIBDIR0')
305 self.python_lib1 = self.get('PYTHON_LIBDIR1')
307 def get_names(self, lProducts):
308 """Get the products name to add in SALOME_MODULES environment variable
309 It is the name of the product, except in the case where the is a
310 component name. And it has to be in SALOME_MODULES variable only
311 if the product has the property has_salome_hui = "yes"
313 :param lProducts list: List of products to potentially add
315 lProdHasGui = [p for p in lProducts if 'properties' in
316 src.product.get_product_config(self.cfg, p) and
318 src.product.get_product_config(self.cfg, p).properties and
319 src.product.get_product_config(self.cfg,
320 p).properties.has_salome_gui=='yes']
322 for ProdName in lProdHasGui:
323 pi = src.product.get_product_config(self.cfg, ProdName)
324 if 'component_name' in pi:
325 lProdName.append(pi.component_name)
327 lProdName.append(ProdName)
330 def set_application_env(self, logger):
331 """Sets the environment defined in the APPLICATION file.
333 :param logger Logger: The logger instance to display messages
336 # Set the variables defined in the "environ" section
337 if 'environ' in self.cfg.APPLICATION:
338 # we write PRODUCT environment it in order to conform to
340 self.add_comment("PRODUCT environment")
341 self.load_cfg_environment(self.cfg.APPLICATION.environ)
342 if self.forBuild and "build" in self.cfg.APPLICATION.environ:
343 self.load_cfg_environment(self.cfg.APPLICATION.environ.build)
344 if not self.forBuild and "launch" in self.cfg.APPLICATION.environ:
345 self.load_cfg_environment(self.cfg.APPLICATION.environ.launch)
348 # If there is an "environ_script" section, load the scripts
349 if 'environ_script' in self.cfg.APPLICATION:
350 for pscript in self.cfg.APPLICATION.environ_script:
351 self.add_comment("script %s" % pscript)
352 sname = pscript.replace(" ", "_")
353 self.run_env_script("APPLICATION_%s" % sname,
354 self.cfg.APPLICATION.environ_script[pscript],
358 def set_salome_minimal_product_env(self, product_info, logger):
359 """Sets the minimal environment for a SALOME product.
360 xxx_ROOT_DIR and xxx_SRC_DIR
362 :param product_info Config: The product description
363 :param logger Logger: The logger instance to display messages
366 root_dir = product_info.name + "_ROOT_DIR"
367 if not self.is_defined(root_dir):
368 if 'install_dir' in product_info and product_info.install_dir:
369 self.set(root_dir, product_info.install_dir)
370 elif not self.silent:
371 logger.write(" " + _("No install_dir for product %s\n") %
372 product_info.name, 5)
374 source_in_package = src.get_property_in_product_cfg(product_info,
375 "sources_in_package")
376 if not self.for_package or source_in_package == "yes":
377 # set source dir, unless no source dir
378 if not src.product.product_is_fixed(product_info):
379 src_dir = product_info.name + "_SRC_DIR"
380 if not self.is_defined(src_dir):
381 if not self.for_package:
382 self.set(src_dir, product_info.source_dir)
384 self.set(src_dir, os.path.join("out_dir_Path",
388 def set_salome_generic_product_env(self, pi):
389 """Sets the generic environment for a SALOME product.
391 :param pi Config: The product description
393 # Construct XXX_ROOT_DIR
394 env_root_dir = self.get(pi.name + "_ROOT_DIR")
395 l_binpath_libpath = []
397 # create additional ROOT_DIR for CPP components
398 if 'component_name' in pi:
399 compo_name = pi.component_name
400 if compo_name + "CPP" == pi.name:
401 compo_root_dir = compo_name + "_ROOT_DIR"
402 envcompo_root_dir = os.path.join(
403 self.cfg.TOOLS.common.install_root, compo_name )
404 self.set(compo_root_dir , envcompo_root_dir)
405 bin_path = os.path.join(envcompo_root_dir, 'bin', 'salome')
406 lib_path = os.path.join(envcompo_root_dir, 'lib', 'salome')
407 l_binpath_libpath.append( (bin_path, lib_path) )
409 if src.get_property_in_product_cfg(pi, "fhs"):
410 lib_path = os.path.join(env_root_dir, 'lib')
411 pylib1_path = os.path.join(env_root_dir, self.python_lib0)
412 pylib2_path = os.path.join(env_root_dir, self.python_lib1)
413 bin_path = os.path.join(env_root_dir, 'bin')
415 lib_path = os.path.join(env_root_dir, 'lib', 'salome')
416 pylib1_path = os.path.join(env_root_dir, self.python_lib0, 'salome')
417 pylib2_path = os.path.join(env_root_dir, self.python_lib1, 'salome')
418 bin_path = os.path.join(env_root_dir, 'bin', 'salome')
420 # Construct the paths to prepend to PATH and LD_LIBRARY_PATH and
422 l_binpath_libpath.append( (bin_path, lib_path) )
424 for bin_path, lib_path in l_binpath_libpath:
425 if not self.forBuild:
426 self.prepend('PATH', bin_path)
427 if src.architecture.is_windows():
428 self.prepend('PATH', lib_path)
430 self.prepend('LD_LIBRARY_PATH', lib_path)
432 l = [ bin_path, lib_path, pylib1_path, pylib2_path ]
433 self.prepend('PYTHONPATH', l)
435 def set_cpp_env(self, product_info):
436 """Sets the generic environment for a SALOME cpp product.
438 :param product_info Config: The product description
440 # Construct XXX_ROOT_DIR
441 env_root_dir = self.get(product_info.name + "_ROOT_DIR")
442 l_binpath_libpath = []
444 # Construct the paths to prepend to PATH and LD_LIBRARY_PATH and
446 bin_path = os.path.join(env_root_dir, 'bin')
447 lib_path = os.path.join(env_root_dir, 'lib')
448 l_binpath_libpath.append( (bin_path, lib_path) )
450 for bin_path, lib_path in l_binpath_libpath:
451 if not self.forBuild:
452 self.prepend('PATH', bin_path)
453 if src.architecture.is_windows():
454 self.prepend('PATH', lib_path)
456 self.prepend('LD_LIBRARY_PATH', lib_path)
458 l = [ bin_path, lib_path,
459 os.path.join(env_root_dir, self.python_lib0),
460 os.path.join(env_root_dir, self.python_lib1)
462 self.prepend('PYTHONPATH', l)
464 def load_cfg_environment(self, cfg_env):
465 """Loads environment defined in cfg_env
467 :param cfg_env Config: A config containing an environment
469 # Loop on cfg_env values
470 for env_def in cfg_env:
471 val = cfg_env[env_def]
473 # if it is env_script, do not do anything (reserved keyword)
474 if env_def == "env_script":
477 # if it is a dict, do not do anything
478 if isinstance(val, src.pyconf.Mapping):
481 # if it is a list, loop on its values
482 if isinstance(val, src.pyconf.Sequence):
483 # transform into list of strings
489 # "_" means that the value must be prepended
490 if env_def.startswith("_"):
491 # separator exception for PV_PLUGIN_PATH
492 if env_def[1:] == 'PV_PLUGIN_PATH':
493 self.prepend(env_def[1:], val, ';')
495 self.prepend(env_def[1:], val)
496 elif env_def.endswith("_"):
497 # separator exception for PV_PLUGIN_PATH
498 if env_def[:-1] == 'PV_PLUGIN_PATH':
499 self.append(env_def[:-1], val, ';')
501 self.append(env_def[:-1], val)
503 self.set(env_def, val)
505 def set_a_product(self, product, logger):
506 """Sets the environment of a product.
508 :param product str: The product name
509 :param logger Logger: The logger instance to display messages
512 # Get the informations corresponding to the product
513 pi = src.product.get_product_config(self.cfg, product)
516 pi.install_dir = os.path.join("out_dir_Path",
521 logger.write(_("Setting environment for %s\n") % product, 4)
524 self.add_comment('setting environ for ' + product)
526 # Do not define environment if the product is native
527 if src.product.product_is_native(pi):
528 if src.product.product_has_env_script(pi):
529 self.run_env_script(pi, native=True)
532 # Set an additional environment for SALOME products
533 if src.product.product_is_salome(pi):
534 # set environment using definition of the product
535 self.set_salome_minimal_product_env(pi, logger)
536 self.set_salome_generic_product_env(pi)
538 if src.product.product_is_cpp(pi):
539 # set a specific environment for cpp modules
540 self.set_salome_minimal_product_env(pi, logger)
543 if src.product.product_is_generated(pi):
544 if "component_name" in pi:
545 # hack the source and install directories in order to point
546 # on the generated product source install directories
547 install_dir_save = pi.install_dir
548 source_dir_save = pi.source_dir
550 pi.install_dir = os.path.join(self.cfg.APPLICATION.workdir,
554 pi.install_dir = os.path.join("out_dir_Path",
557 pi.source_dir = os.path.join(self.cfg.APPLICATION.workdir,
560 pi.name = pi.component_name
561 self.set_salome_minimal_product_env(pi, logger)
562 self.set_salome_generic_product_env(pi)
564 # Put original values
565 pi.install_dir = install_dir_save
566 pi.source_dir = source_dir_save
569 # Put the environment define in the configuration of the product
571 self.load_cfg_environment(pi.environ)
572 if self.forBuild and "build" in pi.environ:
573 self.load_cfg_environment(pi.environ.build)
574 if not self.forBuild and "launch" in pi.environ:
575 self.load_cfg_environment(pi.environ.launch)
576 # if product_info defines a env_scripts, load it
577 if 'env_script' in pi.environ:
578 self.run_env_script(pi, logger)
583 def run_env_script(self, product_info, logger=None, native=False):
584 """Runs an environment script.
586 :param product_info Config: The product description
587 :param logger Logger: The logger instance to display messages
588 :param native Boolean: if True load set_native_env instead of set_env
590 env_script = product_info.environ.env_script
591 # Check that the script exists
592 if not os.path.exists(env_script):
593 raise src.SatException(_("Environment script not found: %s") %
596 if not self.silent and logger is not None:
597 logger.write(" ** load %s\n" % env_script, 4)
599 # import the script and run the set_env function
602 pyproduct = imp.load_source(product_info.name + "_env_script",
605 pyproduct.set_env(self,
606 product_info.install_dir,
607 product_info.version)
609 if "set_nativ_env" in dir(pyproduct):
610 pyproduct.set_nativ_env(self)
612 __, exceptionValue, exceptionTraceback = sys.exc_info()
613 print(exceptionValue)
615 traceback.print_tb(exceptionTraceback)
616 traceback.print_exc()
618 def run_simple_env_script(self, script_path, logger=None):
619 """Runs an environment script. Same as run_env_script, but with a
620 script path as parameter.
622 :param script_path str: a path to an environment script
623 :param logger Logger: The logger instance to display messages
625 if not self.enable_simple_env_script:
627 # Check that the script exists
628 if not os.path.exists(script_path):
629 raise src.SatException(_("Environment script not found: %s") %
632 if not self.silent and logger is not None:
633 logger.write(" ** load %s\n" % script_path, 4)
635 script_basename = os.path.basename(script_path)
636 if script_basename.endswith(".py"):
637 script_basename = script_basename[:-len(".py")]
639 # import the script and run the set_env function
642 pyproduct = imp.load_source(script_basename + "_env_script",
644 pyproduct.load_env(self)
646 __, exceptionValue, exceptionTraceback = sys.exc_info()
647 print(exceptionValue)
649 traceback.print_tb(exceptionTraceback)
650 traceback.print_exc()
652 def set_products(self, logger, src_root=None):
653 """Sets the environment for all the products.
655 :param logger Logger: The logger instance to display messages
656 :param src_root src: the application working directory
659 self.add_comment('setting environ for all products')
661 # Make sure that the python lib dirs are set after python
662 if "Python" in self.cfg.APPLICATION.products:
663 self.set_a_product("Python", logger)
664 self.set_python_libdirs()
666 # The loop on the products
667 for product in self.cfg.APPLICATION.products.keys():
668 if product == "Python":
670 self.set_a_product(product, logger)
673 def set_full_environ(self, logger, env_info):
674 """Sets the full environment for products
675 specified in env_info dictionary.
677 :param logger Logger: The logger instance to display messages
678 :param env_info list: the list of products
680 # set product environ
681 self.set_application_env(logger)
683 self.set_python_libdirs()
686 for product in env_info:
687 self.set_a_product(product, logger)
690 """Class to dump the environment to a file.
692 def __init__(self, config, logger, out_dir, src_root, env_info=None):
695 :param cfg Config: the global config
696 :param logger Logger: The logger instance to display messages
697 :param out_dir str: The directory path where t put the output files
698 :param src_root str: The application working directory
699 :param env_info str: The list of products to add in the files.
703 self.out_dir = out_dir
704 self.src_root= src_root
706 self.env_info = env_info
708 def write_env_file(self, filename, forBuild, shell, for_package = None):
709 """Create an environment file.
711 :param filename str: the file path
712 :param forBuild bool: if true, the build environment
713 :param shell str: the type of file wanted (.sh, .bat)
714 :return: The path to the generated file
718 self.logger.write(_("Create environment file %s\n") %
719 src.printcolors.printcLabel(filename), 3)
721 # create then env object
722 env_file = open(os.path.join(self.out_dir, filename), "w")
723 tmp = src.fileEnviron.get_file_environ(env_file,
726 env = SalomeEnviron(self.config, tmp, forBuild, for_package=for_package)
727 env.silent = self.silent
729 # Set the environment
730 if self.env_info is not None:
731 env.set_full_environ(self.logger, self.env_info)
733 # set env from the APPLICATION
734 env.set_application_env(self.logger)
736 # The list of products to launch
737 lProductsName = env.get_names(self.config.APPLICATION.products.keys())
738 env.set( "SALOME_MODULES", ','.join(lProductsName))
741 env.set_products(self.logger,
742 src_root=self.src_root)
744 # add cleanup and close
750 def write_cfgForPy_file(self,
754 with_commercial = True):
755 """Append to current opened aFile a cfgForPy
756 environment (SALOME python launcher).
758 :param filename str: the file path
759 :param additional_env dict: a dictionary of additional variables
760 to add to the environment
761 :param for_package str: If not None, produce a relative environment
762 designed for a package.
765 self.logger.write(_("Create configuration file %s\n") %
766 src.printcolors.printcLabel(filename.name), 3)
768 # create then env object
769 tmp = src.fileEnviron.get_file_environ(filename,
772 # environment for launch
773 env = SalomeEnviron(self.config,
776 for_package=for_package,
777 enable_simple_env_script = with_commercial)
778 env.silent = self.silent
780 if self.env_info is not None:
781 env.set_full_environ(self.logger, self.env_info)
783 # set env from PRODUCT
784 env.set_application_env(self.logger)
786 # The list of products to launch
787 lProductsName = env.get_names(self.config.APPLICATION.products.keys())
788 env.set( "SALOME_MODULES", ','.join(lProductsName))
791 env.set_products(self.logger,
792 src_root=self.src_root)
794 # Add the additional environment if it is not empty
795 if len(additional_env) != 0:
796 for variable in additional_env:
797 env.set(variable, additional_env[variable])
799 # add cleanup and close
803 """Definition of a Shell.
805 def __init__(self, name, extension):
808 :param name str: the shell name
809 :param extension str: the shell extension
812 self.extension = extension
814 def load_environment(config, build, logger):
815 """Loads the environment (used to run the tests, for example).
817 :param config Config: the global config
818 :param build bool: build environement if True
819 :param logger Logger: The logger instance to display messages
821 environ = SalomeEnviron(config, Environ(os.environ), build)
822 environ.set_application_env(logger)
823 environ.set_products(logger)