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