Salome HOME
b7d53f8a083572e1a04fa71b95fea15dc47dc210
[tools/sat.git] / commands / generate.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 sys
21 import shutil
22 import imp
23 import subprocess
24
25 import src
26
27 parser = src.options.Options()
28 parser.add_option('p', 'products', 'list2', 'products',
29                   _("the list of products to generate"))
30 parser.add_option('', 'yacsgen', 'string', 'yacsgen',
31                   _("path to YACSGEN's module_generator package"))
32
33 def generate_component_list(config, product_info, context, logger):
34     res = "?"
35     logger.write("\n", 3)
36     for compo in src.product.get_product_components(product_info):
37         header = "  %s %s " % (src.printcolors.printcLabel(compo),
38                                "." * (20 - len(compo)))
39         res = generate_component(config,
40                                  compo,
41                                  product_info,
42                                  context,
43                                  header,
44                                  logger)
45         if config.USER.output_verbose_level == 3:
46             logger.write("\r%s%s\r%s" % (header, " " * 20, header), 3)
47         logger.write(src.printcolors.printc(res), 3, False)
48         logger.write("\n", 3, False)
49     return res
50
51 def generate_component(config, compo, product_info, context, header, logger):
52     hxxfile = compo + ".hxx"
53     cpplib = "lib" + compo + "CXX.so"
54     cpp_path = product_info.install_dir
55
56     logger.write("%s\n" % header, 4, False)
57     src.printcolors.print_value(logger, "hxxfile", hxxfile, 4)
58     src.printcolors.print_value(logger, "cpplib", cpplib, 4)
59     src.printcolors.print_value(logger, "cpp_path", cpp_path, 4)
60
61     # create a product_info at runtime
62     compo_info = src.pyconf.Mapping(config)
63     compo_info.name = compo
64     compo_info.nb_proc = 1
65     generate_dir = os.path.join(config.APPLICATION.workdir, "GENERATED")
66     install_dir = os.path.join(config.APPLICATION.workdir, "INSTALL")
67     build_dir = os.path.join(config.APPLICATION.workdir, "BUILD")
68     compo_info.source_dir = os.path.join(generate_dir, compo + "_SRC")
69     compo_info.install_dir = os.path.join(install_dir, compo)
70     compo_info.build_dir = os.path.join(build_dir, compo)
71     compo_info.depend = product_info.depend
72     compo_info.depend.append(product_info.name, "") # add cpp module
73     compo_info.opt_depend = product_info.opt_depend
74
75     config.PRODUCTS.addMapping(compo, src.pyconf.Mapping(config), "")
76     config.PRODUCTS[compo].default = compo_info
77
78     builder = src.compilation.Builder(config, logger, compo_info, check_src=False)
79     builder.header = header
80
81     # generate the component
82     # create GENERATE dir if necessary
83     if not os.path.exists(generate_dir):
84         os.mkdir(generate_dir)
85
86     # delete previous generated directory if it already exists
87     if os.path.exists(compo_info.source_dir):
88         logger.write("  delete %s\n" % compo_info.source_dir, 4)
89         shutil.rmtree(compo_info.source_dir)
90
91     # generate generates in the current directory => change for generate dir
92     curdir = os.curdir
93     os.chdir(generate_dir)
94
95     # inline class to override bootstrap method
96     import module_generator
97     class sat_generator(module_generator.Generator):
98         # old bootstrap for automake (used if salome version <= 7.4)
99         def bootstrap(self, source_dir, log_file):
100             # replace call to default bootstrap() by using subprocess call (cleaner)
101             command = "sh autogen.sh"
102             ier = subprocess.call(command, shell=True, cwd=source_dir,
103                                   stdout=log_file, stderr=subprocess.STDOUT)
104             if ier != 0:
105                 raise src.SatException("bootstrap has ended in error")
106
107     
108     # determine salome version
109     VersionSalome = src.get_salome_version(config)
110     if VersionSalome >= 750 :
111         use_autotools=False
112         builder.log('USE CMAKE', 3)
113     else:
114         use_autotools=True
115         builder.log('USE AUTOTOOLS', 3)
116
117     result = "GENERATE"
118     builder.log('GENERATE', 3)
119     
120     prevstdout = sys.stdout
121     prevstderr = sys.stderr
122
123     try:
124         sys.stdout = logger.logTxtFile
125         sys.stderr = logger.logTxtFile
126
127         if src.product.product_is_mpi(product_info):
128             salome_compo = module_generator.HXX2SALOMEParaComponent(hxxfile,
129                                                                     cpplib,
130                                                                     cpp_path)
131         else:
132             salome_compo = module_generator.HXX2SALOMEComponent(hxxfile,
133                                                                 cpplib,
134                                                                 cpp_path)
135
136         if src.product.product_has_salome_gui(product_info):
137             # get files to build a template GUI
138             gui_files = salome_compo.getGUIfilesTemplate()
139         else:
140             gui_files = None
141
142         mg = module_generator.Module(compo, components=[salome_compo],
143                                      prefix=generate_dir, gui=gui_files)
144         g = sat_generator(mg, context)
145         g.generate()
146
147         if use_autotools:
148             result = "BUID_CONFIGURE"
149             builder.log('BUID_CONFIGURE (no bootstrap)', 3)
150             g.bootstrap(compo_info.source_dir, logger.logTxtFile)
151
152         result = src.OK_STATUS
153     finally:
154         sys.stdout = prevstdout
155         sys.stderr = prevstderr
156
157     # go back to previous directory
158     os.chdir(curdir)
159
160     # do the compilation using the builder object
161     if builder.prepare()!= 0: return "Error in prepare"
162     if use_autotools:
163         if builder.configure()!= 0: return "Error in configure"
164     else:
165         if builder.cmake()!= 0: return "Error in cmake"
166
167     if builder.make(config.VARS.nb_proc, "")!=0: return "Error in make"
168     if builder.install()!=0: return "Error in make install"
169
170     # copy specified logo in generated component install directory
171     # rem : logo is not copied in source dir because this would require
172     #       to modify the generated makefile
173     logo_path = src.product.product_has_logo(product_info)
174     if logo_path:
175         destlogo = os.path.join(compo_info.install_dir, "share", "salome",
176             "resources", compo.lower(), compo + ".png")
177         src.Path(logo_path).copyfile(destlogo)
178
179     return result
180
181 def build_context(config, logger):
182     products_list = [ 'KERNEL', 'GUI' ]
183     ctxenv = src.environment.SalomeEnviron(config,
184                                            src.environment.Environ(dict(
185                                                                    os.environ)),
186                                            True)
187     ctxenv.silent = True
188     ctxenv.set_full_environ(logger, config.APPLICATION.products.keys())
189
190     dicdir = {}
191     for p in products_list:
192         prod_env = p + "_ROOT_DIR"
193         val = os.getenv(prod_env)
194         if os.getenv(prod_env) is None:
195             if p not in config.APPLICATION.products:
196                 warn = _("product %(product)s is not defined. Include it in the"
197                          " application or define $%(env)s.") % \
198                     { "product": p, "env": prod_env}
199                 logger.write(src.printcolors.printcWarning(warn), 1)
200                 logger.write("\n", 3, False)
201                 val = ""
202             val = ctxenv.environ.environ[prod_env]
203         dicdir[p] = val
204
205     # the dictionary requires all keys 
206     # but the generation requires only values for KERNEL and GUI
207     context = {
208         "update": 1,
209         "makeflags": "-j2",
210         "kernel": dicdir["KERNEL"],
211         "gui":    dicdir["GUI"],
212         "yacs":   "",
213         "med":    "",
214         "mesh":   "",
215         "visu":   "",
216         "geom":   "",
217     }
218     return context
219
220 def check_module_generator(directory=None):
221     """Check if module_generator is available.
222     
223     :param directory str: The directory of YACSGEN.
224     :return: The YACSGEN path if the module_generator is available, else None
225     :rtype: str
226     """
227     undo = False
228     if directory is not None and directory not in sys.path:
229         sys.path.insert(0, directory)
230         undo = True
231     
232     res = None
233     try:
234         #import module_generator
235         info = imp.find_module("module_generator")
236         res = info[1]
237     except ImportError:
238         if undo:
239             sys.path.remove(directory)
240         res = None
241
242     return res
243
244 def check_yacsgen(config, directory, logger):
245     """Check if YACSGEN is available.
246     
247     :param config Config: The global configuration.
248     :param directory str: The directory given by option --yacsgen
249     :param logger Logger: The logger instance
250     :return: The path to yacsgen directory
251     :rtype: str
252     """
253     # first check for YACSGEN (command option, then product, then environment)
254     yacsgen_dir = None
255     yacs_src = "?"
256     if directory is not None:
257         yacsgen_dir = directory
258         yacs_src = _("Using YACSGEN from command line")
259     elif 'YACSGEN' in config.APPLICATION.products:
260         yacsgen_info = src.product.get_product_config(config, 'YACSGEN')
261         yacsgen_dir = yacsgen_info.install_dir
262         yacs_src = _("Using YACSGEN from application")
263     elif os.environ.has_key("YACSGEN_ROOT_DIR"):
264         yacsgen_dir = os.getenv("YACSGEN_ROOT_DIR")
265         yacs_src = _("Using YACSGEN from environment")
266
267     if yacsgen_dir is None:
268         return (False, _("The generate command requires YACSGEN."))
269     
270     logger.write("  %s\n" % yacs_src, 2, True)
271     logger.write("  %s\n" % yacsgen_dir, 5, True)
272
273     if not os.path.exists(yacsgen_dir):
274         message = _("YACSGEN directory not found: '%s'") % yacsgen_dir
275         return (False, _(message))
276     
277     # load module_generator
278     c = check_module_generator(yacsgen_dir)
279     if c is not None:
280         return c
281     
282     pv = os.getenv("PYTHON_VERSION")
283     if pv is None:
284         python_info = src.product.get_product_config(config, "Python")
285         pv = '.'.join(python_info.version.split('.')[:2])
286     assert pv is not None, "$PYTHON_VERSION not defined"
287     yacsgen_dir = os.path.join(yacsgen_dir, "lib", "python%s" % pv,
288                                "site-packages")
289     c = check_module_generator(yacsgen_dir)
290     if c is not None:
291         return c
292
293     return (False,
294             _("The python module module_generator was not found in YACSGEN"))
295
296
297 def description():
298     '''method that is called when salomeTools is called with --help option.
299     
300     :return: The text to display for the generate command description.
301     :rtype: str
302     '''
303     return _("The generate command generates SALOME modules from 'pure cpp' "
304              "products.\nWARNING this command NEEDS YACSGEN to run!")
305
306
307 def run(args, runner, logger):
308     '''method that is called when salomeTools is called with generate parameter.
309     '''
310     
311     # Check that the command has been called with an application
312     src.check_config_has_application(runner.cfg)
313     
314     logger.write(_('Generation of SALOME modules for application %s\n') % \
315         src.printcolors.printcLabel(runner.cfg.VARS.application), 1)
316
317     (options, args) = parser.parse_args(args)
318
319     status = src.KO_STATUS
320
321     # verify that YACSGEN is available
322     yacsgen_dir = check_yacsgen(runner.cfg, options.yacsgen, logger)
323     
324     if isinstance(yacsgen_dir, tuple):
325         # The check failed
326         __, error = yacsgen_dir
327         msg = _("Error: %s" % error)
328         logger.write(src.printcolors.printcError(msg), 1)
329         logger.write("\n", 1)
330         return 1
331     
332     # Make the generator module visible by python
333     sys.path.insert(0, yacsgen_dir)
334
335     src.printcolors.print_value(logger, _("YACSGEN dir"), yacsgen_dir, 3)
336     logger.write("\n", 2)
337     products = runner.cfg.APPLICATION.products
338     if options.products:
339         products = options.products
340
341     details = []
342     nbgen = 0
343
344     context = build_context(runner.cfg, logger)
345     for product in products:
346         header = _("Generating %s") % src.printcolors.printcLabel(product)
347         header += " %s " % ("." * (20 - len(product)))
348         logger.write(header, 3)
349         logger.flush()
350
351         if product not in runner.cfg.PRODUCTS:
352             logger.write(_("Unknown product\n"), 3, False)
353             continue
354
355         pi = src.product.get_product_config(runner.cfg, product)
356         if not src.product.product_is_generated(pi):
357             logger.write(_("not a generated product\n"), 3, False)
358             continue
359
360         nbgen += 1
361         try:
362             result = generate_component_list(runner.cfg,
363                                              pi,
364                                              context,
365                                              logger)
366         except Exception as exc:
367             result = str(exc)
368
369         if result != src.OK_STATUS:
370             result = _("ERROR: %s") % result
371             details.append([product, result])
372
373     if len(details) == 0:
374         status = src.OK_STATUS
375     else: #if config.USER.output_level != 3:
376         logger.write("\n", 2, False)
377         logger.write(_("The following modules were not generated correctly:\n"), 2)
378         for d in details:
379             logger.write("  %s: %s\n" % (d[0], d[1]), 2, False)
380     logger.write("\n", 2, False)
381
382     if status == src.OK_STATUS:
383         return 0
384     return len(details)
385