Salome HOME
update doc for salome command and application
[modules/kernel.git] / bin / appli_gen.py
1 #! /usr/bin/env python
2 #  -*- coding: iso-8859-1 -*-
3 # Copyright (C) 2007-2016  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, or (at your option) any later version.
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
25 ## \file appli_gen.py
26 #  Create a %SALOME application (virtual Salome installation)
27 #
28 usage = """%(prog)s [options]
29 Typical use is:
30   python %(prog)s
31 Typical use with options is:
32   python %(prog)s --verbose --prefix=<install directory> --config=<configuration file>
33 """
34
35 import os
36 import sys
37 import shutil
38 import virtual_salome
39 import xml.sax
40 import optparse
41
42 # --- names of tags in XML configuration file
43 appli_tag   = "application"
44 context_tag = "context"
45 sha1_collect_tag = "sha1_collections"
46 modules_tag = "modules"
47 module_tag  = "module"
48 samples_tag = "samples"
49 extra_tests_tag = "extra_tests"
50 extra_test_tag = "extra_test"
51 resources_tag = "resources"
52
53 # --- names of attributes in XML configuration file
54 nam_att  = "name"
55 path_att = "path"
56 gui_att  = "gui"
57
58 # -----------------------------------------------------------------------------
59
60 # --- xml reader for SALOME application configuration file
61
62 class xml_parser:
63     def __init__(self, fileName ):
64         print "Configure parser: processing %s ..." % fileName
65         self.space = []
66         self.config = {}
67         self.config["modules"] = []
68         self.config["guimodules"] = []
69         self.config["extra_tests"] = []
70         parser = xml.sax.make_parser()
71         parser.setContentHandler(self)
72         parser.parse(fileName)
73         pass
74
75     def boolValue( self, text):
76         if text in ("yes", "y", "1"):
77             return 1
78         elif text in ("no", "n", "0"):
79             return 0
80         else:
81             return text
82         pass
83
84     def startElement(self, name, attrs):
85         self.space.append(name)
86         self.current = None
87         # --- if we are analyzing "context" element then store its "path" attribute
88         if self.space == [appli_tag, context_tag] and path_att in attrs.getNames():
89             self.config["context_path"] = attrs.getValue( path_att )
90             pass
91         # --- if we are analyzing "sha1_collection" element then store its "path" attribute
92         if self.space == [appli_tag, sha1_collect_tag] and path_att in attrs.getNames():
93             self.config["sha1_collect_path"] = attrs.getValue( path_att )
94             pass
95         # --- if we are analyzing "resources" element then store its "path" attribute
96         if self.space == [appli_tag, resources_tag] and path_att in attrs.getNames():
97             self.config["resources_path"] = attrs.getValue( path_att )
98             pass
99         # --- if we are analyzing "samples" element then store its "path" attribute
100         if self.space == [appli_tag, samples_tag] and path_att in attrs.getNames():
101             self.config["samples_path"] = attrs.getValue( path_att )
102             pass
103         # --- if we are analyzing "module" element then store its "name" and "path" attributes
104         elif self.space == [appli_tag,modules_tag,module_tag] and \
105             nam_att in attrs.getNames() and \
106             path_att in attrs.getNames():
107             nam = attrs.getValue( nam_att )
108             path = attrs.getValue( path_att )
109             gui = 1
110             if gui_att in attrs.getNames():
111                 gui = self.boolValue(attrs.getValue( gui_att ))
112                 pass
113             self.config["modules"].append(nam)
114             self.config[nam]=path
115             if gui:
116                 self.config["guimodules"].append(nam)
117                 pass
118             pass
119         # --- if we are analyzing "extra_test" element then store its "name" and "path" attributes
120         elif self.space == [appli_tag,extra_tests_tag,extra_test_tag] and \
121             nam_att in attrs.getNames() and \
122             path_att in attrs.getNames():
123             nam = attrs.getValue( nam_att )
124             path = attrs.getValue( path_att )
125             self.config["extra_tests"].append(nam)
126             self.config[nam]=path
127             pass
128         pass
129
130     def endElement(self, name):
131         self.space.pop()
132         self.current = None
133         pass
134
135     def characters(self, content):
136         pass
137
138     def processingInstruction(self, target, data):
139         pass
140
141     def setDocumentLocator(self, locator):
142         pass
143
144     def startDocument(self):
145         self.read = None
146         pass
147
148     def endDocument(self):
149         self.read = None
150         pass
151
152 # -----------------------------------------------------------------------------
153
154 class params:
155     pass
156
157 # -----------------------------------------------------------------------------
158
159 def makedirs(namedir):
160   if os.path.exists(namedir):
161     dirbak = namedir+".bak"
162     if os.path.exists(dirbak):
163       shutil.rmtree(dirbak)
164     os.rename(namedir, dirbak)
165     os.listdir(dirbak) #sert seulement a mettre a jour le systeme de fichier sur certaines machines
166   os.makedirs(namedir)
167
168 def install(prefix, config_file, verbose=0):
169     home_dir = os.path.abspath(os.path.expanduser(prefix))
170     filename = os.path.abspath(os.path.expanduser(config_file))
171     _config = {}
172     try:
173         parser = xml_parser(filename)
174         _config = parser.config
175     except xml.sax.SAXParseException, inst:
176         print inst.getMessage()
177         print "Configure parser: parse error in configuration file %s" % filename
178         pass
179     except xml.sax.SAXException, inst:
180         print inst.args
181         print "Configure parser: error in configuration file %s" % filename
182         pass
183     except:
184         print "Configure parser: Error : can not read configuration file %s, check existence and rights" % filename
185         pass
186
187     if verbose:
188         for cle,val in _config.items():
189             print cle, val
190             pass
191
192     # Remove CTestTestfile.cmake; this file will be filled by successive calls to link_module and link_extra_test
193     try:
194       ctest_file = os.path.join(home_dir, 'bin', 'salome', 'test', "CTestTestfile.cmake")
195       os.remove(ctest_file)
196     except:
197       pass
198
199     for module in _config.get("modules", []):
200         if _config.has_key(module):
201             print "--- add module ", module, _config[module]
202             options = params()
203             options.verbose = verbose
204             options.clear = 0
205             options.prefix = home_dir
206             options.module_name = module
207             options.module_path = _config[module]
208             virtual_salome.link_module(options)
209             pass
210         pass
211
212     for extra_test in _config.get("extra_tests", []):
213         if _config.has_key(extra_test):
214             print "--- add extra test ", extra_test, _config[extra_test]
215             options = params()
216             options.verbose = verbose
217             options.clear = 0
218             options.prefix = home_dir
219             options.extra_test_name = extra_test
220             options.extra_test_path = _config[extra_test]
221             virtual_salome.link_extra_test(options)
222             pass
223         pass
224
225     # Generate CTestCustom.cmake to handle long output
226     ctest_custom = os.path.join(home_dir, 'bin', 'salome', 'test', "CTestCustom.cmake")
227     with open(ctest_custom, 'w') as f:
228       f.write("SET(CTEST_CUSTOM_MAXIMUM_PASSED_TEST_OUTPUT_SIZE 1048576) # 1MB\n")
229       f.write("SET(CTEST_CUSTOM_MAXIMUM_FAILED_TEST_OUTPUT_SIZE 1048576) # 1MB\n")
230
231     appliskel_dir = os.path.join(home_dir, 'bin', 'salome', 'appliskel')
232
233     for fn in ('envd',
234                'getAppliPath.py',
235                'kill_remote_containers.py',
236                'runRemote.sh',
237                'salome',
238                'update_catalogs.py',
239                '.bashrc',
240                ):
241         virtual_salome.symlink( os.path.join( appliskel_dir, fn ), os.path.join( home_dir, fn) )
242         pass
243
244     if filename != os.path.join(home_dir,"config_appli.xml"):
245         shutil.copyfile(filename, os.path.join(home_dir,"config_appli.xml"))
246         pass
247
248
249     # Add .salome-completion.sh file
250     shutil.copyfile(os.path.join(appliskel_dir, ".salome-completion.sh"),
251                     os.path.join(home_dir, ".salome-completion.sh"))
252
253
254     # Creation of env.d directory
255     virtual_salome.mkdir(os.path.join(home_dir,'env.d'))
256
257     if _config.has_key("context_path") and os.path.isfile(_config["context_path"]):
258         shutil.copyfile(_config["context_path"],
259                         os.path.join(home_dir, 'env.d', 'envProducts.cfg'))
260         pass
261     else:
262         print "WARNING: context file does not exist"
263         pass
264
265     if _config.has_key("sha1_collect_path") and os.path.isfile(_config["sha1_collect_path"]):
266         shutil.copyfile(_config["sha1_collect_path"],
267                         os.path.join(home_dir, 'sha1_collections.txt'))
268         pass
269     else:
270         print "WARNING: context file does not exist"
271         pass
272
273     # Create configuration file: configSalome.cfg
274     with open(os.path.join(home_dir, 'env.d', 'configSalome.cfg'),'w') as f:
275         command = "[SALOME ROOT_DIR (modules) Configuration]\n"
276         f.write(command)
277         for module in _config.get("modules", []):
278             command = module + '_ROOT_DIR=${HOME}/${APPLI}\n'
279             f.write(command)
280             pass
281         if _config.has_key("samples_path"):
282             command = 'DATA_DIR=' + _config["samples_path"] +'\n'
283             f.write(command)
284             pass
285         if _config.has_key("resources_path") and os.path.isfile(_config["resources_path"]):
286             command = 'USER_CATALOG_RESOURCES_FILE=' + os.path.abspath(_config["resources_path"]) +'\n'
287             f.write(command)
288
289     # Create configuration file: configGUI.cfg
290     with open(os.path.join(home_dir, 'env.d', 'configGUI.cfg'),'w') as f:
291         command = """[SALOME GUI Configuration]
292 SalomeAppConfig=${HOME}/${APPLI}
293 SUITRoot=${HOME}/${APPLI}/share/salome
294 DISABLE_FPE=1
295 MMGT_REENTRANT=1
296 """
297         f.write(command)
298
299     #SalomeApp.xml file
300     with open(os.path.join(home_dir,'SalomeApp.xml'),'w') as f:
301         command = """<document>
302   <section name="launch">
303     <!-- SALOME launching parameters -->
304     <parameter name="gui"        value="yes"/>
305     <parameter name="splash"     value="yes"/>
306     <parameter name="file"       value="no"/>
307     <parameter name="key"        value="no"/>
308     <parameter name="interp"     value="no"/>
309     <parameter name="logger"     value="no"/>
310     <parameter name="xterm"      value="no"/>
311     <parameter name="portkill"   value="no"/>
312     <parameter name="killall"    value="no"/>
313     <parameter name="noexcepthandler"  value="no"/>
314     <parameter name="modules"    value="%s"/>
315     <parameter name="pyModules"  value=""/>
316     <parameter name="embedded"   value="SalomeAppEngine,study,cppContainer,registry,moduleCatalog"/>
317     <parameter name="standalone" value=""/>
318   </section>
319 </document>
320 """
321         mods = []
322         #Keep all modules except KERNEL and GUI
323         for module in _config.get("modules", []):
324             if module in ("KERNEL","GUI"):
325                 continue
326             mods.append(module)
327         f.write(command % ",".join(mods))
328
329     #Add USERS directory with 777 permission to store users configuration files
330     users_dir = os.path.join(home_dir,'USERS')
331     makedirs(users_dir)
332     os.chmod(users_dir, 0777)
333
334 def main():
335     parser = optparse.OptionParser(usage=usage)
336
337     parser.add_option('--prefix', dest="prefix", default='.',
338                       help="Installation directory (default .)")
339
340     parser.add_option('--config', dest="config", default='config_appli.xml',
341                       help="XML configuration file (default config_appli.xml)")
342
343     parser.add_option('-v', '--verbose', action='count', dest='verbose',
344                       default=0, help="Increase verbosity")
345
346     options, args = parser.parse_args()
347     if not os.path.exists(options.config):
348         print "ERROR: config file %s does not exist. It is mandatory." % options.config
349         sys.exit(1)
350
351     install(prefix=options.prefix, config_file=options.config, verbose=options.verbose)
352     pass
353
354 # -----------------------------------------------------------------------------
355
356 if __name__ == '__main__':
357     main()
358     pass