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
21 import src.debug as DBG
22 import src.architecture
23 import src.environment
25 def get_file_environ(output, shell, environ=None):
26 """Instantiate correct FileEnvironment sub-class.
28 :param output file: the output file stream.
29 :param shell str: the type of shell syntax to use.
30 :param environ dict: a potential additional environment.
33 environ=src.environment.Environ({})
35 return BashFileEnviron(output, environ)
37 return TclFileEnviron(output, environ)
39 return BatFileEnviron(output, environ)
40 if shell == "cfgForPy":
41 return LauncherFileEnviron(output, environ)
43 return ContextFileEnviron(output, environ)
44 raise Exception("FileEnviron: Unknown shell = %s" % shell)
46 class FileEnviron(object):
48 Base class for shell environment
50 def __init__(self, output, environ=None):
54 :param output file: the output file stream.
55 :param environ dict: SalomeEnviron.
57 self._do_init(output, environ)
61 easy non exhaustive quick resume for debug print"""
63 "output" : self.output,
64 "environ" : self.environ,
66 return "%s(\n%s\n)" % (self.__class__.__name__, PP.pformat(res))
69 def _do_init(self, output, environ=None):
73 :param output file: the output file stream.
74 :param environ dict: a potential additional environment.
77 self.init_path=True # by default we initialise all paths, except PATH
78 if environ is not None:
79 self.environ = environ
81 self.environ = src.environment.Environ({})
83 def add_line(self, number):
85 Add some empty lines in the shell file
87 :param number int: the number of lines to add
89 self.output.write("\n" * number)
91 def add_comment(self, comment):
93 Add a comment in the shell file
95 :param comment str: the comment to add
97 self.output.write("# %s\n" % comment)
99 def add_echo(self, text):
101 Add a "echo" in the shell file
103 :param text str: the text to echo
105 self.output.write('echo %s"\n' % text)
107 def add_warning(self, warning):
109 Add a warning "echo" in the shell file
111 :param warning str: the text to echo
113 self.output.write('echo "WARNING %s"\n' % warning)
115 def append_value(self, key, value, sep=os.pathsep):
117 append value to key using sep,
118 if value contains ":" or ";" then raise error
120 :param key str: the environment variable to append
121 :param value str: the value to append to key
122 :param sep str: the separator string
124 # check that value so no contain the system separator
126 if separator in value:
127 raise Exception("FileEnviron append key '%s' value '%s' contains forbidden character '%s'" % (key, value, separator))
129 if self.environ.is_defined(key):
130 value_list = self.environ.get(key).split(sep)
131 if self.environ._expandvars(value) in value_list:
132 do_append=False # value is already in key path : we don't append it again
135 self.environ.append_value(key, value,sep)
136 self.set(key, self.get(key) + sep + value)
138 def append(self, key, value, sep=os.pathsep):
140 Same as append_value but the value argument can be a list
142 :param key str: the environment variable to append
143 :param value str or list: the value(s) to append to key
144 :param sep str: the separator string
146 if isinstance(value, list):
148 self.append_value(key, v, sep)
150 self.append_value(key, value, sep)
152 def prepend_value(self, key, value, sep=os.pathsep):
154 prepend value to key using sep,
155 if value contains ":" or ";" then raise error
157 :param key str: the environment variable to prepend
158 :param value str: the value to prepend to key
159 :param sep str: the separator string
161 # check that value so no contain the system separator
163 if separator in value:
164 raise Exception("FileEnviron append key '%s' value '%s' contains forbidden character '%s'" % (key, value, separator))
167 if self.environ.is_defined(key):
168 value_list = self.environ.get(key).split(sep)
169 exp_val=self.environ._expandvars(value)
170 if exp_val in value_list:
172 if not do_not_prepend:
173 self.environ.prepend_value(key, value,sep)
174 self.set(key, value + sep + self.get(key))
176 def prepend(self, key, value, sep=os.pathsep):
178 Same as prepend_value but the value argument can be a list
180 :param key str: the environment variable to prepend
181 :param value str or list: the value(s) to prepend to key
182 :param sep str: the separator string
184 if isinstance(value, list):
185 for v in reversed(value): # prepend list, first item at last to stay first
186 self.prepend_value(key, v, sep)
188 self.prepend_value(key, value, sep)
190 def is_defined(self, key):
192 Check if the key exists in the environment
194 :param key str: the environment variable to check
196 return self.environ.is_defined(key)
198 def set(self, key, value):
200 Set the environment variable 'key' to value 'value'
202 :param key str: the environment variable to set
203 :param value str: the value
205 raise NotImplementedError("set is not implement for this shell!")
209 Get the value of the environment variable "key"
211 :param key str: the environment variable
215 def get_value(self, key):
216 """Get the real value of the environment variable "key"
217 It can help env scripts
218 :param key str: the environment variable
220 return self.environ.get_value(key)
223 """Add a final instruction in the out file (in case of file generation)
225 :param required bool: Do nothing if required is False
229 def set_no_init_path(self):
230 """Set the no initialisation mode for all paths.
231 By default only PATH is not reinitialised. All others paths are
232 (LD_LIBRARY_PATH, PYTHONPATH, ...)
233 After the call to these function ALL PATHS ARE NOT REINITIALISED.
234 There initial value is inherited from the environment
238 def value_filter(self, value):
240 # on windows platform, replace / by \
241 if src.architecture.is_windows():
242 res = value.replace("/","\\")
246 class TclFileEnviron(FileEnviron):
250 def __init__(self, output, environ=None):
253 :param output file: the output file stream.
254 :param environ dict: a potential additional environment.
256 self._do_init(output, environ)
257 self.output.write(tcl_header.replace("<module_name>",
258 self.environ.get("sat_product_name")))
259 self.output.write("\nset software %s\n" % self.environ.get("sat_product_name") )
260 self.output.write("set version %s\n" % self.environ.get("sat_product_version") )
261 root=os.path.join(self.environ.get("sat_product_base_path"),
263 self.environ.get("sat_product_base_name"),
266 self.output.write("set root %s\n" % root)
267 modules_to_load=self.environ.get("sat_product_load_depend")
268 if len(modules_to_load)>0:
269 # write module load commands for product dependencies
270 self.output.write("\n")
271 for module_to_load in modules_to_load.split(";"):
272 self.output.write(module_to_load+"\n")
274 def set(self, key, value):
275 """Set the environment variable "key" to value "value"
277 :param key str: the environment variable to set
278 :param value str: the value
280 #print "CNC TclFileEnviron set ", key, " to ", value
281 self.output.write('setenv %s "%s"\n' % (key, value))
282 self.environ.set(key, value)
286 Get the value of the environment variable "key"
288 :param key str: the environment variable
290 return self.environ.get(key)
292 def append_value(self, key, value, sep=os.pathsep):
293 """append value to key using sep
295 :param key str: the environment variable to append
296 :param value str: the value to append to key
297 :param sep str: the separator string
300 self.output.write('append-path %s %s\n' % (key, value))
302 self.output.write('append-path --delim=\%c %s %s\n' % (sep, key, value))
304 def prepend_value(self, key, value, sep=os.pathsep):
305 """prepend value to key using sep
307 :param key str: the environment variable to prepend
308 :param value str: the value to prepend to key
309 :param sep str: the separator string
312 self.output.write('prepend-path %s %s\n' % (key, value))
314 self.output.write('prepend-path --delim=\%c %s %s\n' % (sep, key, value))
317 class BashFileEnviron(FileEnviron):
319 Class for bash shell.
321 def __init__(self, output, environ=None):
324 :param output file: the output file stream.
325 :param environ dict: a potential additional environment.
327 self._do_init(output, environ)
328 self.output.write(bash_header)
330 def set(self, key, value):
331 """Set the environment variable "key" to value "value"
333 :param key str: the environment variable to set
334 :param value str: the value
336 self.output.write('export %s="%s"\n' % (key, value))
337 self.environ.set(key, value)
341 class BatFileEnviron(FileEnviron):
343 for Windows batch shell.
345 def __init__(self, output, environ=None):
348 :param output file: the output file stream.
349 :param environ dict: a potential additional environment.
351 self._do_init(output, environ)
352 self.output.write(bat_header)
354 def add_comment(self, comment):
355 """Add a comment in the shell file
357 :param comment str: the comment to add
359 self.output.write("rem %s\n" % comment)
362 """Get the value of the environment variable "key"
364 :param key str: the environment variable
366 return '%%%s%%' % key
368 def set(self, key, value):
369 """Set the environment variable "key" to value "value"
371 :param key str: the environment variable to set
372 :param value str: the value
374 self.output.write('set %s=%s\n' % (key, self.value_filter(value)))
375 self.environ.set(key, value)
378 class ContextFileEnviron(FileEnviron):
379 """Class for a salome context configuration file.
381 def __init__(self, output, environ=None):
384 :param output file: the output file stream.
385 :param environ dict: a potential additional environment.
387 self._do_init(output, environ)
388 self.output.write(cfg_header)
390 def set(self, key, value):
391 """Set the environment variable "key" to value "value"
393 :param key str: the environment variable to set
394 :param value str: the value
396 self.output.write('%s="%s"\n' % (key, value))
397 self.environ.set(key, value)
400 """Get the value of the environment variable "key"
402 :param key str: the environment variable
404 return '%({0})s'.format(key)
406 def add_echo(self, text):
409 :param text str: the comment to add
411 self.add_comment(text)
413 def add_warning(self, warning):
416 :param text str: the warning to add
418 self.add_comment("WARNING %s" % warning)
420 def prepend_value(self, key, value, sep=os.pathsep):
421 """prepend value to key using sep
423 :param key str: the environment variable to prepend
424 :param value str: the value to prepend to key
425 :param sep str: the separator string
428 if self.environ.is_defined(key):
429 value_list = self.environ.get(key).split(sep)
430 #value cannot be expanded (unlike bash/bat case) - but it doesn't matter.
431 if value in value_list:
432 do_append=False # value is already in key path : we don't append it again
435 self.environ.append_value(key, value,sep)
436 self.output.write('ADD_TO_%s: %s\n' % (key, value))
438 def append_value(self, key, value, sep=os.pathsep):
439 """append value to key using sep
441 :param key str: the environment variable to append
442 :param value str: the value to append to key
443 :param sep str: the separator string
445 self.prepend_value(key, value)
448 class LauncherFileEnviron(FileEnviron):
450 Class to generate a launcher file script
451 (in python syntax) SalomeContext API
453 def __init__(self, output, environ=None):
456 :param output file: the output file stream.
457 :param environ dict: a potential additional environment.
459 self._do_init(output, environ)
460 self.python_version=self.environ.get("sat_python_version")
461 self.bin_kernel_root_dir=self.environ.get("sat_bin_kernel_install_dir")
462 self.app_root_dir=self.environ.get("sat_app_root_dir")
464 # four whitespaces for first indentation in a python script
466 self.prefix="context."
467 self.setVarEnv="setVariable"
468 self.begin=self.indent+self.prefix
470 # write the begining of launcher file.
471 # choose the template version corresponding to python version
472 # and substitute BIN_KERNEL_INSTALL_DIR (the path to salomeContext.py)
473 if self.python_version == 2:
474 launcher_header=launcher_header2
476 launcher_header=launcher_header3
477 self.output.write(launcher_header\
478 .replace("BIN_KERNEL_INSTALL_DIR", self.bin_kernel_root_dir))
480 # for these path, we use specialired functions in salomeContext api
481 self.specialKeys={"PATH": "Path",
482 "LD_LIBRARY_PATH": "LdLibraryPath",
483 "PYTHONPATH": "PythonPath"}
485 # we do not want to reinitialise PATH.
486 # for that we make sure PATH is in self.environ
487 # and therefore we will not use setVariable for PATH
488 if not self.environ.is_defined("PATH"):
489 self.environ.set("PATH","")
492 def add_echo(self, text):
495 :param text str: the comment to add
497 self.output.write('# %s"\n' % text)
499 def add_warning(self, warning):
502 :param text str: the warning to add
504 self.output.write('# "WARNING %s"\n' % warning)
506 def append_value(self, key, value, sep=":"):
507 """append value to key using sep,
508 if value contains ":" or ";" then raise error
510 :param key str: the environment variable to append
511 :param value str: the value to append to key
512 :param sep str: the separator string
514 # append is not defined in context api
515 self.prepend_value(key, value)
517 def append(self, key, value, sep=":"):
518 """Same as append_value but the value argument can be a list
520 :param key str: the environment variable to append
521 :param value str or list: the value(s) to append to key
522 :param sep str: the separator string
524 if isinstance(value, list):
526 self.append_value(key, v, sep)
528 self.append_value(key, value, sep)
530 def prepend_value(self, key, value, sep=os.pathsep):
531 """prepend value to key using sep,
532 if value contains ":" or ";" then raise error
534 :param key str: the environment variable to prepend
535 :param value str: the value to prepend to key
536 :param sep str: the separator string
538 # check that value so no contain the system separator
540 msg="LauncherFileEnviron append key '%s' value '%s' contains forbidden character '%s'"
541 if separator in value:
542 raise Exception(msg % (key, value, separator))
544 if (self.init_path and (not self.environ.is_defined(key))):
545 # reinitialisation mode set to true (the default)
546 # for the first occurrence of key, we set it.
547 # therefore key will not be inherited from environment
550 # in all other cases we use append (except if value is already the key
552 if self.environ.is_defined(key):
553 value_list = self.environ.get(key).split(sep)
554 # rem : value cannot be expanded (unlike bash/bat case) - but it doesn't matter.
555 if value in value_list:
556 do_append=False # value is already in key path : we don't append it again
559 self.environ.append_value(key, value,sep) # register value in self.environ
560 if key in self.specialKeys.keys():
561 #for these special keys we use the specific salomeContext function
562 self.output.write(self.begin+'addTo%s(r"%s")\n' %
563 (self.specialKeys[key], self.value_filter(value)))
565 # else we use the general salomeContext addToVariable function
566 self.output.write(self.begin+'addToVariable(r"%s", r"%s",separator="%s")\n'
567 % (key, self.value_filter(value), sep))
570 def prepend(self, key, value, sep=":"):
571 """Same as prepend_value but the value argument can be a list
573 :param key str: the environment variable to prepend
574 :param value str or list: the value(s) to prepend to key
575 :param sep str: the separator string
577 if isinstance(value, list):
579 self.prepend_value(key, v, sep)
581 self.prepend_value(key, value, sep)
584 def set(self, key, value):
585 """Set the environment variable "key" to value "value"
587 :param key str: the environment variable to set
588 :param value str: the value
590 self.output.write(self.begin+self.setVarEnv+
591 '(r"%s", r"%s", overwrite=True)\n' %
592 (key, self.value_filter(value)))
593 self.environ.set(key,value)
596 def add_comment(self, comment):
597 # Special comment in case of the distène licence
598 if comment=="DISTENE license":
599 self.output.write(self.indent+
603 '(r"%s", r"%s", overwrite=True)\n' %
604 ('DISTENE_LICENSE_FILE', 'Use global envvar: DLIM8VAR'))
605 self.output.write(self.indent+
609 '(r"%s", r"%s", overwrite=True)\n' %
610 ('DLIM8VAR', '<your licence>'))
612 if "setting environ for" in comment:
613 self.output.write(self.indent+"#[%s]\n" %
614 comment.split("setting environ for ")[1])
617 self.output.write(self.indent+"# %s\n" % comment)
621 Add a final instruction in the out file (in case of file generation)
622 In the particular launcher case, do nothing
624 :param required bool: Do nothing if required is False
626 if self.python_version == 2:
627 launcher_tail=launcher_tail_py2
629 launcher_tail=launcher_tail_py3
630 self.output.write(launcher_tail)
633 class ScreenEnviron(FileEnviron):
634 def __init__(self, output, environ=None):
635 self._do_init(output, environ)
638 def add_line(self, number):
641 def add_comment(self, comment):
644 def add_echo(self, text):
647 def add_warning(self, warning):
650 def write(self, command, name, value, sign="="):
652 self.output.write(" %s%s %s %s %s\n" % \
653 (src.printcolors.printcLabel(command),
654 " " * (12 - len(command)),
655 src.printcolors.printcInfo(name), sign, value))
657 def is_defined(self, name):
658 return name in self.defined
661 return "${%s}" % name
663 def set(self, name, value):
664 self.write("set", name, value)
665 self.defined[name] = value
667 def prepend(self, name, value, sep=":"):
668 if isinstance(value, list):
669 value = sep.join(value)
670 value = value + sep + self.get(name)
671 self.write("prepend", name, value)
673 def append(self, name, value, sep=":"):
674 if isinstance(value, list):
675 value = sep.join(value)
676 value = self.get(name) + sep + value
677 self.write("append", name, value)
679 def run_env_script(self, module, script):
680 self.write("load", script, "", sign="")
689 rem The following variables are used only in case of a sat package
690 set out_dir_Path=%~dp0
696 # <module_name> module for use with 'environment-modules' package
702 ##########################################################################
704 # This line is used only in case of a sat package
705 export out_dir_Path=$(cd $(dirname ${BASH_SOURCE[0]});pwd)
707 ###########################################################################
711 [SALOME Configuration]
714 launcher_header2="""\
715 #! /usr/bin/env python
717 ################################################################
718 # WARNING: this file is automatically generated by SalomeTools #
719 # WARNING: and so could be overwritten at any time. #
720 ################################################################
727 # Add the pwdPath to able to run the launcher after unpacking a package
728 # Used only in case of a salomeTools package
729 out_dir_Path=os.path.dirname(os.path.realpath(__file__))
731 # Preliminary work to initialize path to SALOME Python modules
734 sys.path[:0] = [ 'BIN_KERNEL_INSTALL_DIR' ] # to get salomeContext
736 # define folder to store omniorb config (initially in virtual application folder)
738 from salomeContextUtils import setOmniOrbUserPath
740 except Exception as e:
743 # End of preliminary work
745 # salome doc only works for virtual applications. Therefore we overwrite it with this function
746 def _showDoc(modules):
747 for module in modules:
748 modulePath = os.getenv(module+"_ROOT_DIR")
749 if modulePath != None:
750 baseDir = os.path.join(modulePath, "share", "doc", "salome")
751 docfile = os.path.join(baseDir, "gui", module.upper(), "index.html")
752 if not os.path.isfile(docfile):
753 docfile = os.path.join(baseDir, "tui", module.upper(), "index.html")
754 if not os.path.isfile(docfile):
755 docfile = os.path.join(baseDir, "dev", module.upper(), "index.html")
756 if os.path.isfile(docfile):
757 out, err = subprocess.Popen(["xdg-open", docfile]).communicate()
759 print ("Online documentation is not accessible for module:", module)
761 print (module+"_ROOT_DIR not found!")
764 # Identify application path then locate configuration files
767 if args == ['--help']:
768 from salomeContext import usage
773 # Create a SalomeContext which parses configFileNames to initialize environment
775 from salomeContext import SalomeContext, SalomeContextException
776 context = SalomeContext(None)
778 # Here set specific variables, if needed
779 # context.addToPath('mypath')
780 # context.addToLdLibraryPath('myldlibrarypath')
781 # context.addToPythonPath('mypythonpath')
782 # context.setVariable('myvarname', 'value')
785 context.getLogger().setLevel(40)
788 launcher_header3="""\
789 #! /usr/bin/env python3
791 ################################################################
792 # WARNING: this file is automatically generated by SalomeTools #
793 # WARNING: and so could be overwritten at any time. #
794 ################################################################
801 # Add the pwdPath to able to run the launcher after unpacking a package
802 # Used only in case of a salomeTools package
803 out_dir_Path=os.path.dirname(os.path.realpath(__file__))
805 # Preliminary work to initialize path to SALOME Python modules
808 sys.path[:0] = [ 'BIN_KERNEL_INSTALL_DIR' ]
810 # define folder to store omniorb config (initially in virtual application folder)
812 from salomeContextUtils import setOmniOrbUserPath
814 except Exception as e:
817 # End of preliminary work
819 # salome doc only works for virtual applications. Therefore we overwrite it with this function
820 def _showDoc(modules):
821 for module in modules:
822 modulePath = os.getenv(module+"_ROOT_DIR")
823 if modulePath != None:
824 baseDir = os.path.join(modulePath, "share", "doc", "salome")
825 docfile = os.path.join(baseDir, "gui", module.upper(), "index.html")
826 if not os.path.isfile(docfile):
827 docfile = os.path.join(baseDir, "tui", module.upper(), "index.html")
828 if not os.path.isfile(docfile):
829 docfile = os.path.join(baseDir, "dev", module.upper(), "index.html")
830 if os.path.isfile(docfile):
831 out, err = subprocess.Popen(["xdg-open", docfile]).communicate()
833 print("Online documentation is not accessible for module:", module)
835 print(module+"_ROOT_DIR not found!")
838 # Identify application path then locate configuration files
841 if args == ['--help']:
842 from salomeContext import usage
846 #from salomeContextUtils import getConfigFileNames
847 #configFileNames, args, unexisting = getConfigFileNames( args, checkExistence=True )
848 #if len(unexisting) > 0:
849 # print("ERROR: unexisting configuration file(s): " + ', '.join(unexisting))
852 # Create a SalomeContext which parses configFileNames to initialize environment
854 from salomeContext import SalomeContext, SalomeContextException
855 context = SalomeContext(None)
857 # Here set specific variables, if needed
858 # context.addToPath('mypath')
859 # context.addToLdLibraryPath('myldlibrarypath')
860 # context.addToPythonPath('mypythonpath')
861 # context.setVariable('myvarname', 'value')
864 context.getLogger().setLevel(40)
867 launcher_tail_py2="""\
868 if len(args) >1 and args[0]=='doc':
872 # Start SALOME, parsing command line arguments
873 out, err, status = context.runSalome(args)
876 except SalomeContextException, e:
878 logging.getLogger("salome").error(e)
882 if __name__ == "__main__":
888 launcher_tail_py3="""\
889 if len(args) >1 and args[0]=='doc':
893 # Start SALOME, parsing command line arguments
894 out, err, status = context.runSalome(args)
897 except SalomeContextException as e:
899 logging.getLogger("salome").error(e)
903 if __name__ == "__main__":