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