Salome HOME
Porting to Python 2.6 - add coding page specification for Python scripts
[modules/kernel.git] / bin / appli_gen.py
1 #! /usr/bin/env python
2 #  -*- coding: iso-8859-1 -*-
3 #  Copyright (C) 2007-2008  CEA/DEN, EDF R&D, OPEN CASCADE
4 #
5 #  Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
6 #  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
7 #
8 #  This library is free software; you can redistribute it and/or
9 #  modify it under the terms of the GNU Lesser General Public
10 #  License as published by the Free Software Foundation; either
11 #  version 2.1 of the License.
12 #
13 #  This library is distributed in the hope that it will be useful,
14 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
15 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 #  Lesser General Public License for more details.
17 #
18 #  You should have received a copy of the GNU Lesser General Public
19 #  License along with this library; if not, write to the Free Software
20 #  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
21 #
22 #  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
23 #
24 ## \file appli_gen.py
25 #  Create a %SALOME application (virtual Salome installation)
26 #
27 usage="""usage: %prog [options]
28 Typical use is:
29   python appli_gen.py 
30 Typical use with options is:
31   python appli_gen.py --verbose --prefix=<install directory> --config=<configuration file>
32 """
33
34 import os, glob, string, sys, re
35 import shutil
36 import xml.sax
37 import optparse
38 import virtual_salome
39
40 # --- names of tags in XML configuration file
41 appli_tag   = "application"
42 prereq_tag  = "prerequisites"
43 modules_tag = "modules"
44 module_tag  = "module"
45 samples_tag = "samples"
46
47 # --- names of attributes in XML configuration file
48 nam_att  = "name"
49 path_att = "path"
50 gui_att  = "gui"
51
52 # -----------------------------------------------------------------------------
53
54 # --- xml reader for SALOME application configuration file
55
56 class xml_parser:
57     def __init__(self, fileName ):
58         print "Configure parser: processing %s ..." % fileName
59         self.space = []
60         self.config = {}
61         self.config["modules"] = []
62         self.config["guimodules"] = []
63         parser = xml.sax.make_parser()
64         parser.setContentHandler(self)
65         parser.parse(fileName)
66         pass
67
68     def boolValue( self, str ):
69         if str in ("yes", "y", "1"):
70             return 1
71         elif str in ("no", "n", "0"):
72             return 0
73         else:
74             return str
75         pass
76
77     def startElement(self, name, attrs):
78         self.space.append(name)
79         self.current = None
80         # --- if we are analyzing "prerequisites" element then store its "path" attribute
81         if self.space == [appli_tag, prereq_tag] and path_att in attrs.getNames():
82             self.config["prereq_path"] = attrs.getValue( path_att )
83             pass
84         # --- if we are analyzing "samples" element then store its "path" attribute
85         if self.space == [appli_tag, samples_tag] and path_att in attrs.getNames():
86             self.config["samples_path"] = attrs.getValue( path_att )
87             pass
88         # --- if we are analyzing "module" element then store its "name" and "path" attributes
89         elif self.space == [appli_tag,modules_tag,module_tag] and \
90             nam_att in attrs.getNames() and \
91             path_att in attrs.getNames():
92             nam = attrs.getValue( nam_att )
93             path = attrs.getValue( path_att )
94             gui = 1
95             if gui_att in attrs.getNames():
96                 gui = self.boolValue(attrs.getValue( gui_att ))
97                 pass
98             self.config["modules"].append(nam)
99             self.config[nam]=path
100             if gui:
101                 self.config["guimodules"].append(nam)
102                 pass
103             pass
104         pass
105
106     def endElement(self, name):
107         p = self.space.pop()
108         self.current = None
109         pass
110
111     def characters(self, content):
112         pass
113
114     def processingInstruction(self, target, data):
115         pass
116
117     def setDocumentLocator(self, locator):
118         pass
119
120     def startDocument(self):
121         self.read = None
122         pass
123
124     def endDocument(self):
125         self.read = None
126         pass
127
128 # -----------------------------------------------------------------------------
129
130 class params:
131     pass
132
133 # -----------------------------------------------------------------------------
134
135 def makedirs(namedir):
136   if os.path.exists(namedir):
137     dirbak=namedir+".bak"
138     if os.path.exists(dirbak):
139       shutil.rmtree(dirbak)
140     os.rename(namedir,dirbak)
141     os.listdir(dirbak) #sert seulement a mettre a jour le systeme de fichier sur certaines machines
142   os.makedirs(namedir)
143
144 def install(prefix,config_file,verbose=0):
145     home_dir=os.path.abspath(os.path.expanduser(prefix))
146     filename=os.path.abspath(os.path.expanduser(config_file))
147     _config={}
148     try:
149         p = xml_parser(filename)
150         _config = p.config
151     except xml.sax.SAXParseException, inst:
152         print inst.getMessage()
153         print "Configure parser: parse error in configuration file %s" % filename
154         pass
155     except xml.sax.SAXException, inst:
156         print inst.args   
157         print "Configure parser: error in configuration file %s" % filename
158         pass
159     except:
160         print "Configure parser: Error : can not read configuration file %s, check existence and rights" % filename
161         pass
162
163     if verbose:
164         for cle in _config.keys():
165             print cle, _config[cle]
166             pass
167
168     for module in _config["modules"]:
169         print "--- add module ", module, _config[module]
170         options = params()
171         options.verbose=verbose
172         options.clear=0
173         options.prefix=home_dir
174         options.module=_config[module]
175         virtual_salome.link_module(options)
176         pass
177
178     appliskel_dir=os.path.join(home_dir,'bin','salome','appliskel')
179
180     for fn in ('envd',
181                'getAppliPath.py',
182                'searchFreePort.sh',
183                'runRemote.sh',
184                'runAppli',
185                'runConsole',
186                'runSession',
187                'runTests',
188                '.bashrc',
189                ):
190         virtual_salome.symlink("./bin/salome/appliskel/"+fn,os.path.join(home_dir, fn))
191         pass
192
193     if filename != os.path.join(home_dir,"config_appli.xml"):
194         command = "cp -p " + filename + ' ' + os.path.join(home_dir,"config_appli.xml")
195         os.system(command)
196         pass
197        
198     virtual_salome.mkdir(os.path.join(home_dir,'env.d'))
199     if os.path.isfile(_config["prereq_path"]):
200         command='cp -p ' + _config["prereq_path"] + ' ' + os.path.join(home_dir,'env.d','envProducts.sh')
201         os.system(command)
202         pass
203     else:
204         print "WARNING: prerequisite file does not exist"
205         pass
206
207
208     f =open(os.path.join(home_dir,'env.d','configSalome.sh'),'w')
209     for module in _config["modules"]:
210         command='export '+ module + '_ROOT_DIR=${HOME}/${APPLI}\n'
211         f.write(command)
212         pass
213     if _config.has_key("samples_path"):
214         command='export DATA_DIR=' + _config["samples_path"] +'\n'
215         f.write(command)
216         pass
217     f.close()
218
219
220     f =open(os.path.join(home_dir,'env.d','configGUI.sh'),'w')
221     command = 'export SalomeAppConfig=${HOME}/${APPLI}\n'
222     f.write(command)
223     command = 'export SUITRoot=${HOME}/${APPLI}/share/salome\n'
224     f.write(command)
225     f.write('export DISABLE_FPE=1\n')
226     f.write('export MMGT_REENTRANT=1\n')
227     f.close()
228
229
230     f =open(os.path.join(home_dir,'SalomeApp.xml'),'w')
231     command="""<document>
232   <section name="launch">
233     <!-- SALOME launching parameters -->
234     <parameter name="gui"        value="yes"/>
235     <parameter name="splash"     value="yes"/>
236     <parameter name="file"       value="no"/>
237     <parameter name="key"        value="no"/>
238     <parameter name="interp"     value="no"/>
239     <parameter name="logger"     value="no"/>
240     <parameter name="xterm"      value="no"/>
241     <parameter name="portkill"   value="no"/>
242     <parameter name="killall"    value="no"/>
243     <parameter name="noexcepthandler"  value="no"/>
244     <parameter name="modules"    value="""
245     f.write(command)    
246     f.write('"')
247     for module in _config["guimodules"][:-1]:
248         f.write(module)
249         f.write(',')
250         pass
251     if len(_config["guimodules"]) > 0:
252       f.write(_config["guimodules"][-1])
253     f.write('"/>')
254     command="""
255     <parameter name="pyModules"  value=""/>
256     <parameter name="embedded"   value="SalomeAppEngine,study,cppContainer,registry,moduleCatalog"/>
257     <parameter name="standalone" value="pyContainer"/>
258   </section>
259 </document>
260 """
261     f.write(command)    
262     f.close()
263
264     #Add default CatalogResources.xml file
265     f =open(os.path.join(home_dir,'CatalogResources.xml'),'w')
266     command="""<!DOCTYPE ResourcesCatalog>
267 <resources>
268    <machine hostname="localhost" />
269 </resources>
270 """
271     f.write(command)    
272     f.close()
273
274     #Add USERS directory with 777 permission to store users configuration files
275     users_dir=os.path.join(home_dir,'USERS')
276     makedirs(users_dir)
277     os.chmod(users_dir, 0777)
278
279 def main():
280     parser = optparse.OptionParser(usage=usage)
281
282     parser.add_option('--prefix', dest="prefix", default='.',
283                       help="Installation directory (default .)")
284
285     parser.add_option('--config', dest="config", default='config_appli.xml',
286                       help="XML configuration file (default config_appli.xml)")
287
288     parser.add_option('-v', '--verbose', action='count', dest='verbose',
289                       default=0, help="Increase verbosity")
290
291     options, args = parser.parse_args()
292     install(prefix=options.prefix,config_file=options.config,verbose=options.verbose)
293     pass
294
295 # -----------------------------------------------------------------------------
296
297 if __name__ == '__main__':
298     main()
299     pass