Salome HOME
begin fix sat test
[tools/sat.git] / src / fileEnviron.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 pprint as PP
21 import src.debug as DBG
22
23 bat_header="""\
24 @echo off
25
26 rem The following variables are used only in case of a sat package
27 set out_dir_Path=%~dp0
28 set PRODUCT_OUT_DIR=%out_dir_Path%
29 set prereq_install_Path=%out_dir_Path%\PREREQUISITES\INSTALL
30 set prereq_build_Path=%out_dir_Path%\PREREQUISITES\BUILD
31 """
32
33
34 bash_header="""\
35 #!/bin/bash
36 ##########################################################################
37 #
38 #### cleandup ###
39 # cleanup a path (first parameter) from duplicated entries;
40 # second parameter is the separator
41 cleandup() {
42 out_var=`echo $1 | awk -v sep=$2 '{                      \\
43      na = split($1,a,sep);                               \\
44      k=0;                                                \\
45      for(i=0;i<=na;i++) {                                \\
46        found=0;                                          \\
47        for(j=0;j<k;j++) {                                \\
48          if(a[i]==aa[j])                                 \\
49          {                                               \\
50            found=1;                                      \\
51            break;                                        \\
52          };                                              \\
53        };                                                \\
54        if(found==0) {                                    \\
55          aa[k++]=a[i];                                   \\
56        };                                                \\
57      };                                                  \\
58      ORS=sep;                                            \\
59      for(i=0;i<k;i++) {                                  \\
60        print aa[i];                                      \\
61      }                                                   \\
62    }' | sed -e 's|\\(.*\\)$1|\\1|g' -e 's|^[:;]||' -e 's|[:;]$||'`
63 echo $out_var
64 }
65 ### clean ###
66 clean ()
67 {
68 xenv=`printenv $1`
69 out_var=`cleandup $xenv $2`
70 export $1=$out_var
71 }
72
73 # The 3 following variables are used only in case of a sat package
74 export out_dir_Path=$(cd $(dirname ${BASH_SOURCE[0]});pwd)
75 export PRODUCT_OUT_DIR=${out_dir_Path}
76 export PRODUCT_ROOT_DIR=${PRODUCT_OUT_DIR}
77
78 ###########################################################################
79 """
80
81 cfg_header="""\
82 [SALOME Configuration]
83 """
84
85 Launcher_header="""\
86 # a generated SALOME Configuration file using python syntax
87 """
88
89 def get_file_environ(output, shell, environ=None):
90     """Instantiate correct FileEnvironment sub-class.
91     
92     :param output file: the output file stream.
93     :param shell str: the type of shell syntax to use.
94     :param environ dict: a potential additional environment.
95     """
96     if shell == "bash":
97         return BashFileEnviron(output, environ)
98     if shell == "bat":
99         return BatFileEnviron(output, environ)
100     if shell == "cfgForPy":
101         return LauncherFileEnviron(output, environ)
102     if shell == "cfg":
103         return ContextFileEnviron(output, environ)
104     raise Exception("FileEnviron: Unknown shell = %s" % shell)
105
106 class FileEnviron(object):
107     """\
108     Base class for shell environment
109     """
110     def __init__(self, output, environ=None):
111         """\
112         Initialization
113         
114         :param output file: the output file stream.
115         :param environ dict: a potential additional environment.
116         """
117         self._do_init(output, environ)
118
119     def __repr__(self):
120         """\
121         easy non exhaustive quick resume for debug print"""
122         res = {
123           "output" : self.output,
124           "environ" : self.environ,
125         }
126         return "%s(\n%s\n)" % (self.__class__.__name__, PP.pformat(res))
127         
128
129     def _do_init(self, output, environ=None):
130         """\
131         Initialization
132         
133         :param output file: the output file stream.
134         :param environ dict: a potential additional environment.
135         """
136         self.output = output
137         self.toclean = []
138         if environ is not None:
139             #if str(type(environ)) == "<type 'instance'>":
140             if id(environ) == id(os.environ):
141                DBG.tofix("set %s environ as python os.environ, are you sure it is safe ?" % self.__class__.__name__, True)
142             self.environ = environ
143         else:
144             DBG.tofix("set %s environ as COPY of python os.environ, are you sure it is safe ?" % self.__class__.__name__, True)
145             self.environ = dict(os.environ) #make a copy cvw 180320
146
147     def add_line(self, number):
148         """\
149         Add some empty lines in the shell file
150         
151         :param number int: the number of lines to add
152         """
153         self.output.write("\n" * number)
154
155     def add_comment(self, comment):
156         """\
157         Add a comment in the shell file
158         
159         :param comment str: the comment to add
160         """
161         self.output.write("# %s\n" % comment)
162
163     def add_echo(self, text):
164         """\
165         Add a "echo" in the shell file
166         
167         :param text str: the text to echo
168         """
169         self.output.write('echo %s"\n' % text)
170
171     def add_warning(self, warning):
172         """\
173         Add a warning "echo" in the shell file
174         
175         :param warning str: the text to echo
176         """
177         self.output.write('echo "WARNING %s"\n' % warning)
178
179     def append_value(self, key, value, sep=os.pathsep):
180         """\
181         append value to key using sep,
182         if value contains ":" or ";" then raise error
183
184         :param key str: the environment variable to append
185         :param value str: the value to append to key
186         :param sep str: the separator string
187         """
188         for c in [";", ":"]: # windows or linux path separators
189           if c in value:
190             raise Exception("FileEnviron append key '%s' value '%s' contains forbidden character '%s'" % (key, value, c))
191         self.set(key, self.get(key) + sep + value)
192         if (key, sep) not in self.toclean:
193             self.toclean.append((key, sep))
194
195     def append(self, key, value, sep=os.pathsep):
196         """\
197         Same as append_value but the value argument can be a list
198         
199         :param key str: the environment variable to append
200         :param value str or list: the value(s) to append to key
201         :param sep str: the separator string
202         """
203         if isinstance(value, list):
204             for v in value:
205                 self.append_value(key, v, sep)
206         else:
207             self.append_value(key, value, sep)
208
209     def prepend_value(self, key, value, sep=os.pathsep):
210         """\
211         prepend value to key using sep,
212         if value contains ":" or ";" then raise error
213         
214         :param key str: the environment variable to prepend
215         :param value str: the value to prepend to key
216         :param sep str: the separator string
217         """
218         for c in [";", ":"]: # windows or linux path separators
219           if c in value:
220             raise Exception("FileEnviron prepend key '%s' value '%s' contains forbidden character '%s'" % (key, value, c))
221         self.set(key, value + sep + self.get(key))
222         if (key, sep) not in self.toclean:
223             self.toclean.append((key, sep))
224
225     def prepend(self, key, value, sep=os.pathsep):
226         """\
227         Same as prepend_value but the value argument can be a list
228         
229         :param key str: the environment variable to prepend
230         :param value str or list: the value(s) to prepend to key
231         :param sep str: the separator string
232         """
233         if isinstance(value, list):
234             for v in reversed(value): # prepend list, first item at last to stay first
235                 self.prepend_value(key, v, sep)
236         else:
237             self.prepend_value(key, value, sep)
238
239     def is_defined(self, key):
240         """\
241         Check if the key exists in the environment
242         
243         :param key str: the environment variable to check
244         """
245         return (key in self.environ)
246
247     def set(self, key, value):
248         """\
249         Set the environment variable 'key' to value 'value'
250         
251         :param key str: the environment variable to set
252         :param value str: the value
253         """
254         raise NotImplementedError("set is not implement for this shell!")
255
256     def get(self, key):
257         """\
258         Get the value of the environment variable "key"
259         
260         :param key str: the environment variable
261         """
262         return '${%s}' % key
263
264     def command_value(self, key, command):
265         """\
266         Get the value given by the system command "command" 
267         and put it in the environment variable key.
268         Has to be overwritten in the derived classes
269         This can be seen as a virtual method
270         
271         :param key str: the environment variable
272         :param command str: the command to execute
273         """
274         raise NotImplementedError("command_value is not implement "
275                                   "for this shell!")
276
277     def finish(self, required=True):
278         """Add a final instruction in the out file (in case of file generation)
279         
280         :param required bool: Do nothing if required is False
281         """
282         for (key, sep) in self.toclean:
283             if sep != ' ':
284                 self.output.write('clean %s "%s"\n' % (key, sep))
285
286 class BashFileEnviron(FileEnviron):
287     """\
288     Class for bash shell.
289     """
290     def __init__(self, output, environ=None):
291         """Initialization
292         
293         :param output file: the output file stream.
294         :param environ dict: a potential additional environment.
295         """
296         self._do_init(output, environ)
297         self.output.write(bash_header)
298
299     def set(self, key, value):
300         """Set the environment variable "key" to value "value"
301         
302         :param key str: the environment variable to set
303         :param value str: the value
304         """
305         self.output.write('export %s="%s"\n' % (key, value))
306         self.environ[key] = value
307
308     def command_value(self, key, command):
309         """\
310         Get the value given by the system command "command" 
311         and put it in the environment variable key.
312         Has to be overwritten in the derived classes
313         This can be seen as a virtual method
314         
315         :param key str: the environment variable
316         :param command str: the command to execute
317         """
318         self.output.write('export %s=$(%s)\n' % (key, command))
319
320     def finish(self, required=True):
321         """Add a final instruction in the out file (in case of file generation)
322         
323         :param required bool: Do nothing if required is False
324         """
325         if not required:
326             return
327         FileEnviron.finish(self, required)
328         
329 class BatFileEnviron(FileEnviron):
330     """\
331     for Windows batch shell.
332     """
333     def __init__(self, output, environ=None):
334         """Initialization
335         
336         :param output file: the output file stream.
337         :param environ dict: a potential additional environment.
338         """
339         self._do_init(output, environ)
340         self.output.write(bat_header)
341
342     def add_comment(self, comment):
343         """Add a comment in the shell file
344         
345         :param comment str: the comment to add
346         """
347         self.output.write("rem %s\n" % comment)
348     
349     def get(self, key):
350         """Get the value of the environment variable "key"
351         
352         :param key str: the environment variable
353         """
354         return '%%%s%%' % key
355     
356     def set(self, key, value):
357         """Set the environment variable "key" to value "value"
358         
359         :param key str: the environment variable to set
360         :param value str: the value
361         """
362         self.output.write('set %s=%s\n' % (key, value))
363         self.environ[key] = value
364
365     def command_value(self, key, command):
366         """\
367         Get the value given by the system command "command" 
368         and put it in the environment variable key.
369         Has to be overwritten in the derived classes
370         This can be seen as a virtual method
371         
372         :param key str: the environment variable
373         :param command str: the command to execute
374         """
375         self.output.write('%s > tmp.txt\n' % (command))
376         self.output.write('set /p %s =< tmp.txt\n' % (key))
377
378     def finish(self, required=True):
379         """\
380         Add a final instruction in the out file (in case of file generation)
381         In the particular windows case, do nothing
382         
383         :param required bool: Do nothing if required is False
384         """
385         return
386
387 class ContextFileEnviron(FileEnviron):
388     """Class for a salome context configuration file.
389     """
390     def __init__(self, output, environ=None):
391         """Initialization
392         
393         :param output file: the output file stream.
394         :param environ dict: a potential additional environment.
395         """
396         self._do_init(output, environ)
397         self.output.write(cfg_header)
398
399     def set(self, key, value):
400         """Set the environment variable "key" to value "value"
401         
402         :param key str: the environment variable to set
403         :param value str: the value
404         """
405         self.output.write('%s="%s"\n' % (key, value))
406         self.environ[key] = value
407
408     def get(self, key):
409         """Get the value of the environment variable "key"
410         
411         :param key str: the environment variable
412         """
413         return '%({0})s'.format(key)
414
415     def command_value(self, key, command):
416         """\
417         Get the value given by the system command "command" 
418         and put it in the environment variable key.
419         Has to be overwritten in the derived classes
420         This can be seen as a virtual method
421         
422         :param key str: the environment variable
423         :param command str: the command to execute
424         """
425         raise NotImplementedError("command_value is not implement "
426                                   "for salome context files!")
427
428     def add_echo(self, text):
429         """Add a comment
430         
431         :param text str: the comment to add
432         """
433         self.add_comment(text)
434
435     def add_warning(self, warning):
436         """Add a warning
437         
438         :param text str: the warning to add
439         """
440         self.add_comment("WARNING %s"  % warning)
441
442     def prepend_value(self, key, value, sep=os.pathsep):
443         """prepend value to key using sep
444         
445         :param key str: the environment variable to prepend
446         :param value str: the value to prepend to key
447         :param sep str: the separator string
448         """
449         self.output.write('ADD_TO_%s: %s\n' % (key, value))
450
451     def append_value(self, key, value, sep=os.pathsep):
452         """append value to key using sep
453         
454         :param key str: the environment variable to append
455         :param value str: the value to append to key
456         :param sep str: the separator string
457         """
458         self.prepend_value(key, value)
459
460     def finish(self, required=True):
461         """Add a final instruction in the out file (in case of file generation)
462         
463         :param required bool: Do nothing if required is False
464         """
465         return
466
467 def special_path_separator(name):
468     """\
469     TCLLIBPATH, TKLIBPATH, PV_PLUGIN_PATH environments variables need
470     some exotic path separator.
471     This function gives the separator regarding the name of the variable
472     to append or prepend.
473        
474     :param name str: The name of the variable to find the separator
475     """
476     special_blanks_keys=["TCLLIBPATH", "TKLIBPATH"]
477     special_semicolon_keys=["PV_PLUGIN_PATH"]
478     res=os.pathsep
479     if name in special_blanks_keys: res=" "
480     if name in special_semicolon_keys: res=";"
481     return res
482
483 class LauncherFileEnviron:
484     """\
485     Class to generate a launcher file script 
486     (in python syntax) SalomeContext API
487     """
488     def __init__(self, output, environ=None):
489         """Initialization
490         
491         :param output file: the output file stream.
492         :param environ dict: a potential additional environment.
493         """
494         self.output = output
495         self.toclean = []
496         if environ is not None:
497             self.environ = environ
498         else:
499             self.environ = os.environ
500         # Initialize some variables
501         if not "PATH" in self.environ.keys():
502             self.environ["PATH"]=""
503         if not "LD_LIBRARY_PATH" in self.environ.keys():
504             self.environ["LD_LIBRARY_PATH"]=""
505         if not "PYTHONPATH" in self.environ.keys():
506             self.environ["PYTHONPATH"]=""
507         if not "TCLLIBPATH" in self.environ.keys():
508             self.environ["TCLLIBPATH"]=""
509         if not "TKLIBPATH" in self.environ.keys():
510             self.environ["TKLIBPATH"]=""
511
512         # four whitespaces for first indentation in a python script
513         self.indent="    "
514         self.prefix="context."
515         self.setVarEnv="setVariable"
516         
517         self.begin=self.indent+self.prefix
518         self.output.write(Launcher_header)
519         self.specialKeys={"PATH": "Path",
520                           "LD_LIBRARY_PATH": "LdLibraryPath",
521                           "PYTHONPATH": "PythonPath"}
522
523     def change_to_launcher(self, value):
524         res=value
525         return res
526
527     def add_line(self, number):
528         """Add some empty lines in the launcher file
529         
530         :param number int: the number of lines to add
531         """
532         self.output.write("\n" * number)
533
534     def add_echo(self, text):
535         """Add a comment
536         
537         :param text str: the comment to add
538         """
539         self.output.write('# %s"\n' % text)
540
541     def add_warning(self, warning):
542         """Add a warning
543         
544         :param text str: the warning to add
545         """
546         self.output.write('# "WARNING %s"\n' % warning)
547
548     def append_value(self, key, value, sep=":"):
549         """append value to key using sep,
550         if value contains ":" or ";" then raise error
551         
552         :param key str: the environment variable to append
553         :param value str: the value to append to key
554         :param sep str: the separator string
555         """
556         for c in [";", ":"]: # windows or linux path separators
557           if c in value:
558             raise Exception("LauncherFileEnviron append key '%s' value '%s' contains forbidden character '%s'" % (key, value, c))
559         if self.is_defined(key) :
560             self.add(key, value)
561         else :
562             self.set(key, value)
563
564     def append(self, key, value, sep=":"):
565         """Same as append_value but the value argument can be a list
566         
567         :param key str: the environment variable to append
568         :param value str or list: the value(s) to append to key
569         :param sep str: the separator string
570         """
571         if isinstance(value, list):
572             for v in value:
573                 self.append_value(key, v, sep)
574         else:
575             self.append_value(key, value, sep)
576
577     def prepend_value(self, key, value, sep=":"):
578         """prepend value to key using sep,
579         if value contains ":" or ";" then raise error
580         
581         :param key str: the environment variable to prepend
582         :param value str: the value to prepend to key
583         :param sep str: the separator string
584         """
585         for c in [";", ":"]: # windows or linux path separators
586           if c in value:
587             raise Exception("LauncherFileEnviron prepend key '%s' value '%s' contains forbidden character '%s'" % (key, value, c))
588         if self.is_defined(key) :
589             self.add(key, value)
590         else :
591             self.set(key, value)
592
593     def prepend(self, key, value, sep=":"):
594         """Same as prepend_value but the value argument can be a list
595         
596         :param key str: the environment variable to prepend
597         :param value str or list: the value(s) to prepend to key
598         :param sep str: the separator string
599         """
600         if isinstance(value, list):
601             for v in value:
602                 self.prepend_value(key, v, sep)
603         else:
604             self.prepend_value(key, value, sep)
605
606     def is_defined(self, key):
607         """Check if the key exists in the environment
608         
609         :param key str: the environment variable to check
610         """
611         return key in self.environ.keys()
612
613     def get(self, key):
614         """Get the value of the environment variable "key"
615         
616         :param key str: the environment variable
617         """
618         return '${%s}' % key
619
620     def set(self, key, value):
621         """Set the environment variable "key" to value "value"
622         
623         :param key str: the environment variable to set
624         :param value str: the value
625         """
626         self.output.write(self.begin+self.setVarEnv+
627                           '(r"%s", r"%s", overwrite=True)\n' % 
628                           (key, self.change_to_launcher(value)))
629         self.environ[key] = value
630     
631     def add(self, key, value):
632         """prepend value to key using sep
633         
634         :param key str: the environment variable to prepend
635         :param value str: the value to prepend to key
636         """     
637         if key in self.specialKeys.keys():
638             self.output.write(self.begin+'addTo%s(r"%s")\n' % 
639                               (self.specialKeys[key],
640                                self.change_to_launcher(value)))
641             self.environ[key]+=":"+value
642             return
643         sep=special_path_separator(key)
644         self.output.write(self.indent+
645                           '#temporary solution!!! have to be defined in API a '
646                           '?dangerous? addToSpecial(r"%s", r"%s")\n' % 
647                           (key, value))
648         #pathsep not precised because do not know future os launch?
649         self.output.write(self.begin+'addToSpecial(r"%s", r"%s")\n' 
650                           % (key, self.change_to_launcher(value)))
651         self.environ[key]+=sep+value #here yes we know os for current execution
652
653     def command_value(self, key, command):
654         """\
655         Get the value given by the system command "command" 
656         and put it in the environment variable key.
657         
658         :param key str: the environment variable
659         :param command str: the command to execute
660         """
661         self.output.write(self.indent+'#`%s`\n' % command)
662
663         import shlex, subprocess
664         args = shlex.split(command)
665         res=subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
666         out, __ = res.communicate()
667         self.output.write(self.begin+
668                           self.setVarEnv+
669                           '(r"%s", r"%s", overwrite=True)\n' % (key, out))
670
671     def add_comment(self, comment):
672         # Special comment in case of the distène licence
673         if comment=="DISTENE license":
674             self.output.write(self.indent+
675                               "#"+
676                               self.prefix+
677                               self.setVarEnv+
678                               '(r"%s", r"%s", overwrite=True)\n' % 
679                               ('DISTENE_LICENSE_FILE', 
680                                self.change_to_launcher(
681                                             'Use global envvar: DLIM8VAR')))
682             self.output.write(self.indent+
683                               "#"+
684                               self.prefix+
685                               self.setVarEnv+
686                               '(r"%s", r"%s", overwrite=True)\n' % 
687                               ('DLIM8VAR', 
688                                self.change_to_launcher(
689                                                 '<your licence>')))
690             return
691         if "setting environ for" in comment:
692             self.output.write(self.indent+"#[%s]\n" % 
693                               comment.split("setting environ for ")[1])
694             return
695
696         self.output.write(self.indent+"# %s\n" % comment)
697
698     def finish(self, required=True):
699         """\
700         Add a final instruction in the out file (in case of file generation)
701         In the particular launcher case, do nothing
702         
703         :param required bool: Do nothing if required is False
704         """
705         return
706
707 class ScreenEnviron(FileEnviron):
708     def __init__(self, output, environ=None):
709         self._do_init(output, environ)
710         self.defined = {}
711
712     def add_line(self, number):
713         pass
714
715     def add_comment(self, comment):
716         pass
717
718     def add_echo(self, text):
719         pass
720
721     def add_warning(self, warning):
722         pass
723
724     def write(self, command, name, value, sign="="):
725         import src
726         self.output.write("  %s%s %s %s %s\n" % \
727             (src.printcolors.printcLabel(command),
728              " " * (12 - len(command)),
729              src.printcolors.printcInfo(name), sign, value))
730
731     def is_defined(self, name):
732         return name in self.defined
733
734     def get(self, name):
735         return "${%s}" % name
736
737     def set(self, name, value):
738         self.write("set", name, value)
739         self.defined[name] = value
740
741     def prepend(self, name, value, sep=":"):
742         if isinstance(value, list):
743             value = sep.join(value)
744         value = value + sep + self.get(name)
745         self.write("prepend", name, value)
746
747     def append(self, name, value, sep=":"):
748         if isinstance(value, list):
749             value = sep.join(value)
750         value = self.get(name) + sep + value
751         self.write("append", name, value)
752
753     def command_value(self, key, command):
754         pass
755
756     def run_env_script(self, module, script):
757         self.write("load", script, "", sign="")
758
759 # The SALOME launcher template 
760 withProfile =  """\
761 #! /usr/bin/env python
762
763 ################################################################
764 # WARNING: this file is automatically generated by SalomeTools #
765 # WARNING: and so could be overwritten at any time.            #
766 ################################################################
767
768 import os
769 import sys
770 import subprocess
771
772
773 # Add the pwdPath to able to run the launcher after unpacking a package
774 # Used only in case of a salomeTools package
775 out_dir_Path=os.path.dirname(os.path.realpath(__file__))
776
777 # Preliminary work to initialize path to SALOME Python modules
778 def __initialize():
779
780   sys.path[:0] = [ 'BIN_KERNEL_INSTALL_DIR' ]
781   os.environ['ABSOLUTE_APPLI_PATH'] = 'KERNEL_INSTALL_DIR'
782   
783   # define folder to store omniorb config (initially in virtual application folder)
784   try:
785     from salomeContextUtils import setOmniOrbUserPath
786     setOmniOrbUserPath()
787   except Exception as e:
788     print(e)
789     sys.exit(1)
790 # End of preliminary work
791
792 # salome doc only works for virtual applications. Therefore we overwrite it with this function
793 def _showDoc(modules):
794     for module in modules:
795       modulePath = os.getenv(module+"_ROOT_DIR")
796       if modulePath != None:
797         baseDir = os.path.join(modulePath, "share", "doc", "salome")
798         docfile = os.path.join(baseDir, "gui", module.upper(), "index.html")
799         if not os.path.isfile(docfile):
800           docfile = os.path.join(baseDir, "tui", module.upper(), "index.html")
801         if not os.path.isfile(docfile):
802           docfile = os.path.join(baseDir, "dev", module.upper(), "index.html")
803         if os.path.isfile(docfile):
804           out, err = subprocess.Popen(["xdg-open", docfile]).communicate()
805         else:
806           print "Online documentation is not accessible for module:", module
807       else:
808         print module+"_ROOT_DIR not found!"
809
810 def main(args):
811   # Identify application path then locate configuration files
812   __initialize()
813
814   if args == ['--help']:
815     from salomeContext import usage
816     usage()
817     sys.exit(0)
818
819   #from salomeContextUtils import getConfigFileNames
820   #configFileNames, args, unexisting = getConfigFileNames( args, checkExistence=True )
821   #if len(unexisting) > 0:
822   #  print "ERROR: unexisting configuration file(s): " + ', '.join(unexisting)
823   #  sys.exit(1)
824
825   # Create a SalomeContext which parses configFileNames to initialize environment
826   try:
827     from salomeContext import SalomeContext, SalomeContextException
828     SalomeContext.addToSpecial=addToSpecial
829     context = SalomeContext(None)
830     
831     # Here set specific variables, if needed
832     # context.addToPath('mypath')
833     # context.addToLdLibraryPath('myldlibrarypath')
834     # context.addToPythonPath('mypythonpath')
835     # context.setVariable('myvarname', 'value')
836
837     # Logger level error
838     context.getLogger().setLevel(40)
839
840     context.setVariable(r"PRODUCT_ROOT_DIR", out_dir_Path, overwrite=True)
841     # here your local standalone environment
842
843     if len(args) >1 and args[0]=='doc':
844         _showDoc(args[1:])
845         return
846
847     # Start SALOME, parsing command line arguments
848     out, err, status = context.runSalome(args)
849     sys.exit(status)
850
851   except SalomeContextException, e:
852     import logging
853     logging.getLogger("salome").error(e)
854     sys.exit(1)
855 #
856 def addToSpecial(self, name, value, pathSep=None):
857   # add special dangerous cases: TCLLIBPATH PV_PLUGIN_PATH etc...
858   # http://computer-programming-forum.com/57-tcl/1dfddc136afccb94.htm
859   # TCLLIBPATH: Tcl treats the contents of that variable as a list. Be happy, for you can now use drive letters on windows.
860   if value == '':
861     return
862   
863   specialBlanksKeys=["TCLLIBPATH", "TKLIBPATH"]
864   specialSemicolonKeys=["PV_PLUGIN_PATH"]
865   res=os.pathsep
866   if name in specialBlanksKeys: res=" "
867   if name in specialSemicolonKeys: res=";"
868   
869   if pathSep==None:
870     sep=res
871   else:
872     sep=pathSep
873   value = os.path.expandvars(value) # expand environment variables
874   self.getLogger().debug("Add to %s: %s", name, value)
875   env = os.getenv(name, None)
876   if env is None:
877     os.environ[name] = value
878   else:
879     os.environ[name] = value + sep + env #explicitely or not special path separator ?whitespace, semicolon?
880
881 if __name__ == "__main__":
882   args = sys.argv[1:]
883   main(args)
884 #
885 """
886     
887 withProfile3 =  """\
888 #! /usr/bin/env python3
889
890 ################################################################
891 # WARNING: this file is automatically generated by SalomeTools #
892 # WARNING: and so could be overwritten at any time.            #
893 ################################################################
894
895 import os
896 import sys
897 import subprocess
898
899
900 # Add the pwdPath to able to run the launcher after unpacking a package
901 # Used only in case of a salomeTools package
902 out_dir_Path=os.path.dirname(os.path.realpath(__file__))
903
904 # Preliminary work to initialize path to SALOME Python modules
905 def __initialize():
906
907   sys.path[:0] = [ 'BIN_KERNEL_INSTALL_DIR' ]
908   os.environ['ABSOLUTE_APPLI_PATH'] = 'KERNEL_INSTALL_DIR'
909   
910   # define folder to store omniorb config (initially in virtual application folder)
911   try:
912     from salomeContextUtils import setOmniOrbUserPath
913     setOmniOrbUserPath()
914   except Exception as e:
915     print(e)
916     sys.exit(1)
917 # End of preliminary work
918
919 # salome doc only works for virtual applications. Therefore we overwrite it with this function
920 def _showDoc(modules):
921     for module in modules:
922       modulePath = os.getenv(module+"_ROOT_DIR")
923       if modulePath != None:
924         baseDir = os.path.join(modulePath, "share", "doc", "salome")
925         docfile = os.path.join(baseDir, "gui", module.upper(), "index.html")
926         if not os.path.isfile(docfile):
927           docfile = os.path.join(baseDir, "tui", module.upper(), "index.html")
928         if not os.path.isfile(docfile):
929           docfile = os.path.join(baseDir, "dev", module.upper(), "index.html")
930         if os.path.isfile(docfile):
931           out, err = subprocess.Popen(["xdg-open", docfile]).communicate()
932         else:
933           print("Online documentation is not accessible for module:", module)
934       else:
935         print(module+"_ROOT_DIR not found!")
936
937 def main(args):
938   # Identify application path then locate configuration files
939   __initialize()
940
941   if args == ['--help']:
942     from salomeContext import usage
943     usage()
944     sys.exit(0)
945
946   #from salomeContextUtils import getConfigFileNames
947   #configFileNames, args, unexisting = getConfigFileNames( args, checkExistence=True )
948   #if len(unexisting) > 0:
949   #  print("ERROR: unexisting configuration file(s): " + ', '.join(unexisting))
950   #  sys.exit(1)
951
952   # Create a SalomeContext which parses configFileNames to initialize environment
953   try:
954     from salomeContext import SalomeContext, SalomeContextException
955     SalomeContext.addToSpecial=addToSpecial
956     context = SalomeContext(None)
957     
958     # Here set specific variables, if needed
959     # context.addToPath('mypath')
960     # context.addToLdLibraryPath('myldlibrarypath')
961     # context.addToPythonPath('mypythonpath')
962     # context.setVariable('myvarname', 'value')
963
964     # Logger level error
965     context.getLogger().setLevel(40)
966
967     context.setVariable(r"PRODUCT_ROOT_DIR", out_dir_Path, overwrite=True)
968     # here your local standalone environment
969
970     if len(args) >1 and args[0]=='doc':
971         _showDoc(args[1:])
972         return
973
974     # Start SALOME, parsing command line arguments
975     out, err, status = context.runSalome(args)
976     sys.exit(status)
977
978   except SalomeContextException as e:
979     import logging
980     logging.getLogger("salome").error(e)
981     sys.exit(1)
982 #
983 def addToSpecial(self, name, value, pathSep=None):
984   # add special dangerous cases: TCLLIBPATH PV_PLUGIN_PATH etc...
985   # http://computer-programming-forum.com/57-tcl/1dfddc136afccb94.htm
986   # TCLLIBPATH: Tcl treats the contents of that variable as a list. Be happy, for you can now use drive letters on windows.
987   if value == '':
988     return
989   
990   specialBlanksKeys=["TCLLIBPATH", "TKLIBPATH"]
991   specialSemicolonKeys=["PV_PLUGIN_PATH"]
992   res=os.pathsep
993   if name in specialBlanksKeys: res=" "
994   if name in specialSemicolonKeys: res=";"
995   
996   if pathSep==None:
997     sep=res
998   else:
999     sep=pathSep
1000   value = os.path.expandvars(value) # expand environment variables
1001   self.getLogger().debug("Add to %s: %s", name, value)
1002   env = os.getenv(name, None)
1003   if env is None:
1004     os.environ[name] = value
1005   else:
1006     os.environ[name] = value + sep + env #explicitely or not special path separator ?whitespace, semicolon?
1007
1008 if __name__ == "__main__":
1009   args = sys.argv[1:]
1010   main(args)
1011 #
1012 """
1013