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
23 bat_header="""@echo off
25 rem The following variables are used only in case of a sat package
26 set out_dir_Path=%~dp0
27 set PRODUCT_OUT_DIR=%out_dir_Path%
28 set prereq_install_Path=%out_dir_Path%\PREREQUISITES\INSTALL
29 set prereq_build_Path=%out_dir_Path%\PREREQUISITES\BUILD
33 bash_header="""#!/bin/bash
34 ##########################################################################
37 # cleanup a path (first parameter) from duplicated entries;
38 # second parameter is the separator
40 out_var=`echo $1 | awk -v sep=$2 '{ \\
41 na = split($1,a,sep); \\
43 for(i=0;i<=na;i++) { \\
60 }' | sed -e 's|\\(.*\\)$1|\\1|g' -e 's|^[:;]||' -e 's|[:;]$||'`
67 out_var=`cleandup $xenv $2`
71 # The 3 following variables are used only in case of a sat package
72 export out_dir_Path=$(cd $(dirname ${BASH_SOURCE[0]});pwd)
73 export PRODUCT_OUT_DIR=${out_dir_Path}
74 export PRODUCT_ROOT_DIR=${PRODUCT_OUT_DIR}
76 ###########################################################################
79 cfg_header='''[SALOME Configuration]
82 Launcher_header='''# a generated SALOME Configuration file using python syntax
85 def get_file_environ(output, shell, environ=None):
86 """Instantiate correct FileEnvironment sub-class.
88 :param output file: the output file stream.
89 :param shell str: the type of shell syntax to use.
90 :param environ dict: a potential additional environment.
93 return BashFileEnviron(output, environ)
95 return BatFileEnviron(output, environ)
96 if shell == "cfgForPy":
97 return LauncherFileEnviron(output, environ)
99 return ContextFileEnviron(output, environ)
100 raise Exception("FileEnviron: Unknown shell = %s" % shell)
102 class FileEnviron(object):
103 """Base class for shell environment
105 def __init__(self, output, environ=None):
108 :param output file: the output file stream.
109 :param environ dict: a potential additional environment.
111 self._do_init(output, environ)
114 """easy non exhaustive quick resume for debug print"""
116 "output" : self.output,
117 "environ" : self.environ,
119 return "%s(\n%s\n)" % (self.__class__.__name__, PP.pformat(res))
122 def _do_init(self, output, environ=None):
125 :param output file: the output file stream.
126 :param environ dict: a potential additional environment.
130 if environ is not None:
131 #if str(type(environ)) == "<type 'instance'>":
132 if id(environ) == id(os.environ):
133 DBG.tofix("set %s environ as python os.environ, are you sure it is safe ?" % self.__class__.__name__, True)
134 self.environ = environ
136 DBG.tofix("set %s environ as COPY of python os.environ, are you sure it is safe ?" % self.__class__.__name__, True)
137 self.environ = dict(os.environ) #make a copy cvw 180320
139 def add_line(self, number):
140 """Add some empty lines in the shell file
142 :param number int: the number of lines to add
144 self.output.write("\n" * number)
146 def add_comment(self, comment):
147 """Add a comment in the shell file
149 :param comment str: the comment to add
151 self.output.write("# %s\n" % comment)
153 def add_echo(self, text):
154 """Add a "echo" in the shell file
156 :param text str: the text to echo
158 self.output.write('echo %s"\n' % text)
160 def add_warning(self, warning):
161 """Add a warning "echo" in the shell file
163 :param warning str: the text to echo
165 self.output.write('echo "WARNING %s"\n' % warning)
167 def append_value(self, key, value, sep=os.pathsep):
168 '''append value to key using sep
170 :param key str: the environment variable to append
171 :param value str: the value to append to key
172 :param sep str: the separator string
174 self.set(key, self.get(key) + sep + value)
175 if (key, sep) not in self.toclean:
176 self.toclean.append((key, sep))
178 def append(self, key, value, sep=os.pathsep):
179 '''Same as append_value but the value argument can be a list
181 :param key str: the environment variable to append
182 :param value str or list: the value(s) to append to key
183 :param sep str: the separator string
185 if isinstance(value, list):
186 self.append_value(key, sep.join(value), sep)
188 self.append_value(key, value, sep)
190 def prepend_value(self, key, value, sep=os.pathsep):
191 '''prepend value to key using sep
193 :param key str: the environment variable to prepend
194 :param value str: the value to prepend to key
195 :param sep str: the separator string
197 self.set(key, value + sep + self.get(key))
198 if (key, sep) not in self.toclean:
199 self.toclean.append((key, sep))
201 def prepend(self, key, value, sep=os.pathsep):
202 '''Same as prepend_value but the value argument can be a list
204 :param key str: the environment variable to prepend
205 :param value str or list: the value(s) to prepend to key
206 :param sep str: the separator string
208 if isinstance(value, list):
209 self.prepend_value(key, sep.join(value), sep)
211 self.prepend_value(key, value, sep)
213 def is_defined(self, key):
214 '''Check if the key exists in the environment
216 :param key str: the environment variable to check
218 return (key in self.environ)
220 def set(self, key, value):
221 '''Set the environment variable "key" to value "value"
223 :param key str: the environment variable to set
224 :param value str: the value
226 raise NotImplementedError("set is not implement for this shell!")
229 '''Get the value of the environment variable "key"
231 :param key str: the environment variable
235 def command_value(self, key, command):
236 '''Get the value given by the system command "command"
237 and put it in the environment variable key.
238 Has to be overwritten in the derived classes
239 This can be seen as a virtual method
241 :param key str: the environment variable
242 :param command str: the command to execute
244 raise NotImplementedError("command_value is not implement "
247 def finish(self, required=True):
248 """Add a final instruction in the out file (in case of file generation)
250 :param required bool: Do nothing if required is False
252 for (key, sep) in self.toclean:
254 self.output.write('clean %s "%s"\n' % (key, sep))
256 class BashFileEnviron(FileEnviron):
257 """Class for bash shell.
259 def __init__(self, output, environ=None):
262 :param output file: the output file stream.
263 :param environ dict: a potential additional environment.
265 self._do_init(output, environ)
266 self.output.write(bash_header)
268 def set(self, key, value):
269 '''Set the environment variable "key" to value "value"
271 :param key str: the environment variable to set
272 :param value str: the value
274 self.output.write('export %s="%s"\n' % (key, value))
275 self.environ[key] = value
277 def command_value(self, key, command):
278 '''Get the value given by the system command "command"
279 and put it in the environment variable key.
280 Has to be overwritten in the derived classes
281 This can be seen as a virtual method
283 :param key str: the environment variable
284 :param command str: the command to execute
286 self.output.write('export %s=$(%s)\n' % (key, command))
288 def finish(self, required=True):
289 """Add a final instruction in the out file (in case of file generation)
291 :param required bool: Do nothing if required is False
295 FileEnviron.finish(self, required)
297 class BatFileEnviron(FileEnviron):
298 """for Windows batch shell.
300 def __init__(self, output, environ=None):
303 :param output file: the output file stream.
304 :param environ dict: a potential additional environment.
306 self._do_init(output, environ)
307 self.output.write(bat_header)
309 def add_comment(self, comment):
310 """Add a comment in the shell file
312 :param comment str: the comment to add
314 self.output.write("rem %s\n" % comment)
317 '''Get the value of the environment variable "key"
319 :param key str: the environment variable
321 return '%%%s%%' % key
323 def set(self, key, value):
324 '''Set the environment variable "key" to value "value"
326 :param key str: the environment variable to set
327 :param value str: the value
329 self.output.write('set %s=%s\n' % (key, value))
330 self.environ[key] = value
332 def command_value(self, key, command):
333 '''Get the value given by the system command "command"
334 and put it in the environment variable key.
335 Has to be overwritten in the derived classes
336 This can be seen as a virtual method
338 :param key str: the environment variable
339 :param command str: the command to execute
341 self.output.write('%s > tmp.txt\n' % (command))
342 self.output.write('set /p %s =< tmp.txt\n' % (key))
344 def finish(self, required=True):
345 """Add a final instruction in the out file (in case of file generation)
346 In the particular windows case, do nothing
348 :param required bool: Do nothing if required is False
352 class ContextFileEnviron(FileEnviron):
353 """Class for a salome context configuration file.
355 def __init__(self, output, environ=None):
358 :param output file: the output file stream.
359 :param environ dict: a potential additional environment.
361 self._do_init(output, environ)
362 self.output.write(cfg_header)
364 def set(self, key, value):
365 '''Set the environment variable "key" to value "value"
367 :param key str: the environment variable to set
368 :param value str: the value
370 self.output.write('%s="%s"\n' % (key, value))
371 self.environ[key] = value
374 '''Get the value of the environment variable "key"
376 :param key str: the environment variable
378 return '%({0})s'.format(key)
380 def command_value(self, key, command):
381 '''Get the value given by the system command "command"
382 and put it in the environment variable key.
383 Has to be overwritten in the derived classes
384 This can be seen as a virtual method
386 :param key str: the environment variable
387 :param command str: the command to execute
389 raise NotImplementedError("command_value is not implement "
390 "for salome context files!")
392 def add_echo(self, text):
395 :param text str: the comment to add
397 self.add_comment(text)
399 def add_warning(self, warning):
402 :param text str: the warning to add
404 self.add_comment("WARNING %s" % warning)
406 def prepend_value(self, key, value, sep=os.pathsep):
407 '''prepend value to key using sep
409 :param key str: the environment variable to prepend
410 :param value str: the value to prepend to key
411 :param sep str: the separator string
413 self.output.write('ADD_TO_%s: %s\n' % (key, value))
415 def append_value(self, key, value, sep=os.pathsep):
416 '''append value to key using sep
418 :param key str: the environment variable to append
419 :param value str: the value to append to key
420 :param sep str: the separator string
422 self.prepend_value(key, value)
424 def finish(self, required=True):
425 """Add a final instruction in the out file (in case of file generation)
427 :param required bool: Do nothing if required is False
431 def special_path_separator(name):
432 """TCLLIBPATH, TKLIBPATH, PV_PLUGIN_PATH environments variables need
433 some exotic path separator.
434 This function gives the separator regarding the name of the variable
435 to append or prepend.
437 :param name str: The name of the variable to find the separator
439 special_blanks_keys=["TCLLIBPATH", "TKLIBPATH"]
440 special_semicolon_keys=["PV_PLUGIN_PATH"]
442 if name in special_blanks_keys: res=" "
443 if name in special_semicolon_keys: res=";"
446 class LauncherFileEnviron:
447 """Class to generate a launcher file script
448 (in python syntax) SalomeContext API
450 def __init__(self, output, environ=None):
453 :param output file: the output file stream.
454 :param environ dict: a potential additional environment.
458 if environ is not None:
459 self.environ = environ
461 self.environ = os.environ
462 # Initialize some variables
463 if not "PATH" in self.environ.keys():
464 self.environ["PATH"]=""
465 if not "LD_LIBRARY_PATH" in self.environ.keys():
466 self.environ["LD_LIBRARY_PATH"]=""
467 if not "PYTHONPATH" in self.environ.keys():
468 self.environ["PYTHONPATH"]=""
469 if not "TCLLIBPATH" in self.environ.keys():
470 self.environ["TCLLIBPATH"]=""
471 if not "TKLIBPATH" in self.environ.keys():
472 self.environ["TKLIBPATH"]=""
474 # four whitespaces for first indentation in a python script
476 self.prefix="context."
477 self.setVarEnv="setVariable"
479 self.begin=self.indent+self.prefix
480 self.output.write(Launcher_header)
481 self.specialKeys={"PATH": "Path",
482 "LD_LIBRARY_PATH": "LdLibraryPath",
483 "PYTHONPATH": "PythonPath"}
485 def change_to_launcher(self, value):
491 def add_line(self, number):
492 """Add some empty lines in the launcher file
494 :param number int: the number of lines to add
496 self.output.write("\n" * number)
498 def add_echo(self, text):
501 :param text str: the comment to add
503 self.output.write('# %s"\n' % text)
505 def add_warning(self, warning):
508 :param text str: the warning to add
510 self.output.write('# "WARNING %s"\n' % warning)
512 def append_value(self, key, value, sep=":"):
513 '''append value to key using sep
515 :param key str: the environment variable to append
516 :param value str: the value to append to key
517 :param sep str: the separator string
519 if self.is_defined(key) :
524 def append(self, key, value, sep=":"):
525 '''Same as append_value but the value argument can be a list
527 :param key str: the environment variable to append
528 :param value str or list: the value(s) to append to key
529 :param sep str: the separator string
531 if isinstance(value, list):
532 self.append_value(key, sep.join(value), sep)
534 self.append_value(key, value, sep)
536 def prepend_value(self, key, value, sep=":"):
537 '''prepend value to key using sep
539 :param key str: the environment variable to prepend
540 :param value str: the value to prepend to key
541 :param sep str: the separator string
543 if self.is_defined(key) :
548 def prepend(self, key, value, sep=":"):
549 '''Same as prepend_value but the value argument can be a list
551 :param key str: the environment variable to prepend
552 :param value str or list: the value(s) to prepend to key
553 :param sep str: the separator string
555 if isinstance(value, list):
556 self.prepend_value(key, sep.join(value), sep)
558 self.prepend_value(key, value, sep)
560 def is_defined(self, key):
561 '''Check if the key exists in the environment
563 :param key str: the environment variable to check
565 return key in self.environ.keys()
568 '''Get the value of the environment variable "key"
570 :param key str: the environment variable
574 def set(self, key, value):
575 '''Set the environment variable "key" to value "value"
577 :param key str: the environment variable to set
578 :param value str: the value
580 self.output.write(self.begin+self.setVarEnv+
581 '(r"%s", r"%s", overwrite=True)\n' %
582 (key, self.change_to_launcher(value)))
583 self.environ[key] = value
585 def add(self, key, value):
586 '''prepend value to key using sep
588 :param key str: the environment variable to prepend
589 :param value str: the value to prepend to key
591 if key in self.specialKeys.keys():
592 self.output.write(self.begin+'addTo%s(r"%s")\n' %
593 (self.specialKeys[key],
594 self.change_to_launcher(value)))
595 self.environ[key]+=":"+value
597 sep=special_path_separator(key)
598 self.output.write(self.indent+
599 '#temporary solution!!! have to be defined in API a '
600 '?dangerous? addToSpecial(r"%s", r"%s")\n' %
602 #pathsep not precised because do not know future os launch?
603 self.output.write(self.begin+'addToSpecial(r"%s", r"%s")\n'
604 % (key, self.change_to_launcher(value)))
605 self.environ[key]+=sep+value #here yes we know os for current execution
607 def command_value(self, key, command):
608 '''Get the value given by the system command "command"
609 and put it in the environment variable key.
611 :param key str: the environment variable
612 :param command str: the command to execute
614 self.output.write(self.indent+'#`%s`\n' % command)
616 import shlex, subprocess
617 args = shlex.split(command)
618 res=subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
619 out, __ = res.communicate()
620 self.output.write(self.begin+
622 '(r"%s", r"%s", overwrite=True)\n' % (key, out))
624 def add_comment(self, comment):
625 # Special comment in case of the distène licence
626 if comment=="DISTENE license":
627 self.output.write(self.indent+
631 '(r"%s", r"%s", overwrite=True)\n' %
632 ('DISTENE_LICENSE_FILE',
633 self.change_to_launcher(
634 'Use global envvar: DLIM8VAR')))
635 self.output.write(self.indent+
639 '(r"%s", r"%s", overwrite=True)\n' %
641 self.change_to_launcher(
644 if "setting environ for" in comment:
645 self.output.write(self.indent+"#[%s]\n" %
646 comment.split("setting environ for ")[1])
649 self.output.write(self.indent+"# %s\n" % comment)
651 def finish(self, required=True):
652 """Add a final instruction in the out file (in case of file generation)
653 In the particular launcher case, do nothing
655 :param required bool: Do nothing if required is False
659 class ScreenEnviron(FileEnviron):
660 def __init__(self, output, environ=None):
661 self._do_init(output, environ)
664 def add_line(self, number):
667 def add_comment(self, comment):
670 def add_echo(self, text):
673 def add_warning(self, warning):
676 def write(self, command, name, value, sign="="):
678 self.output.write(" %s%s %s %s %s\n" % \
679 (src.printcolors.printcLabel(command),
680 " " * (12 - len(command)),
681 src.printcolors.printcInfo(name), sign, value))
683 def is_defined(self, name):
684 return self.defined.has_key(name)
687 return "${%s}" % name
689 def set(self, name, value):
690 self.write("set", name, value)
691 self.defined[name] = value
693 def prepend(self, name, value, sep=":"):
694 if isinstance(value, list):
695 value = sep.join(value)
696 value = value + sep + self.get(name)
697 self.write("prepend", name, value)
699 def append(self, name, value, sep=":"):
700 if isinstance(value, list):
701 value = sep.join(value)
702 value = self.get(name) + sep + value
703 self.write("append", name, value)
705 def command_value(self, key, command):
708 def run_env_script(self, module, script):
709 self.write("load", script, "", sign="")
711 # The SALOME launcher template
712 withProfile = """#! /usr/bin/env python
714 ################################################################
715 # WARNING: this file is automatically generated by SalomeTools #
716 # WARNING: and so could be overwritten at any time. #
717 ################################################################
724 # Add the pwdPath to able to run the launcher after unpacking a package
725 # Used only in case of a salomeTools package
726 out_dir_Path=os.path.abspath(os.path.dirname(__file__))
728 # Preliminary work to initialize path to SALOME Python modules
731 sys.path[:0] = [ 'BIN_KERNEL_INSTALL_DIR' ]
732 os.environ['ABSOLUTE_APPLI_PATH'] = 'KERNEL_INSTALL_DIR'
734 # define folder to store omniorb config (initially in virtual application folder)
736 from salomeContextUtils import setOmniOrbUserPath
741 # End of preliminary work
743 # salome doc only works for virtual applications. Therefore we overwrite it with this function
744 def _showDoc(modules):
745 for module in modules:
746 modulePath = os.getenv(module+"_ROOT_DIR")
747 if modulePath != None:
748 baseDir = os.path.join(modulePath, "share", "doc", "salome")
749 docfile = os.path.join(baseDir, "gui", module.upper(), "index.html")
750 if not os.path.isfile(docfile):
751 docfile = os.path.join(baseDir, "tui", module.upper(), "index.html")
752 if not os.path.isfile(docfile):
753 docfile = os.path.join(baseDir, "dev", module.upper(), "index.html")
754 if os.path.isfile(docfile):
755 out, err = subprocess.Popen(["xdg-open", docfile]).communicate()
757 print "Online documentation is not accessible for module:", module
759 print module+"_ROOT_DIR not found!"
762 # Identify application path then locate configuration files
765 if args == ['--help']:
766 from salomeContext import usage
770 #from salomeContextUtils import getConfigFileNames
771 #configFileNames, args, unexisting = getConfigFileNames( args, checkExistence=True )
772 #if len(unexisting) > 0:
773 # print "ERROR: unexisting configuration file(s): " + ', '.join(unexisting)
776 # Create a SalomeContext which parses configFileNames to initialize environment
778 from salomeContext import SalomeContext, SalomeContextException
779 SalomeContext.addToSpecial=addToSpecial
780 context = SalomeContext(None)
782 # Here set specific variables, if needed
783 # context.addToPath('mypath')
784 # context.addToLdLibraryPath('myldlibrarypath')
785 # context.addToPythonPath('mypythonpath')
786 # context.setVariable('myvarname', 'value')
789 context.getLogger().setLevel(40)
791 context.setVariable(r"PRODUCT_ROOT_DIR", out_dir_Path, overwrite=True)
792 # here your local standalone environment
794 if len(args) >1 and args[0]=='doc':
798 # Start SALOME, parsing command line arguments
799 context.runSalome(args)
800 #print 'Thank you for using SALOME!'
803 context.getLogger().setLevel(20)
805 except SalomeContextException, e:
807 logging.getLogger("salome").error(e)
810 def addToSpecial(self, name, value, pathSep=None):
811 "add special dangerous cases: TCLLIBPATH PV_PLUGIN_PATH etc..."
812 #http://computer-programming-forum.com/57-tcl/1dfddc136afccb94.htm
813 #TCLLIBPATH: Tcl treats the contents of that variable as a list. Be happy, for you can now use drive letters on windows.
817 specialBlanksKeys=["TCLLIBPATH", "TKLIBPATH"]
818 specialSemicolonKeys=["PV_PLUGIN_PATH"]
820 if name in specialBlanksKeys: res=" "
821 if name in specialSemicolonKeys: res=";"
827 value = os.path.expandvars(value) # expand environment variables
828 self.getLogger().debug("Add to %s: %s", name, value)
829 env = os.getenv(name, None)
831 os.environ[name] = value
833 os.environ[name] = value + sep + env #explicitely or not special path separator ?whitespace, semicolon?
835 if __name__ == "__main__":