]> SALOME platform Git repositories - tools/sat.git/blob - src/environment.py
Salome HOME
bug fix: do not crash if there is no test base defined in a project
[tools/sat.git] / src / environment.py
1 #!/usr/bin/env python
2 #-*- coding:utf-8 -*-
3 #  Copyright (C) 2010-2013  CEA/DEN
4 #
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.
9 #
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.
14 #
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
18
19 import os
20 import subprocess
21 import string
22 import sys
23
24 import src
25
26 class Environ:
27     '''Class to manage the environment context
28     '''
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.
32            
33         :param environ dict:  
34         '''
35         if environ is not None:
36             self.environ = environ
37         else:
38             self.environ = os.environ
39
40     def __repr__(self):
41         """easy non exhaustive quick resume for debug print
42         """
43         res={}
44         res["environ"]=self.environ
45         return self.__class__.__name__ + str(res)[0:-1] + " ...etc...}"
46
47     def _expandvars(self, value):
48         '''replace some $VARIABLE into its actual value in the environment
49         
50         :param value str: the string to be replaced
51         :return: the replaced variable
52         :rtype: str
53         '''
54         if "$" in value:
55             # The string.Template class is a string class 
56             # for supporting $-substitutions
57             zt = string.Template(value)
58             try:
59                 value = zt.substitute(self.environ)
60             except KeyError as exc:
61                 raise src.SatException(_("Missing definition "
62                                          "in environment: %s") % str(exc))
63         return value
64
65     def append_value(self, key, value, sep=os.pathsep):
66         '''append value to key using sep
67         
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
71         '''
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)
78             else:
79                 value_list.append(value_list.pop(value_list.index(value)))
80             self.set(key, sep.join(value_list))
81         else:
82             self.set(key, value)
83
84     def append(self, key, value, sep=os.pathsep):
85         '''Same as append_value but the value argument can be a list
86         
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
90         '''
91         if isinstance(value, list):
92             for v in value:
93                 self.append_value(key, v, sep)
94         else:
95             self.append_value(key, value, sep)
96
97     def prepend_value(self, key, value, sep=os.pathsep):
98         '''prepend value to key using sep
99         
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
103         '''
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)
108             else:
109                 value_list.insert(0, value_list.pop(value_list.index(value)))
110             self.set(key, sep.join(value_list))
111         else:
112             self.set(key, value)
113
114     def prepend(self, key, value, sep=os.pathsep):
115         '''Same as prepend_value but the value argument can be a list
116         
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
120         '''
121         if isinstance(value, list):
122             for v in value:
123                 self.prepend_value(key, v, sep)
124         else:
125             self.prepend_value(key, value, sep)
126
127     def is_defined(self, key):
128         '''Check if the key exists in the environment
129         
130         :param key str: the environment variable to check
131         '''
132         return key in self.environ.keys()
133
134     def set(self, key, value):
135         '''Set the environment variable "key" to value "value"
136         
137         :param key str: the environment variable to set
138         :param value str: the value
139         '''
140         self.environ[key] = self._expandvars(value)
141
142     def get(self, key):
143         '''Get the value of the environment variable "key"
144         
145         :param key str: the environment variable
146         '''
147         if key in self.environ:
148             return self.environ[key]
149         else:
150             return ""
151
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
155         
156         :param key str: the environment variable
157         :param command str: the command to execute
158         '''
159         value = subprocess.Popen(command,
160                                  shell=True,
161                                  stdout=subprocess.PIPE,
162                                  env=self.environ).communicate()[0]
163         self.environ[key] = value
164
165
166 class SalomeEnviron:
167     """Class to manage the environment of SALOME.
168     """
169
170     def __init__(self, cfg, environ, forBuild=False, for_package=None):
171         '''Initialization.
172
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, 
177                               else a build one
178         :param for_package str: If not None, produce a relative environment 
179                                 designed for a package. 
180         '''
181         self.environ = environ
182         self.cfg = cfg
183         self.forBuild = forBuild
184         self.for_package = for_package
185         self.silent = False
186
187     def __repr__(self):
188         """easy non exhaustive quick resume for debug print"""
189         res={}
190         res["environ"]=str(self.environ)
191         res["forBuild"]=self.forBuild
192         return self.__class__.__name__ + str(res)[0:-1] + " ...etc...}"
193
194     def append(self, key, value, sep=os.pathsep):
195         '''append value to key using sep
196         
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
200         '''
201         return self.environ.append(key, value, sep)
202
203     def prepend(self, key, value, sep=os.pathsep):
204         '''prepend value to key using sep
205         
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
209         '''
210         return self.environ.prepend(key, value, sep)
211
212     def is_defined(self, key):
213         '''Check if the key exists in the environment
214         
215         :param key str: the environment variable to check
216         '''
217         return self.environ.is_defined(key)
218
219     def get(self, key):
220         '''Get the value of the environment variable "key"
221         
222         :param key str: the environment variable
223         '''
224         return self.environ.get(key)
225
226     def set(self, key, value):
227         '''Set the environment variable "key" to value "value"
228         
229         :param key str: the environment variable to set
230         :param value str: the value
231         '''
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,
235                                    shell=True,
236                                    stdout=subprocess.PIPE).communicate()
237             value = res[0].strip()
238
239         return self.environ.set(key, value)
240
241     def dump(self, out):
242         """Write the environment to out
243         
244         :param out file: the stream where to write the environment
245         """
246         for k in self.environ.environ.keys():
247             try:
248                 value = self.get(k)
249             except:
250                 value = "?"
251             out.write("%s=%s\n" % (k, value))
252
253     def add_line(self, nb_line):
254         """Add empty lines to the out stream (in case of file generation)
255         
256         :param nb_line int: the number of empty lines to add
257         """
258         if 'add_line' in dir(self.environ):
259             self.environ.add_line(nb_line)
260
261     def add_comment(self, comment):
262         """Add a commentary to the out stream (in case of file generation)
263         
264         :param comment str: the commentary to add
265         """
266         if 'add_comment' in dir(self.environ):
267             self.environ.add_comment(comment)
268
269     def add_warning(self, warning):
270         """Add a warning to the out stream (in case of file generation)
271         
272         :param warning str: the warning to add
273         """
274         if 'add_warning' in dir(self.environ):
275             self.environ.add_warning(warning)
276
277     def finish(self, required):
278         """Add a final instruction in the out file (in case of file generation)
279         
280         :param required bool: Do nothing if required is False
281         """
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)
286
287     def set_python_libdirs(self):
288         """Set some generic variables for python library paths
289         """
290         ver = self.get('PYTHON_VERSION')
291         self.set('PYTHON_LIBDIR0', os.path.join('lib',
292                                                 'python' + ver,
293                                                 'site-packages'))
294         self.set('PYTHON_LIBDIR1', os.path.join('lib64',
295                                                 'python' + ver,
296                                                 'site-packages'))
297           
298         self.python_lib0 = self.get('PYTHON_LIBDIR0')
299         self.python_lib1 = self.get('PYTHON_LIBDIR1')
300
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 has_gui = "yes"
306         
307         :param lProducts list: List of products to potentially add
308         """
309         lProdHasGui = [p for p in lProducts if 'type ' in 
310                     src.product.get_product_config(self.cfg, p) and 
311                     src.product.get_product_config(self.cfg, p).type=='salome']
312         lProdName = []
313         for ProdName in lProdHasGui:
314             pi = src.product.get_product_config(self.cfg, ProdName)
315             if 'component_name' in pi:
316                 lProdName.append(pi.component_name)
317             else:
318                 lProdName.append(ProdName)
319         return lProdName
320
321     def set_application_env(self, logger):
322         """Sets the environment defined in the APPLICATION file.
323         
324         :param logger Logger: The logger instance to display messages
325         """
326         
327         # Set the variables defined in the "environ" section
328         if 'environ' in self.cfg.APPLICATION:
329             self.add_comment("APPLICATION environment")
330             for p in self.cfg.APPLICATION.environ:
331                 self.set(p, self.cfg.APPLICATION.environ[p])
332             self.add_line(1)
333
334         # If there is an "environ_script" section, load the scripts
335         if 'environ_script' in self.cfg.APPLICATION:
336             for pscript in self.cfg.APPLICATION.environ_script:
337                 self.add_comment("script %s" % pscript)
338                 sname = pscript.replace(" ", "_")
339                 self.run_env_script("APPLICATION_%s" % sname,
340                                 self.cfg.APPLICATION.environ_script[pscript],
341                                 logger)
342                 self.add_line(1)
343         
344         # If there is profile (SALOME), then define additional variables
345         if ('profile' in self.cfg.APPLICATION and 
346                                     "product" in self.cfg.APPLICATION.profile):
347             profile_product = self.cfg.APPLICATION.profile.product
348             product_info_profile = src.product.get_product_config(self.cfg,
349                                                             profile_product)
350             profile_share_salome = os.path.join(product_info_profile.install_dir,
351                                                 "share",
352                                                 "salome" )
353             self.set( "SUITRoot", profile_share_salome )
354             self.set( "SalomeAppConfig",
355                       os.path.join(profile_share_salome,
356                                    "resources",
357                                    profile_product.lower() ) )
358         
359         # The list of products to launch
360         lProductsName = self.get_names(self.cfg.APPLICATION.products.keys())
361         
362         self.set( "SALOME_MODULES",    ','.join(lProductsName))
363
364     def set_salome_minimal_product_env(self, product_info, logger):
365         """Sets the minimal environment for a SALOME product.
366            xxx_ROOT_DIR and xxx_SRC_DIR
367         
368         :param product_info Config: The product description
369         :param logger Logger: The logger instance to display messages        
370         """
371         # set root dir
372         root_dir = product_info.name + "_ROOT_DIR"
373         if not self.is_defined(root_dir):
374             if 'install_dir' in product_info and product_info.install_dir:
375                 self.set(root_dir, product_info.install_dir)
376             elif not self.silent:
377                 logger.write("  " + _("No install_dir for product %s\n") %
378                               product_info.name, 5)
379         
380         if not self.for_package:
381             # set source dir, unless no source dir
382             if not src.product.product_is_fixed(product_info):
383                 src_dir = product_info.name + "_SRC_DIR"
384                 if not self.is_defined(src_dir):
385                     self.set(src_dir, product_info.source_dir)
386
387     def set_salome_generic_product_env(self, product):
388         """Sets the generic environment for a SALOME product.
389         
390         :param product str: The product name    
391         """
392         # get the product descritption
393         pi = src.product.get_product_config(self.cfg, product)
394         # Construct XXX_ROOT_DIR
395         env_root_dir = self.get(pi.name + "_ROOT_DIR")
396         l_binpath_libpath = []
397
398         # create additional ROOT_DIR for CPP components
399         if 'component_name' in pi:
400             compo_name = pi.component_name
401             if compo_name + "CPP" == product:
402                 compo_root_dir = compo_name + "_ROOT_DIR"
403                 envcompo_root_dir = os.path.join(
404                             self.cfg.TOOLS.common.install_root, compo_name )
405                 self.set(compo_root_dir ,  envcompo_root_dir)
406                 bin_path = os.path.join(envcompo_root_dir, 'bin', 'salome')
407                 lib_path = os.path.join(envcompo_root_dir, 'lib', 'salome')
408                 l_binpath_libpath.append( (bin_path, lib_path) )
409
410         appliname = 'salome'
411         if (src.get_cfg_param(pi, 'product_type', 'SALOME').upper() 
412                             not in [ "SALOME", "SMESH_PLUGIN", "SAMPLE" ]):
413             appliname = ''
414
415         # Construct the paths to prepend to PATH and LD_LIBRARY_PATH and 
416         # PYTHONPATH
417         bin_path = os.path.join(env_root_dir, 'bin', appliname)
418         lib_path = os.path.join(env_root_dir, 'lib', appliname)
419         l_binpath_libpath.append( (bin_path, lib_path) )
420
421         for bin_path, lib_path in l_binpath_libpath:
422             if not self.forBuild:
423                 self.prepend('PATH', bin_path)
424                 if src.architecture.is_windows():
425                     self.prepend('PATH', lib_path)
426                 else :
427                     self.prepend('LD_LIBRARY_PATH', lib_path)
428
429             l = [ bin_path, lib_path,
430                   os.path.join(env_root_dir, self.python_lib0, appliname),
431                   os.path.join(env_root_dir, self.python_lib1, appliname)
432                 ]
433             self.prepend('PYTHONPATH', l)
434
435     def load_cfg_environment(self, cfg_env):
436         """Loads environment defined in cfg_env 
437         
438         :param cfg_env Config: A config containing an environment    
439         """
440         # Loop on cfg_env values
441         for env_def in cfg_env:
442             val = cfg_env[env_def]
443             
444             # if it is env_script, do not do anything (reserved keyword)
445             if env_def == "env_script":
446                 continue
447             
448             # if it is a dict, do not do anything
449             if isinstance(val, src.pyconf.Mapping):
450                 continue
451
452             # if it is a list, loop on its values
453             if isinstance(val, src.pyconf.Sequence):
454                 # transform into list of strings
455                 l_val = []
456                 for item in val:
457                     l_val.append(item)
458                 val = l_val
459
460             # "_" means that the value must be prepended
461             if env_def.startswith("_"):
462                 # separator exception for PV_PLUGIN_PATH
463                 if env_def[1:] == 'PV_PLUGIN_PATH':
464                     self.prepend(env_def[1:], val, ';')
465                 else:
466                     self.prepend(env_def[1:], val)
467             elif env_def.endswith("_"):
468                 # separator exception for PV_PLUGIN_PATH
469                 if env_def[:-1] == 'PV_PLUGIN_PATH':
470                     self.append(env_def[:-1], val, ';')
471                 else:
472                     self.append(env_def[:-1], val)
473             else:
474                 self.set(env_def, val)
475
476     def set_a_product(self, product, logger):
477         """Sets the environment of a product. 
478         
479         :param product str: The product name
480         :param logger Logger: The logger instance to display messages
481         """
482
483         # Get the informations corresponding to the product
484         pi = src.product.get_product_config(self.cfg, product)
485         
486         if self.for_package:
487             pi.install_dir = os.path.join("out_dir_Path",
488                                           self.for_package,
489                                           pi.name)
490                     
491         # Do not define environment if the product is native
492         if src.product.product_is_native(pi):
493             return
494         
495         if not self.silent:
496             logger.write(_("Setting environment for %s\n") % product, 4)
497
498         self.add_line(1)
499         self.add_comment('setting environ for ' + product)
500         
501         # Set an additional environment for SALOME products
502         if src.product.product_is_salome(pi):
503             # set environment using definition of the product
504             self.set_salome_minimal_product_env(pi, logger)
505             self.set_salome_generic_product_env(product)
506
507         # Put the environment define in the configuration of the product
508         if "environ" in pi:
509             self.load_cfg_environment(pi.environ)
510             if self.forBuild and "build" in pi.environ:
511                 self.load_cfg_environment(pi.environ.build)
512             if not self.forBuild and "launch" in pi.environ:
513                 self.load_cfg_environment(pi.environ.launch)
514             # if product_info defines a env_scripts, load it
515             if 'env_script' in pi.environ:
516                 self.run_env_script(pi, logger)
517
518         
519             
520
521     def run_env_script(self, product_info, logger=None):
522         """Runs an environment script. 
523         
524         :param product_info Config: The product description
525         :param logger Logger: The logger instance to display messages
526         """
527         env_script = product_info.environ.env_script
528         # Check that the script exists
529         if not os.path.exists(env_script):
530             raise src.SatException(_("Environment script not found: %s") % 
531                                    env_script)
532
533         if not self.silent and logger is not None:
534             logger.write("  ** load %s\n" % env_script, 4)
535
536         # import the script and run the set_env function
537         try:
538             import imp
539             pyproduct = imp.load_source(product_info.name + "_env_script",
540                                         env_script)
541             pyproduct.set_env(self, product_info.install_dir,
542                               product_info.version)
543         except:
544             __, exceptionValue, exceptionTraceback = sys.exc_info()
545             print(exceptionValue)
546             import traceback
547             traceback.print_tb(exceptionTraceback)
548             traceback.print_exc()
549
550     def run_simple_env_script(self, script_path, logger=None):
551         """Runs an environment script. Same as run_env_script, but with a 
552            script path as parameter.
553         
554         :param script_path str: a path to an environment script
555         :param logger Logger: The logger instance to display messages
556         """
557         # Check that the script exists
558         if not os.path.exists(script_path):
559             raise src.SatException(_("Environment script not found: %s") % 
560                                    script_path)
561
562         if not self.silent and logger is not None:
563             logger.write("  ** load %s\n" % script_path, 4)
564
565         script_basename = os.path.basename(script_path)
566         if script_basename.endswith(".py"):
567             script_basename = script_basename[:-len(".py")]
568
569         # import the script and run the set_env function
570         try:
571             import imp
572             pyproduct = imp.load_source(script_basename + "_env_script",
573                                         script_path)
574             pyproduct.load_env(self)
575         except:
576             __, exceptionValue, exceptionTraceback = sys.exc_info()
577             print(exceptionValue)
578             import traceback
579             traceback.print_tb(exceptionTraceback)
580             traceback.print_exc()
581
582     def set_products(self, logger, src_root=None):
583         """Sets the environment for all the products. 
584         
585         :param logger Logger: The logger instance to display messages
586         :param src_root src: the application working directory
587         """
588         self.add_line(1)
589         self.add_comment('setting environ for all products')
590
591         self.set_python_libdirs()
592
593         # Set the application working directory
594         if src_root is None:
595             src_root = self.cfg.APPLICATION.workdir
596         self.set('SRC_ROOT', src_root)
597
598         # SALOME variables
599         appli_name = "APPLI"
600         if "APPLI" in self.cfg and "application_name" in self.cfg.APPLI:
601             appli_name = self.cfg.APPLI.application_name
602         self.set("SALOME_APPLI_ROOT",
603                  os.path.join(self.cfg.APPLICATION.workdir, appli_name))
604
605         # The loop on the products
606         for product in self.cfg.APPLICATION.products.keys():
607             self.set_a_product(product, logger)
608             self.finish(False)
609  
610     def set_full_environ(self, logger, env_info):
611         """Sets the full environment for products 
612            specified in env_info dictionary. 
613         
614         :param logger Logger: The logger instance to display messages
615         :param env_info list: the list of products
616         """
617         # set product environ
618         self.set_application_env(logger)
619
620         self.set_python_libdirs()
621
622         # set products        
623         for product in env_info:
624             self.set_a_product(product, logger)
625
626 class FileEnvWriter:
627     """Class to dump the environment to a file.
628     """
629     def __init__(self, config, logger, out_dir, src_root, env_info=None):
630         '''Initialization.
631
632         :param cfg Config: the global config
633         :param logger Logger: The logger instance to display messages
634         :param out_dir str: The directory path where t put the output files
635         :param src_root str: The application working directory
636         :param env_info str: The list of products to add in the files.
637         '''
638         self.config = config
639         self.logger = logger
640         self.out_dir = out_dir
641         self.src_root= src_root
642         self.silent = True
643         self.env_info = env_info
644
645     def write_env_file(self, filename, forBuild, shell):
646         """Create an environment file.
647         
648         :param filename str: the file path
649         :param forBuild bool: if true, the build environment
650         :param shell str: the type of file wanted (.sh, .bat)
651         :return: The path to the generated file
652         :rtype: str
653         """
654         if not self.silent:
655             self.logger.write(_("Create environment file %s\n") % 
656                               src.printcolors.printcLabel(filename), 3)
657
658         # create then env object
659         env_file = open(os.path.join(self.out_dir, filename), "w")
660         tmp = src.fileEnviron.get_file_environ(env_file,
661                                                shell,
662                                                {})
663         env = SalomeEnviron(self.config, tmp, forBuild)
664         env.silent = self.silent
665
666         # Set the environment
667         if self.env_info is not None:
668             env.set_full_environ(self.logger, self.env_info)
669         else:
670             # set env from the APPLICATION
671             env.set_application_env(self.logger)
672             # set the products
673             env.set_products(self.logger,
674                             src_root=self.src_root)
675
676         # add cleanup and close
677         env.finish(True)
678         env_file.close()
679
680         return env_file.name
681    
682     def write_cfgForPy_file(self,
683                             filename,
684                             additional_env = {},
685                             for_package = None):
686         """Append to current opened aFile a cfgForPy 
687            environment (SALOME python launcher).
688            
689         :param filename str: the file path
690         :param additional_env dict: a dictionary of additional variables 
691                                     to add to the environment
692         :param for_package str: If not None, produce a relative environment 
693                                 designed for a package. 
694         """
695         if not self.silent:
696             self.logger.write(_("Create configuration file %s\n") % 
697                               src.printcolors.printcLabel(filename.name), 3)
698
699         # create then env object
700         tmp = src.fileEnviron.get_file_environ(filename, 
701                                                "cfgForPy", 
702                                                {})
703         # environment for launch
704         env = SalomeEnviron(self.config,
705                             tmp,
706                             forBuild=False,
707                             for_package=for_package)
708         env.silent = self.silent
709
710         if self.env_info is not None:
711             env.set_full_environ(self.logger, self.env_info)
712         else:
713             # set env from PRODUCT
714             env.set_application_env(self.logger)
715
716             # set the products
717             env.set_products(self.logger,
718                             src_root=self.src_root)
719
720         # Add the additional environment if it is not empty
721         if len(additional_env) != 0:
722             for variable in additional_env:
723                 env.set(variable, additional_env[variable])
724
725         # add cleanup and close
726         env.finish(True)
727
728 class Shell:
729     """Definition of a Shell.
730     """
731     def __init__(self, name, extension):
732         '''Initialization.
733
734         :param name str: the shell name
735         :param extension str: the shell extension
736         '''
737         self.name = name
738         self.extension = extension
739
740 def load_environment(config, build, logger):
741     """Loads the environment (used to run the tests, for example).
742     
743     :param config Config: the global config
744     :param build bool: build environement if True
745     :param logger Logger: The logger instance to display messages
746     """
747     environ = SalomeEnviron(config, Environ(os.environ), build)
748     environ.set_application_env(logger)
749     environ.set_products(logger)
750     environ.finish(True)