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 BatFileEnviron(output, environ)
38 if shell == "cfgForPy":
39 return LauncherFileEnviron(output, environ)
41 return ContextFileEnviron(output, environ)
42 raise Exception("FileEnviron: Unknown shell = %s" % shell)
44 class FileEnviron(object):
46 Base class for shell environment
48 def __init__(self, output, environ=None):
52 :param output file: the output file stream.
53 :param environ dict: SalomeEnviron.
55 self._do_init(output, environ)
59 easy non exhaustive quick resume for debug print"""
61 "output" : self.output,
62 "environ" : self.environ,
64 return "%s(\n%s\n)" % (self.__class__.__name__, PP.pformat(res))
67 def _do_init(self, output, environ=None):
71 :param output file: the output file stream.
72 :param environ dict: a potential additional environment.
75 self.init_path=True # by default we initialise all paths, except PATH
76 if environ is not None:
77 self.environ = environ
79 self.environ = src.environment.Environ({})
81 def add_line(self, number):
83 Add some empty lines in the shell file
85 :param number int: the number of lines to add
87 self.output.write("\n" * number)
89 def add_comment(self, comment):
91 Add a comment in the shell file
93 :param comment str: the comment to add
95 self.output.write("# %s\n" % comment)
97 def add_echo(self, text):
99 Add a "echo" in the shell file
101 :param text str: the text to echo
103 self.output.write('echo %s"\n' % text)
105 def add_warning(self, warning):
107 Add a warning "echo" in the shell file
109 :param warning str: the text to echo
111 self.output.write('echo "WARNING %s"\n' % warning)
113 def append_value(self, key, value, sep=os.pathsep):
115 append value to key using sep,
116 if value contains ":" or ";" then raise error
118 :param key str: the environment variable to append
119 :param value str: the value to append to key
120 :param sep str: the separator string
122 # check that value so no contain the system separator
124 if separator in value:
125 raise Exception("FileEnviron append key '%s' value '%s' contains forbidden character '%s'" % (key, value, separator))
127 if self.environ.is_defined(key):
128 value_list = self.environ.get(key).split(sep)
129 if self.environ._expandvars(value) in value_list:
130 do_append=False # value is already in key path : we don't append it again
133 self.environ.append_value(key, value,sep)
134 self.set(key, self.get(key) + sep + value)
136 def append(self, key, value, sep=os.pathsep):
138 Same as append_value but the value argument can be a list
140 :param key str: the environment variable to append
141 :param value str or list: the value(s) to append to key
142 :param sep str: the separator string
144 if isinstance(value, list):
146 self.append_value(key, v, sep)
148 self.append_value(key, value, sep)
150 def prepend_value(self, key, value, sep=os.pathsep):
152 prepend value to key using sep,
153 if value contains ":" or ";" then raise error
155 :param key str: the environment variable to prepend
156 :param value str: the value to prepend to key
157 :param sep str: the separator string
159 # check that value so no contain the system separator
161 if separator in value:
162 raise Exception("FileEnviron append key '%s' value '%s' contains forbidden character '%s'" % (key, value, separator))
165 if self.environ.is_defined(key):
166 value_list = self.environ.get(key).split(sep)
167 exp_val=self.environ._expandvars(value)
168 if exp_val in value_list:
170 if not do_not_prepend:
171 self.environ.prepend_value(key, value,sep)
172 self.set(key, value + sep + self.get(key))
174 def prepend(self, key, value, sep=os.pathsep):
176 Same as prepend_value but the value argument can be a list
178 :param key str: the environment variable to prepend
179 :param value str or list: the value(s) to prepend to key
180 :param sep str: the separator string
182 if isinstance(value, list):
183 for v in reversed(value): # prepend list, first item at last to stay first
184 self.prepend_value(key, v, sep)
186 self.prepend_value(key, value, sep)
188 def is_defined(self, key):
190 Check if the key exists in the environment
192 :param key str: the environment variable to check
194 return self.environ.is_defined(key)
196 def set(self, key, value):
198 Set the environment variable 'key' to value 'value'
200 :param key str: the environment variable to set
201 :param value str: the value
203 raise NotImplementedError("set is not implement for this shell!")
207 Get the value of the environment variable "key"
209 :param key str: the environment variable
213 def get_value(self, key):
214 """Get the real value of the environment variable "key"
215 It can help env scripts
216 :param key str: the environment variable
218 return self.environ.get_value(key)
221 """Add a final instruction in the out file (in case of file generation)
223 :param required bool: Do nothing if required is False
227 def set_no_init_path(self):
228 """Set the no initialisation mode for all paths.
229 By default only PATH is not reinitialised. All others paths are
230 (LD_LIBRARY_PATH, PYTHONPATH, ...)
231 After the call to these function ALL PATHS ARE NOT REINITIALISED.
232 There initial value is inherited from the environment
236 def value_filter(self, value):
238 # on windows platform, replace / by \
239 if src.architecture.is_windows():
240 res = value.replace("/","\\")
244 class BashFileEnviron(FileEnviron):
246 Class for bash shell.
248 def __init__(self, output, environ=None):
251 :param output file: the output file stream.
252 :param environ dict: a potential additional environment.
254 self._do_init(output, environ)
255 self.output.write(bash_header)
257 def set(self, key, value):
258 """Set the environment variable "key" to value "value"
260 :param key str: the environment variable to set
261 :param value str: the value
263 self.output.write('export %s="%s"\n' % (key, value))
264 self.environ.set(key, value)
268 class BatFileEnviron(FileEnviron):
270 for Windows batch shell.
272 def __init__(self, output, environ=None):
275 :param output file: the output file stream.
276 :param environ dict: a potential additional environment.
278 self._do_init(output, environ)
279 self.output.write(bat_header)
281 def add_comment(self, comment):
282 """Add a comment in the shell file
284 :param comment str: the comment to add
286 self.output.write("rem %s\n" % comment)
289 """Get the value of the environment variable "key"
291 :param key str: the environment variable
293 return '%%%s%%' % key
295 def set(self, key, value):
296 """Set the environment variable "key" to value "value"
298 :param key str: the environment variable to set
299 :param value str: the value
301 self.output.write('set %s=%s\n' % (key, self.value_filter(value)))
302 self.environ.set(key, value)
305 class ContextFileEnviron(FileEnviron):
306 """Class for a salome context configuration file.
308 def __init__(self, output, environ=None):
311 :param output file: the output file stream.
312 :param environ dict: a potential additional environment.
314 self._do_init(output, environ)
315 self.output.write(cfg_header)
317 def set(self, key, value):
318 """Set the environment variable "key" to value "value"
320 :param key str: the environment variable to set
321 :param value str: the value
323 self.output.write('%s="%s"\n' % (key, value))
324 self.environ.set(key, value)
327 """Get the value of the environment variable "key"
329 :param key str: the environment variable
331 return '%({0})s'.format(key)
333 def add_echo(self, text):
336 :param text str: the comment to add
338 self.add_comment(text)
340 def add_warning(self, warning):
343 :param text str: the warning to add
345 self.add_comment("WARNING %s" % warning)
347 def prepend_value(self, key, value, sep=os.pathsep):
348 """prepend value to key using sep
350 :param key str: the environment variable to prepend
351 :param value str: the value to prepend to key
352 :param sep str: the separator string
355 if self.environ.is_defined(key):
356 value_list = self.environ.get(key).split(sep)
357 #value cannot be expanded (unlike bash/bat case) - but it doesn't matter.
358 if value in value_list:
359 do_append=False # value is already in key path : we don't append it again
362 self.environ.append_value(key, value,sep)
363 self.output.write('ADD_TO_%s: %s\n' % (key, value))
365 def append_value(self, key, value, sep=os.pathsep):
366 """append value to key using sep
368 :param key str: the environment variable to append
369 :param value str: the value to append to key
370 :param sep str: the separator string
372 self.prepend_value(key, value)
375 class LauncherFileEnviron(FileEnviron):
377 Class to generate a launcher file script
378 (in python syntax) SalomeContext API
380 def __init__(self, output, environ=None):
383 :param output file: the output file stream.
384 :param environ dict: a potential additional environment.
386 self._do_init(output, environ)
387 self.python_version=self.environ.get("sat_python_version")
388 self.bin_kernel_root_dir=self.environ.get("sat_bin_kernel_install_dir")
389 self.app_root_dir=self.environ.get("sat_app_root_dir")
391 # four whitespaces for first indentation in a python script
393 self.prefix="context."
394 self.setVarEnv="setVariable"
395 self.begin=self.indent+self.prefix
397 # write the begining of launcher file.
398 # choose the template version corresponding to python version
399 # and substitute BIN_KERNEL_INSTALL_DIR (the path to salomeContext.py)
400 if self.python_version == 2:
401 launcher_header=launcher_header2
403 launcher_header=launcher_header3
404 self.output.write(launcher_header\
405 .replace("BIN_KERNEL_INSTALL_DIR", self.bin_kernel_root_dir))
407 # for these path, we use specialired functions in salomeContext api
408 self.specialKeys={"PATH": "Path",
409 "LD_LIBRARY_PATH": "LdLibraryPath",
410 "PYTHONPATH": "PythonPath"}
412 # we do not want to reinitialise PATH.
413 # for that we make sure PATH is in self.environ
414 # and therefore we will not use setVariable for PATH
415 if not self.environ.is_defined("PATH"):
416 self.environ.set("PATH","")
419 def add_echo(self, text):
422 :param text str: the comment to add
424 self.output.write('# %s"\n' % text)
426 def add_warning(self, warning):
429 :param text str: the warning to add
431 self.output.write('# "WARNING %s"\n' % warning)
433 def append_value(self, key, value, sep=":"):
434 """append value to key using sep,
435 if value contains ":" or ";" then raise error
437 :param key str: the environment variable to append
438 :param value str: the value to append to key
439 :param sep str: the separator string
441 # append is not defined in context api
442 self.prepend_value(key, value)
444 def append(self, key, value, sep=":"):
445 """Same as append_value but the value argument can be a list
447 :param key str: the environment variable to append
448 :param value str or list: the value(s) to append to key
449 :param sep str: the separator string
451 if isinstance(value, list):
453 self.append_value(key, v, sep)
455 self.append_value(key, value, sep)
457 def prepend_value(self, key, value, sep=os.pathsep):
458 """prepend value to key using sep,
459 if value contains ":" or ";" then raise error
461 :param key str: the environment variable to prepend
462 :param value str: the value to prepend to key
463 :param sep str: the separator string
465 # check that value so no contain the system separator
467 msg="LauncherFileEnviron append key '%s' value '%s' contains forbidden character '%s'"
468 if separator in value:
469 raise Exception(msg % (key, value, separator))
471 if (self.init_path and (not self.environ.is_defined(key))):
472 # reinitialisation mode set to true (the default)
473 # for the first occurrence of key, we set it.
474 # therefore key will not be inherited from environment
477 # in all other cases we use append (except if value is already the key
479 if self.environ.is_defined(key):
480 value_list = self.environ.get(key).split(sep)
481 # rem : value cannot be expanded (unlike bash/bat case) - but it doesn't matter.
482 if value in value_list:
483 do_append=False # value is already in key path : we don't append it again
486 self.environ.append_value(key, value,sep) # register value in self.environ
487 if key in self.specialKeys.keys():
488 #for these special keys we use the specific salomeContext function
489 self.output.write(self.begin+'addTo%s(r"%s")\n' %
490 (self.specialKeys[key], self.value_filter(value)))
492 # else we use the general salomeContext addToVariable function
493 self.output.write(self.begin+'addToVariable(r"%s", r"%s",separator="%s")\n'
494 % (key, self.value_filter(value), sep))
497 def prepend(self, key, value, sep=":"):
498 """Same as prepend_value but the value argument can be a list
500 :param key str: the environment variable to prepend
501 :param value str or list: the value(s) to prepend to key
502 :param sep str: the separator string
504 if isinstance(value, list):
506 self.prepend_value(key, v, sep)
508 self.prepend_value(key, value, sep)
511 def set(self, key, value):
512 """Set the environment variable "key" to value "value"
514 :param key str: the environment variable to set
515 :param value str: the value
517 self.output.write(self.begin+self.setVarEnv+
518 '(r"%s", r"%s", overwrite=True)\n' %
519 (key, self.value_filter(value)))
520 self.environ.set(key,value)
523 def add_comment(self, comment):
524 # Special comment in case of the distène licence
525 if comment=="DISTENE license":
526 self.output.write(self.indent+
530 '(r"%s", r"%s", overwrite=True)\n' %
531 ('DISTENE_LICENSE_FILE', 'Use global envvar: DLIM8VAR'))
532 self.output.write(self.indent+
536 '(r"%s", r"%s", overwrite=True)\n' %
537 ('DLIM8VAR', '<your licence>'))
539 if "setting environ for" in comment:
540 self.output.write(self.indent+"#[%s]\n" %
541 comment.split("setting environ for ")[1])
544 self.output.write(self.indent+"# %s\n" % comment)
548 Add a final instruction in the out file (in case of file generation)
549 In the particular launcher case, do nothing
551 :param required bool: Do nothing if required is False
553 if self.python_version == 2:
554 launcher_tail=launcher_tail_py2
556 launcher_tail=launcher_tail_py3
557 self.output.write(launcher_tail)
560 class ScreenEnviron(FileEnviron):
561 def __init__(self, output, environ=None):
562 self._do_init(output, environ)
565 def add_line(self, number):
568 def add_comment(self, comment):
571 def add_echo(self, text):
574 def add_warning(self, warning):
577 def write(self, command, name, value, sign="="):
579 self.output.write(" %s%s %s %s %s\n" % \
580 (src.printcolors.printcLabel(command),
581 " " * (12 - len(command)),
582 src.printcolors.printcInfo(name), sign, value))
584 def is_defined(self, name):
585 return name in self.defined
588 return "${%s}" % name
590 def set(self, name, value):
591 self.write("set", name, value)
592 self.defined[name] = value
594 def prepend(self, name, value, sep=":"):
595 if isinstance(value, list):
596 value = sep.join(value)
597 value = value + sep + self.get(name)
598 self.write("prepend", name, value)
600 def append(self, name, value, sep=":"):
601 if isinstance(value, list):
602 value = sep.join(value)
603 value = self.get(name) + sep + value
604 self.write("append", name, value)
606 def run_env_script(self, module, script):
607 self.write("load", script, "", sign="")
616 rem The following variables are used only in case of a sat package
617 set out_dir_Path=%~dp0
623 ##########################################################################
625 # This line is used only in case of a sat package
626 export out_dir_Path=$(cd $(dirname ${BASH_SOURCE[0]});pwd)
628 ###########################################################################
632 [SALOME Configuration]
635 launcher_header2="""\
636 #! /usr/bin/env python
638 ################################################################
639 # WARNING: this file is automatically generated by SalomeTools #
640 # WARNING: and so could be overwritten at any time. #
641 ################################################################
648 # Add the pwdPath to able to run the launcher after unpacking a package
649 # Used only in case of a salomeTools package
650 out_dir_Path=os.path.dirname(os.path.realpath(__file__))
652 # Preliminary work to initialize path to SALOME Python modules
655 sys.path[:0] = [ 'BIN_KERNEL_INSTALL_DIR' ] # to get salomeContext
657 # define folder to store omniorb config (initially in virtual application folder)
659 from salomeContextUtils import setOmniOrbUserPath
661 except Exception as e:
664 # End of preliminary work
666 # salome doc only works for virtual applications. Therefore we overwrite it with this function
667 def _showDoc(modules):
668 for module in modules:
669 modulePath = os.getenv(module+"_ROOT_DIR")
670 if modulePath != None:
671 baseDir = os.path.join(modulePath, "share", "doc", "salome")
672 docfile = os.path.join(baseDir, "gui", module.upper(), "index.html")
673 if not os.path.isfile(docfile):
674 docfile = os.path.join(baseDir, "tui", module.upper(), "index.html")
675 if not os.path.isfile(docfile):
676 docfile = os.path.join(baseDir, "dev", module.upper(), "index.html")
677 if os.path.isfile(docfile):
678 out, err = subprocess.Popen(["xdg-open", docfile]).communicate()
680 print ("Online documentation is not accessible for module:", module)
682 print (module+"_ROOT_DIR not found!")
685 # Identify application path then locate configuration files
688 if args == ['--help']:
689 from salomeContext import usage
694 # Create a SalomeContext which parses configFileNames to initialize environment
696 from salomeContext import SalomeContext, SalomeContextException
697 context = SalomeContext(None)
699 # Here set specific variables, if needed
700 # context.addToPath('mypath')
701 # context.addToLdLibraryPath('myldlibrarypath')
702 # context.addToPythonPath('mypythonpath')
703 # context.setVariable('myvarname', 'value')
706 context.getLogger().setLevel(40)
709 launcher_header3="""\
710 #! /usr/bin/env python3
712 ################################################################
713 # WARNING: this file is automatically generated by SalomeTools #
714 # WARNING: and so could be overwritten at any time. #
715 ################################################################
722 # Add the pwdPath to able to run the launcher after unpacking a package
723 # Used only in case of a salomeTools package
724 out_dir_Path=os.path.dirname(os.path.realpath(__file__))
726 # Preliminary work to initialize path to SALOME Python modules
729 sys.path[:0] = [ 'BIN_KERNEL_INSTALL_DIR' ]
731 # define folder to store omniorb config (initially in virtual application folder)
733 from salomeContextUtils import setOmniOrbUserPath
735 except Exception as e:
738 # End of preliminary work
740 # salome doc only works for virtual applications. Therefore we overwrite it with this function
741 def _showDoc(modules):
742 for module in modules:
743 modulePath = os.getenv(module+"_ROOT_DIR")
744 if modulePath != None:
745 baseDir = os.path.join(modulePath, "share", "doc", "salome")
746 docfile = os.path.join(baseDir, "gui", module.upper(), "index.html")
747 if not os.path.isfile(docfile):
748 docfile = os.path.join(baseDir, "tui", module.upper(), "index.html")
749 if not os.path.isfile(docfile):
750 docfile = os.path.join(baseDir, "dev", module.upper(), "index.html")
751 if os.path.isfile(docfile):
752 out, err = subprocess.Popen(["xdg-open", docfile]).communicate()
754 print("Online documentation is not accessible for module:", module)
756 print(module+"_ROOT_DIR not found!")
759 # Identify application path then locate configuration files
762 if args == ['--help']:
763 from salomeContext import usage
767 #from salomeContextUtils import getConfigFileNames
768 #configFileNames, args, unexisting = getConfigFileNames( args, checkExistence=True )
769 #if len(unexisting) > 0:
770 # print("ERROR: unexisting configuration file(s): " + ', '.join(unexisting))
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_tail_py2="""\
789 if len(args) >1 and args[0]=='doc':
793 # Start SALOME, parsing command line arguments
794 out, err, status = context.runSalome(args)
797 except SalomeContextException, e:
799 logging.getLogger("salome").error(e)
803 if __name__ == "__main__":
809 launcher_tail_py3="""\
810 if len(args) >1 and args[0]=='doc':
814 # Start SALOME, parsing command line arguments
815 out, err, status = context.runSalome(args)
818 except SalomeContextException as e:
820 logging.getLogger("salome").error(e)
824 if __name__ == "__main__":