Salome HOME
Add Builder class
[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 # create bash product file
27 _bash_content = """PRODUCT_DIR=%s
28 if [[ "${ENV_FOR_LAUNCH}x" == "x" ]]
29 then
30     export ENV_FOR_LAUNCH=1
31 fi
32
33 if [[ "${ENV_FOR_LAUNCH}" == "1" ]]
34 then
35     source $PRODUCT_DIR/env_launch.sh
36 else
37     source $PRODUCT_DIR/env_build.sh
38 fi
39 """
40
41 # create batch product file
42 _batch_content = """set PRODUCT_DIR=%s
43 IF NOT DEFINED ENV_FOR_LAUNCH set ENV_FOR_LAUNCH=1
44
45 if "%%ENV_FOR_LAUNCH%%"=="1" (
46     %%PRODUCT_DIR%%\\env_launch.bat
47 ) else (
48     %%PRODUCT_DIR%%\\env_build.bat
49 )
50 """
51
52 class Environ:
53     '''Class to manage the environment context
54     '''
55     def __init__(self, environ=None):
56         '''Initialization. If the environ argument is passed, the environment
57            will be add to it, else it is the external environment.
58            
59         :param environ dict:  
60         '''
61         if environ is not None:
62             self.environ = environ
63         else:
64             self.environ = os.environ
65
66     def __repr__(self):
67         """easy non exhaustive quick resume for debug print
68         """
69         res={}
70         res["environ"]=self.environ
71         return self.__class__.__name__ + str(res)[0:-1] + " ...etc...}"
72
73     def _expandvars(self, value):
74         '''replace some $VARIABLE into its actual value in the environment
75         
76         :param value str: the string to be replaced
77         :return: the replaced variable
78         :rtype: str
79         '''
80         if "$" in value:
81             # The string.Template class is a string class 
82             # for supporting $-substitutions
83             zt = string.Template(value)
84             try:
85                 value = zt.substitute(self.environ)
86             except KeyError as exc:
87                 raise src.SatException(_("Missing definition "
88                                          "in environment: %s") % str(exc))
89         return value
90
91     def append_value(self, key, value, sep=os.pathsep):
92         '''append value to key using sep
93         
94         :param key str: the environment variable to append
95         :param value str: the value to append to key
96         :param sep str: the separator string
97         '''
98         # check if the key is already in the environment
99         if key in self.environ:
100             value_list = self.environ[key].split(sep)
101             # Check if the value is already in the key value or not
102             if not value in value_list:
103                 value_list.append(value)
104             else:
105                 value_list.append(value_list.pop(value_list.index(value)))
106             self.set(key, sep.join(value_list))
107         else:
108             self.set(key, value)
109
110     def append(self, key, value, sep=os.pathsep):
111         '''Same as append_value but the value argument can be a list
112         
113         :param key str: the environment variable to append
114         :param value str or list: the value(s) to append to key
115         :param sep str: the separator string
116         '''
117         if isinstance(value, list):
118             for v in value:
119                 self.append_value(key, v, sep)
120         else:
121             self.append_value(key, value, sep)
122
123     def prepend_value(self, key, value, sep=os.pathsep):
124         '''prepend value to key using sep
125         
126         :param key str: the environment variable to prepend
127         :param value str: the value to prepend to key
128         :param sep str: the separator string
129         '''
130         if key in self.environ:
131             value_list = self.environ[key].split(sep)
132             if not value in value_list:
133                 value_list.insert(0, value)
134             else:
135                 value_list.insert(0, value_list.pop(value_list.index(value)))
136             self.set(key, sep.join(value_list))
137         else:
138             self.set(key, value)
139
140     def prepend(self, key, value, sep=os.pathsep):
141         '''Same as prepend_value but the value argument can be a list
142         
143         :param key str: the environment variable to prepend
144         :param value str or list: the value(s) to prepend to key
145         :param sep str: the separator string
146         '''
147         if isinstance(value, list):
148             for v in value:
149                 self.prepend_value(key, v, sep)
150         else:
151             self.prepend_value(key, value, sep)
152
153     def is_defined(self, key):
154         '''Check if the key exists in the environment
155         
156         :param key str: the environment variable to check
157         '''
158         return self.environ.has_key(key)
159
160     def set(self, key, value):
161         '''Set the environment variable "key" to value "value"
162         
163         :param key str: the environment variable to set
164         :param value str: the value
165         '''
166         self.environ[key] = self._expandvars(value)
167
168     def get(self, key):
169         '''Get the value of the environment variable "key"
170         
171         :param key str: the environment variable
172         '''
173         if key in self.environ:
174             return self.environ[key]
175         else:
176             return ""
177
178     def command_value(self, key, command):
179         '''Get the value given by the system command "command" 
180            and put it in the environment variable key
181         
182         :param key str: the environment variable
183         :param command str: the command to execute
184         '''
185         value = subprocess.Popen(command,
186                                  shell=True,
187                                  stdout=subprocess.PIPE,
188                                  env=self.environ).communicate()[0]
189         self.environ[key] = value
190
191
192 class SalomeEnviron:
193     """Class to manage the environment of SALOME.
194     """
195
196     def __init__(self, cfg, environ, forBuild=False):
197         self.environ = environ
198         self.cfg = cfg
199         self.forBuild = forBuild
200         self.silent = False
201
202     def __repr__(self):
203         """easy non exhaustive quick resume for debug print"""
204         res={}
205         res["environ"]=str(self.environ)
206         res["forBuild"]=self.forBuild
207         return self.__class__.__name__ + str(res)[0:-1] + " ...etc...}"
208
209     def append(self, key, value, sep=os.pathsep):
210         return self.environ.append(key, value, sep)
211
212     def prepend(self, key, value, sep=os.pathsep):
213         return self.environ.prepend(key, value, sep)
214
215     def is_defined(self, key):
216         return self.environ.is_defined(key)
217
218     def get(self, key):
219         return self.environ.get(key)
220
221     def set(self, key, value):
222         # check if value needs to be evaluated
223         if value is not None and value.startswith("`") and value.endswith("`"):
224             res = subprocess.Popen("echo %s" % value, shell=True, stdout=subprocess.PIPE).communicate()
225             value = res[0].strip()
226
227         return self.environ.set(key, value)
228
229     def dump(self, out):
230         """Write the environment to out"""
231         for k in self.environ.environ.keys():
232             try:
233                 value = self.get(k)
234             except:
235                 value = "?"
236             out.write("%s=%s\n" % (k, value))
237
238     def add_line(self, nb_line):
239         if 'add_line' in dir(self.environ):
240             self.environ.add_line(nb_line)
241
242     def add_comment(self, comment):
243         if 'add_comment' in dir(self.environ):
244             self.environ.add_comment(comment)
245
246     def add_warning(self, warning):
247         if 'add_warning' in dir(self.environ):
248             self.environ.add_warning(warning)
249
250     def finish(self, required):
251         if 'finish' in dir(self.environ):
252             self.environ.add_line(1)
253             self.environ.add_comment("clean all the path")
254             self.environ.finish(required)
255
256     def list_version_4_prereq(self, prerequisite, logger):
257         alist = []
258         for path in self.cfg.TOOLS.environ.prereq_install_dir:
259             if not os.path.exists(path):
260                 continue
261             prereqlist = os.listdir(path)
262             for prereq in prereqlist:
263                 if prereq.split("-")[0] == prerequisite:
264                     #logger.error(str(prereq) + "\n")
265                     alist.append(str(prereq))
266
267         if len(alist) > 0:
268             logger.write(_("Available prerequisites are:") + "\n\t%s\n" % '\n\t'.join(alist), 2)
269
270     def set_python_libdirs(self):
271         if src.architecture.is_windows():
272             # sysconfig.get_python_lib() does not return appropriate path on Windows
273             # clearly decide here once for windows
274             ver = self.get('PYTHON_VERSION')
275             self.set('PYTHON_LIBDIR0', os.path.join('lib', 'python' + ver, 'site-packages'))
276             self.set('PYTHON_LIBDIR1', os.path.join('lib64', 'python' + ver, 'site-packages'))
277
278         else:
279             ver = self.get('PYTHON_VERSION')
280             self.set('PYTHON_LIBDIR0', os.path.join('lib', 'python' + ver, 'site-packages'))
281             self.set('PYTHON_LIBDIR1', os.path.join('lib64', 'python' + ver, 'site-packages'))
282           
283         self.python_lib0 = self.get('PYTHON_LIBDIR0')
284         self.python_lib1 = self.get('PYTHON_LIBDIR1')
285
286     ##
287     # Get the products name to add in SALOME_MODULES environment variable
288     # It is the name of the product, except in the case where the is a component name.
289     # And it has to be in SALOME_MODULES variable only if has_gui = "yes"
290     def getNames(self, lProducts):
291         lProdHasGui = [p for p in lProducts if 'has_gui' in src.product.get_product_config(self.cfg, p) and src.product.get_product_config(self.cfg, p).has_gui=='yes']
292         lProdName = []
293         for ProdName in lProdHasGui:
294             pi = src.product.get_product_config(self.cfg, ProdName)
295             if 'component_name' in pi:
296                 lProdName.append(pi.component_name)
297             else:
298                 lProdName.append(ProdName)
299         return lProdName
300
301     ##
302     # Sets the environment defined in the PRODUCT file.
303     def set_application_env(self, logger):
304         if 'environ' in self.cfg.APPLICATION:
305             self.add_comment("APPLICATION environment")
306             for p in self.cfg.APPLICATION.environ:
307                 self.set(p, self.cfg.APPLICATION.environ[p])
308             self.add_line(1)
309
310         if 'environ_script' in self.cfg.APPLICATION:
311             for pscript in self.cfg.APPLICATION.environ_script:
312                 self.add_comment("script %s" % pscript)
313                 sname = pscript.replace(" ", "_")
314                 self.run_env_script("APPLICATION_%s" % sname, self.cfg.APPLICATION.environ_script[pscript], logger)
315                 self.add_line(1)
316         
317         if 'profile' in self.cfg.APPLICATION:
318             profile_product = self.cfg.APPLICATION.profile.product
319             product_info_profile = src.product.get_product_config(self.cfg, profile_product)
320             profile_share_salome = os.path.join( product_info_profile.install_dir, "share", "salome" )
321             self.set( "SUITRoot", profile_share_salome )
322             self.set( "SalomeAppConfig", os.path.join( profile_share_salome, "resources", profile_product.lower() ) )
323         
324         # The list of products to launch
325         lProductsName = self.getNames(self.cfg.APPLICATION.products.keys())
326         
327         self.set( "SALOME_MODULES",    ','.join(lProductsName))
328
329     ##
330     # Set xxx_ROOT_DIR and xxx_SRC_DIR.
331     def set_salome_minimal_product_env(self, product_info, logger, single_dir, cfgdic=None):
332         # set root dir
333         root_dir = product_info.name + "_ROOT_DIR"
334         indic = cfgdic is not None and root_dir in cfgdic
335         if not self.is_defined(root_dir) and not indic:
336             if single_dir:
337                 self.set(root_dir, os.path.join(self.get('INSTALL_ROOT'), 'SALOME'))
338             elif 'install_dir' in product_info and product_info.install_dir:
339                 self.set(root_dir, product_info.install_dir)
340             elif not self.silent:
341                 logger.write("  " + _("No install_dir for product %s\n") % product_info.name, 5)
342
343         # set source dir, unless the product is fixed (no source dir)
344         if not src.product.product_is_fixed(product_info):
345             src_dir = product_info.name + "_SRC_DIR"
346             indic = cfgdic is not None and src_dir in cfgdic
347             if not self.is_defined(src_dir) and not indic:
348                 self.set(src_dir, product_info.source_dir)
349
350     def set_salome_generic_product_env(self, product):
351         pi = src.product.get_product_config(self.cfg, product)
352         env_root_dir = self.get(pi.name + "_ROOT_DIR")
353         l_binpath_libpath = []
354
355         # create additional ROOT_DIR for CPP components
356         if 'component_name' in pi:
357             compo_name = pi.component_name
358             if compo_name + "CPP" == product:
359                 compo_root_dir = compo_name + "_ROOT_DIR"
360                 envcompo_root_dir = os.path.join( self.cfg.TOOLS.common.install_root, compo_name )
361                 self.set(compo_root_dir ,  envcompo_root_dir)
362                 bin_path = os.path.join(envcompo_root_dir, 'bin', 'salome')
363                 lib_path = os.path.join(envcompo_root_dir, 'lib', 'salome')
364                 l_binpath_libpath.append( (bin_path, lib_path) )
365
366         appliname = 'salome'
367         if src.get_cfg_param(pi, 'product_type', 'SALOME').upper() not in [ "SALOME", "SMESH_PLUGIN", "SAMPLE" ]:
368             appliname = ''
369
370         bin_path = os.path.join(env_root_dir, 'bin', appliname)
371         lib_path = os.path.join(env_root_dir, 'lib', appliname)
372         l_binpath_libpath.append( (bin_path, lib_path) )
373
374         for bin_path, lib_path in l_binpath_libpath:
375             if not self.forBuild:
376                 self.prepend('PATH', bin_path)
377                 if src.architecture.is_windows():
378                     self.prepend('PATH', lib_path)
379                 else :
380                     self.prepend('LD_LIBRARY_PATH', lib_path)
381
382             l = [ bin_path, lib_path,
383                   os.path.join(env_root_dir, self.python_lib0, appliname),
384                   os.path.join(env_root_dir, self.python_lib1, appliname)
385                 ]
386             self.prepend('PYTHONPATH', l)
387
388     ##
389     # Loads environment define in the configuration.
390     def load_cfg_environment(self, cfg_env):
391         for env_def in cfg_env:
392             val = cfg_env[env_def]
393             if isinstance(val, src.pyconf.Mapping):
394                 continue
395
396             if isinstance(val, src.pyconf.Sequence):
397                 # transform into list of strings
398                 l_val = []
399                 for item in val:
400                     l_val.append(item)
401                 val = l_val
402
403             if env_def.startswith("_"):
404                 # separator exception for PV_PLUGIN_PATH
405                 if env_def[1:] == 'PV_PLUGIN_PATH':
406                     self.prepend(env_def[1:], val, ';')
407                 else:
408                     self.prepend(env_def[1:], val)
409             elif env_def.endswith("_"):
410                 # separator exception for PV_PLUGIN_PATH
411                 if env_def[:-1] == 'PV_PLUGIN_PATH':
412                     self.prepend(env_def[:-1], val, ';')
413                 else:
414                     self.prepend(env_def[:-1], val)
415             else:
416                 self.set(env_def, val)
417
418     ##
419     # Sets the environment of a product.
420     def set_a_product(self, product, logger, single_dir):
421                
422         if not self.silent:
423             logger.write(_("Setting environment for %s\n") % product, 4)
424
425         self.add_line(1)
426         self.add_comment('setting environ for ' + product)
427         
428         pi = src.product.get_product_config(self.cfg, product)
429
430         # Do not define environment if the product is native or fixed
431         if src.product.product_is_native(pi):
432             return
433
434         if "environ" in pi:
435             # set environment using definition of the product
436             self.set_salome_minimal_product_env(pi, logger, single_dir, pi.environ)
437             self.set_salome_generic_product_env(product)
438             self.load_cfg_environment(pi.environ)
439             if self.forBuild and "build" in pi.environ:
440                 self.load_cfg_environment(pi.environ.build)
441             if not self.forBuild and "launch" in pi.environ:
442                 self.load_cfg_environment(pi.environ.launch)
443         else:
444             # no environment defined in config
445             self.set_salome_minimal_product_env(pi, logger, single_dir)
446             if 'install_dir' in pi :
447                 self.set_salome_generic_product_env(product)
448
449         # if product_info defines a env_scripts load it
450         if 'env_script' in pi:
451             self.run_env_script(pi, logger)
452             
453
454     ##
455     # Runs an environment script.
456     def run_env_script(self, product_info, logger=None):
457         env_script = product_info.env_script
458         if not os.path.exists(product_info.env_script):
459             raise src.SatException(_("Environment script not found: %s") % env_script)
460
461         if not self.silent and logger is not None:
462             logger.write("  ** load %s\n" % product_info.env_script, 4)
463
464         try:
465             import imp
466             pyproduct = imp.load_source(product_info.name + "_env_script", env_script)
467             pyproduct.set_env(self, product_info.install_dir, product_info.version)
468         except:
469             __, exceptionValue, exceptionTraceback = sys.exc_info()
470             print(exceptionValue)
471             import traceback
472             traceback.print_tb(exceptionTraceback)
473             traceback.print_exc()
474
475     ##
476     # Sets the environment for all the products.
477     def set_products(self, logger, src_root=None, single_dir=False):
478         self.add_line(1)
479         self.add_comment('setting environ for all products')
480
481         self.set_python_libdirs()
482
483         if src_root is None:
484             src_root = self.cfg.APPLICATION.workdir
485         self.set('SRC_ROOT', src_root)
486
487         appli_name = "APPLI"
488         if "APPLI" in self.cfg and "application_name" in self.cfg.APPLI:
489             appli_name = self.cfg.APPLI.application_name
490         self.set("SALOME_APPLI_ROOT", os.path.join(self.cfg.APPLICATION.workdir, appli_name))
491
492         if not single_dir:
493             single_dir = src.get_cfg_param(self.cfg.APPLICATION, "compil_in_single_dir", "no") == 'yes'
494
495         for product in src.get_cfg_param(self.cfg.APPLICATION, "imported_products", []):
496             self.set_a_product(product, logger, single_dir=single_dir)
497             self.finish(False)
498
499         for product in self.cfg.APPLICATION.products.keys():
500             self.set_a_product(product, logger, single_dir=single_dir)
501             self.finish(False)
502
503    
504     ##
505     # Sets the full environment for prerequisites and products specified in env_info dictionary.
506     def set_full_environ(self, logger, env_info):
507         # set product environ
508         self.set_application_env(logger)
509
510         # set products
511         install_root = os.path.join(self.cfg.APPLICATION.workdir, "INSTALL")
512         source_root = os.path.join(self.cfg.APPLICATION.workdir, "SOURCES")
513         self.set('INSTALL_ROOT', install_root)
514         self.set('SRC_ROOT', source_root)
515         self.set_python_libdirs()
516
517         single_dir = src.get_cfg_param(self.cfg.APPLICATION, "compil_in_single_dir", "no") == 'yes'
518         for product in env_info['products']:
519             self.set_a_product(product, logger, single_dir=single_dir)
520
521 ##
522 # Class to dump the environment to a file.
523 class FileEnvWriter:
524     def __init__(self, config, logger, out_dir, src_root, single_dir, env_info=None):
525         self.config = config
526         self.logger = logger
527         self.out_dir = out_dir
528         self.src_root= src_root
529         self.single_dir = single_dir
530         self.silent = True
531         self.env_info = env_info
532
533     def write_env_file(self, filename, forBuild, shell):
534         """Create an environment file."""
535         if not self.silent:
536             self.logger.write(_("Create environment file %s\n") % src.printcolors.printcLabel(filename), 3)
537
538         # create then env object
539         env_file = open(os.path.join(self.out_dir, filename), "w")
540         tmp = src.fileEnviron.get_file_environ(env_file, shell, {}, self.config )
541         env = SalomeEnviron(self.config, tmp, forBuild)
542         env.silent = self.silent
543
544         if self.env_info is not None:
545             env.set_full_environ(self.logger, self.env_info)
546         else:
547             # set env from PRODUCT
548             env.set_application_env(self.logger)
549             # set the products
550             env.set_products(self.logger,
551                             src_root=self.src_root, single_dir=self.single_dir)
552
553         # add cleanup and close
554         env.finish(True)
555         env_file.close()
556
557         return env_file.name
558
559     def write_product_file(self, filename, shell):
560         """Create a product file."""
561         if not self.silent:
562             self.logger.write(_("Create product file %s\n") % src.printcolors.printcLabel(filename), 3)
563
564         prod_file = open(os.path.join(self.out_dir, filename), "w")
565         if shell == "bash":
566             content = _bash_content % self.out_dir
567         elif shell == "batch":
568             content = _batch_content % self.out_dir
569         else:
570             raise src.SatException(_("Unknown shell: %s") % shell)
571
572         prod_file.write(content)
573         prod_file.close()
574        
575         return prod_file.name
576    
577     def write_cfgForPy_file(self, aFile, additional_env = {}):
578         """append to current opened aFile a cfgForPy environment (python syntax)."""
579         if not self.silent:
580             self.logger.write(_("Create configuration file %s\n") % src.printcolors.printcLabel(aFile.name), 3)
581
582         # create then env object
583         tmp = src.fileEnviron.get_file_environ(aFile, "cfgForPy", {}, self.config)
584         forBuild = True
585         forLaunch = False
586         env = SalomeEnviron(self.config, tmp, forLaunch)
587         env.silent = self.silent
588
589         if self.env_info is not None:
590             env.set_full_environ(self.logger, self.env_info)
591         else:
592             # set env from PRODUCT
593             env.set_application_env(self.logger)
594             # set the prerequisites
595             env.set_prerequisites(self.logger)
596             # set the products
597             env.set_products(self.logger,
598                             src_root=self.src_root, single_dir=self.single_dir)
599
600         if len(additional_env) != 0:
601             for variable in additional_env:
602                 env.set(variable, additional_env[variable])
603
604         # add cleanup and close
605         env.finish(True)
606
607 ##
608 # Definition of a Shell.
609 class Shell:
610     def __init__(self, name, extension):
611         self.name = name
612         self.extension = extension
613
614 ##
615 # Loads the environment (used to run the tests).
616 def load_environment(config, build, logger):
617     environ = SalomeEnviron(config, Environ(os.environ), build)
618     environ.set_application_env(logger)
619     environ.set_products(logger)
620     environ.finish(True)