]> SALOME platform Git repositories - tools/sat.git/blob - commands/compile.py
Salome HOME
add the generate command
[tools/sat.git] / commands / compile.py
1 #!/usr/bin/env python
2 #-*- coding:utf-8 -*-
3 #  Copyright (C) 2010-2012  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
21 import src
22
23 # Compatibility python 2/3 for input function
24 # input stays input for python 3 and input = raw_input for python 2
25 try: 
26     input = raw_input
27 except NameError: 
28     pass
29
30 # Define all possible option for the compile command :  sat compile <options>
31 parser = src.options.Options()
32 parser.add_option('p', 'products', 'list2', 'products',
33     _('products to configure. This option can be'
34     ' passed several time to configure several products.'))
35 parser.add_option('', 'with_fathers', 'boolean', 'fathers',
36     _("build all necessary products to the given product (KERNEL is build before"
37       " building GUI)."), False)
38 parser.add_option('', 'with_children', 'boolean', 'children',
39     _("build all products using the given product (all SMESH plugins are build "
40       "after SMESH)."), False)
41 parser.add_option('', 'clean_all', 'boolean', 'clean_all',
42     _("clean BUILD dir and INSTALL dir before building product."), False)
43 parser.add_option('', 'clean_install', 'boolean', 'clean_install',
44     _("clean INSTALL dir before building product."), False)
45 parser.add_option('', 'make_flags', 'string', 'makeflags',
46     _("add extra options to the 'make' command."))
47 parser.add_option('', 'show', 'boolean', 'no_compile',
48     _("DO NOT COMPILE just show if products are installed or not."), False)
49 parser.add_option('', 'stop_first_fail', 'boolean', 'stop_first_fail', _("Stop"
50                     "s the command at first product compilation fail."), False)
51
52 def get_products_list(options, cfg, logger):
53     '''method that gives the product list with their informations from 
54        configuration regarding the passed options.
55     
56     :param options Options: The Options instance that stores the commands 
57                             arguments
58     :param cfg Config: The global configuration
59     :param logger Logger: The logger instance to use for the display and 
60                           logging
61     :return: The list of (product name, product_informations).
62     :rtype: List
63     '''
64     # Get the products to be prepared, regarding the options
65     if options.products is None:
66         # No options, get all products sources
67         products = cfg.APPLICATION.products
68     else:
69         # if option --products, check that all products of the command line
70         # are present in the application.
71         products = options.products
72         for p in products:
73             if p not in cfg.APPLICATION.products:
74                 raise src.SatException(_("Product %(product)s "
75                             "not defined in application %(application)s") %
76                         { 'product': p, 'application': cfg.VARS.application} )
77     
78     # Construct the list of tuple containing 
79     # the products name and their definition
80     products_infos = src.product.get_products_infos(products, cfg)
81     
82     products_infos = [pi for pi in products_infos if not(
83                                      src.product.product_is_native(pi[1]) or 
84                                      src.product.product_is_fixed(pi[1]))]
85     
86     return products_infos
87
88 def get_children(config, p_name_p_info):
89     l_res = []
90     p_name, __ = p_name_p_info
91     # Get all products of the application
92     products = config.APPLICATION.products
93     products_infos = src.product.get_products_infos(products, config)
94     for p_name_potential_child, p_info_potential_child in products_infos:
95         if ("depend" in p_info_potential_child and 
96                 p_name in p_info_potential_child.depend):
97             l_res.append(p_name_potential_child)
98     return l_res
99
100 def get_recursive_children(config, p_name_p_info, without_native_fixed=False):
101     """ Get the recursive list of the product that depend on 
102         the product defined by prod_info
103     
104     :param config Config: The global configuration
105     :param prod_info Config: The specific config of the product
106     :param without_native_fixed boolean: If true, do not include the fixed
107                                          or native products in the result
108     :return: The list of product_informations.
109     :rtype: List
110     """
111     p_name, __ = p_name_p_info
112     # Initialization of the resulting list
113     l_children = []
114     
115     # Get the direct children (not recursive)
116     l_direct_children = get_children(config, p_name_p_info)
117     # Minimal case : no child
118     if l_direct_children == []:
119         return []
120     # Add the children and call the function to get the children of the
121     # children
122     for child_name in l_direct_children:
123         l_children_name = [pn_pi[0] for pn_pi in l_children]
124         if child_name not in l_children_name:
125             if child_name not in config.APPLICATION.products:
126                 msg = _("The product %(child_name)s that is in %(product_nam"
127                         "e)s children is not present in application "
128                         "%(appli_name)s" % {"child_name" : child_name, 
129                                     "product_name" : p_name.name, 
130                                     "appli_name" : config.VARS.application})
131                 raise src.SatException(msg)
132             prod_info_child = src.product.get_product_config(config,
133                                                               child_name)
134             pname_pinfo_child = (prod_info_child.name, prod_info_child)
135             # Do not append the child if it is native or fixed and 
136             # the corresponding parameter is called
137             if without_native_fixed:
138                 if not(src.product.product_is_native(prod_info_child) or 
139                        src.product.product_is_fixed(prod_info_child)):
140                     l_children.append(pname_pinfo_child)
141             else:
142                 l_children.append(pname_pinfo_child)
143             # Get the children of the children
144             l_grand_children = get_recursive_children(config,
145                                 pname_pinfo_child,
146                                 without_native_fixed = without_native_fixed)
147             l_children += l_grand_children
148     return l_children
149
150 def get_recursive_fathers(config, p_name_p_info, without_native_fixed=False):
151     """ Get the recursive list of the dependencies of the product defined by
152         prod_info
153     
154     :param config Config: The global configuration
155     :param prod_info Config: The specific config of the product
156     :param without_native_fixed boolean: If true, do not include the fixed
157                                          or native products in the result
158     :return: The list of product_informations.
159     :rtype: List
160     """
161     p_name, p_info = p_name_p_info
162     # Initialization of the resulting list
163     l_fathers = []
164     # Minimal case : no dependencies
165     if "depend" not in p_info or p_info.depend == []:
166         return []
167     # Add the dependencies and call the function to get the dependencies of the
168     # dependencies
169     for father_name in p_info.depend:
170         l_fathers_name = [pn_pi[0] for pn_pi in l_fathers]
171         if father_name not in l_fathers_name:
172             if father_name not in config.APPLICATION.products:
173                 msg = _("The product %(father_name)s that is in %(product_nam"
174                         "e)s dependencies is not present in application "
175                         "%(appli_name)s" % {"father_name" : father_name, 
176                                     "product_name" : p_name, 
177                                     "appli_name" : config.VARS.application})
178                 raise src.SatException(msg)
179             prod_info_father = src.product.get_product_config(config,
180                                                               father_name)
181             pname_pinfo_father = (prod_info_father.name, prod_info_father)
182             # Do not append the father if it is native or fixed and 
183             # the corresponding parameter is called
184             if without_native_fixed:
185                 if not(src.product.product_is_native(prod_info_father) or 
186                        src.product.product_is_fixed(prod_info_father)):
187                     l_fathers.append(pname_pinfo_father)
188             else:
189                 l_fathers.append(pname_pinfo_father)
190             # Get the dependencies of the dependency
191             l_grand_fathers = get_recursive_fathers(config,
192                                 pname_pinfo_father,
193                                 without_native_fixed = without_native_fixed)
194             for item in l_grand_fathers:
195                 if item not in l_fathers:
196                     l_fathers.append(item)
197     return l_fathers
198
199 def sort_products(config, p_infos):
200     """ Sort the p_infos regarding the dependencies between the products
201     
202     :param config Config: The global configuration
203     :param p_infos list: List of (str, Config) => (product_name, product_info)
204     """
205     l_prod_sorted = src.deepcopy_list(p_infos)
206     for prod in p_infos:
207         l_fathers = get_recursive_fathers(config,
208                                           prod,
209                                           without_native_fixed=True)
210         l_fathers = [father for father in l_fathers if father in p_infos]
211         if l_fathers == []:
212             continue
213         for p_sorted in l_prod_sorted:
214             if p_sorted in l_fathers:
215                 l_fathers.remove(p_sorted)
216             if l_fathers==[]:
217                 l_prod_sorted.remove(prod)
218                 l_prod_sorted.insert(l_prod_sorted.index(p_sorted)+1, prod)
219                 break
220         
221     return l_prod_sorted
222
223 def extend_with_fathers(config, p_infos):
224     p_infos_res = src.deepcopy_list(p_infos)
225     for p_name_p_info in p_infos:
226         fathers = get_recursive_fathers(config,
227                                         p_name_p_info,
228                                         without_native_fixed=True)
229         for p_name_p_info_father in fathers:
230             if p_name_p_info_father not in p_infos_res:
231                 p_infos_res.append(p_name_p_info_father)
232     return p_infos_res
233
234 def extend_with_children(config, p_infos):
235     p_infos_res = src.deepcopy_list(p_infos)
236     for p_name_p_info in p_infos:
237         children = get_recursive_children(config,
238                                         p_name_p_info,
239                                         without_native_fixed=True)
240         for p_name_p_info_child in children:
241             if p_name_p_info_child not in p_infos_res:
242                 p_infos_res.append(p_name_p_info_child)
243     return p_infos_res    
244
245 def check_dependencies(config, p_name_p_info):
246     l_depends_not_installed = []
247     fathers = get_recursive_fathers(config, p_name_p_info, without_native_fixed=True)
248     for p_name_father, p_info_father in fathers:
249         if not(src.product.check_installation(p_info_father)):
250             l_depends_not_installed.append(p_name_father)
251     return l_depends_not_installed
252
253 def log_step(logger, header, step):
254     logger.write("\r%s%s" % (header, " " * 30), 3)
255     logger.write("\r%s%s" % (header, step), 3)
256     logger.write("\n==== %s \n" % src.printcolors.printcInfo(step), 4)
257     logger.flush()
258
259 def log_res_step(logger, res):
260     if res == 0:
261         logger.write("%s \n" % src.printcolors.printcSuccess("OK"), 4)
262         logger.flush()
263     else:
264         logger.write("%s \n" % src.printcolors.printcError("KO"), 4)
265         logger.flush()
266
267 def compile_all_products(sat, config, options, products_infos, logger):
268     '''Execute the proper configuration commands 
269        in each product build directory.
270
271     :param config Config: The global configuration
272     :param products_info list: List of 
273                                  (str, Config) => (product_name, product_info)
274     :param logger Logger: The logger instance to use for the display and logging
275     :return: the number of failing commands.
276     :rtype: int
277     '''
278     res = 0
279     for p_name_info in products_infos:
280         
281         p_name, p_info = p_name_info
282         
283         # Logging
284         len_end_line = 30
285         logger.write("\n", 4, False)
286         logger.write("################ ", 4)
287         header = _("Compilation of %s") % src.printcolors.printcLabel(p_name)
288         header += " %s " % ("." * (len_end_line - len(p_name)))
289         logger.write(header, 3)
290         logger.write("\n", 4, False)
291         logger.flush()
292
293         # Do nothing if he product is not compilable
294         if ("properties" in p_info and "compilation" in p_info.properties and 
295                                             p_info.properties.compilation == "no"):
296             log_step(logger, header, "ignored")
297             logger.write("\n", 3, False)
298             continue
299
300         # Clean the build and the install directories 
301         # if the corresponding options was called
302         if options.clean_all:
303             log_step(logger, header, "CLEAN BUILD AND INSTALL")
304             sat.clean(config.VARS.application + 
305                       " --products " + p_name + 
306                       " --build --install", batch=True, verbose=0)
307         
308         # Clean the the install directory 
309         # if the corresponding option was called
310         if options.clean_install and not options.clean_all:
311             log_step(logger, header, "CLEAN INSTALL")
312             sat.clean(config.VARS.application + 
313                       " --products " + p_name + 
314                       " --install", batch=True, verbose=0)
315         
316         # Check if it was already successfully installed
317         if src.product.check_installation(p_info):
318             logger.write(_("Already installed\n"))
319             continue
320         
321         # If the show option was called, do not launch the compilation
322         if options.no_compile:
323             logger.write(_("Not installed\n"))
324             continue
325         
326         # Check if the dependencies are installed
327         l_depends_not_installed = check_dependencies(config, p_name_info)
328         if len(l_depends_not_installed) > 0:
329             logger.write(src.printcolors.printcError(
330                     _("ERROR : the following product(s) is(are) mandatory: ")))
331             for prod_name in l_depends_not_installed:
332                 logger.write(src.printcolors.printcError(prod_name + " "))
333             logger.write("\n")
334             continue
335         
336         # Call the function to compile the product
337         res_prod, len_end_line, error_step = compile_product(sat,
338                                                              p_name_info,
339                                                              config,
340                                                              options,
341                                                              logger,
342                                                              header,
343                                                              len_end_line)
344         
345         if res_prod != 0:
346             # Clean the install directory if there is any
347             sat.clean(config.VARS.application + 
348                       " --products " + p_name + 
349                       " --install", batch=True, verbose=0)
350             res += 1
351             
352         # Log the result
353         if res_prod > 0:
354             logger.write("\r%s%s" % (header, " " * len_end_line), 3)
355             logger.write("\r" + header + src.printcolors.printcError("KO ") + error_step)
356             logger.write("\n==== %(KO)s in compile of %(name)s \n" %
357                 { "name" : p_name , "KO" : src.printcolors.printcInfo("ERROR")}, 4)
358             logger.flush()
359         else:
360             logger.write("\r%s%s" % (header, " " * len_end_line), 3)
361             logger.write("\r" + header + src.printcolors.printcSuccess("OK"))
362             logger.write(_("\nINSTALL directory = %s" % 
363                            src.printcolors.printcInfo(p_info.install_dir)), 3)
364             logger.write("\n==== %s \n" % src.printcolors.printcInfo("OK"), 4)
365             logger.write("\n==== Compilation of %(name)s %(OK)s \n" %
366                 { "name" : p_name , "OK" : src.printcolors.printcInfo("OK")}, 4)
367             logger.flush()
368         logger.write("\n", 3, False)
369         
370         
371         if res_prod != 0 and options.stop_first_fail:
372             break
373         
374     return res
375
376 def compile_product(sat, p_name_info, config, options, logger, header, len_end):
377     '''Execute the proper configuration command(s) 
378        in the product build directory.
379     
380     :param p_name_info tuple: (str, Config) => (product_name, product_info)
381     :param config Config: The global configuration
382     :param logger Logger: The logger instance to use for the display 
383                           and logging
384     :return: 1 if it fails, else 0.
385     :rtype: int
386     '''
387     
388     p_name, p_info = p_name_info
389        
390     # Execute "sat configure", "sat make" and "sat install"
391     res = 0
392     error_step = ""
393     
394     # Logging and sat command call for configure step
395     len_end_line = len_end
396     log_step(logger, header, "CONFIGURE")
397     res_c = sat.configure(config.VARS.application + " --products " + p_name,
398                           verbose = 0,
399                           logger_add_link = logger)
400     log_res_step(logger, res_c)
401     res += res_c
402     
403     if res_c > 0:
404         error_step = "CONFIGURE"
405     else:    
406         # Logging and sat command call for make step
407         # Logging take account of the fact that the product has a compilation 
408         # script or not
409         if src.product.product_has_script(p_info):
410             # if the product has a compilation script, 
411             # it is executed during make step
412             scrit_path_display = src.printcolors.printcLabel(
413                                                         p_info.compil_script)
414             log_step(logger, header, "SCRIPT " + scrit_path_display)
415             len_end_line = len(scrit_path_display)
416         else:
417             log_step(logger, header, "MAKE")
418         make_arguments = config.VARS.application + " --products " + p_name
419         # Get the make_flags option if there is any
420         if options.makeflags:
421             make_arguments += " --option -j" + options.makeflags
422         res_m = sat.make(make_arguments,
423                          verbose = 0,
424                          logger_add_link = logger)
425         log_res_step(logger, res_m)
426         res += res_m
427         
428         if res_m > 0:
429             error_step = "MAKE"
430         else: 
431             # Logging and sat command call for make install step
432             log_step(logger, header, "MAKE INSTALL")
433             res_mi = sat.makeinstall(config.VARS.application + 
434                                      " --products " + 
435                                      p_name,
436                                     verbose = 0,
437                                     logger_add_link = logger)
438
439             log_res_step(logger, res_mi)
440             res += res_mi
441             
442             if res_mi > 0:
443                 error_step = "MAKE INSTALL"
444     
445     # Add the config file corresponding to the dependencies/versions of the 
446     # product that have been successfully compiled
447     if res==0:
448         logger.write(_("Add the config file in installation directory\n"), 5)
449         add_compile_config_file(p_info, config)
450     
451     return res, len_end_line, error_step
452
453 def add_compile_config_file(p_info, config):
454     '''Execute the proper configuration command(s) 
455        in the product build directory.
456     
457     :param p_info Config: The specific config of the product
458     :param config Config: The global configuration
459     '''
460     # Create the compile config
461     compile_cfg = src.pyconf.Config()
462     for prod_name in p_info.depend:
463         if prod_name not in compile_cfg:
464             compile_cfg.addMapping(prod_name,
465                                    src.pyconf.Mapping(compile_cfg),
466                                    "")
467         prod_dep_info = src.product.get_product_config(config, prod_name, False)
468         compile_cfg[prod_name] = prod_dep_info.version
469     # Write it in the install directory of the product
470     compile_cfg_path = os.path.join(p_info.install_dir, src.CONFIG_FILENAME)
471     f = open(compile_cfg_path, 'w')
472     compile_cfg.__save__(f)
473     f.close()
474     
475 def description():
476     '''method that is called when salomeTools is called with --help option.
477     
478     :return: The text to display for the compile command description.
479     :rtype: str
480     '''
481     return _("The compile command constructs the products of the application")
482   
483 def run(args, runner, logger):
484     '''method that is called when salomeTools is called with compile parameter.
485     '''
486     
487     # Parse the options
488     (options, args) = parser.parse_args(args)
489
490     # Warn the user if he invoked the clean_all option 
491     # without --products option
492     if (options.clean_all and 
493         options.products is None and 
494         not runner.options.batch):
495         rep = input(_("You used --clean_all without specifying a product"
496                           " are you sure you want to continue? [Yes/No] "))
497         if rep.upper() != _("YES").upper():
498             return 0
499         
500     # check that the command has been called with an application
501     src.check_config_has_application( runner.cfg )
502
503     # Get the list of products to treat
504     products_infos = get_products_list(options, runner.cfg, logger)
505
506     if options.fathers:
507         # Extend the list with all recursive dependencies of the given products
508         products_infos = extend_with_fathers(runner.cfg, products_infos)
509
510     if options.children:
511         # Extend the list with all products that use the given products
512         products_infos = extend_with_children(runner.cfg, products_infos)
513
514     # Sort the list regarding the dependencies of the products
515     products_infos = sort_products(runner.cfg, products_infos)
516
517     # Print some informations
518     logger.write(_('Executing the compile commands in the build '
519                                 'directories of the products of '
520                                 'the application %s\n') % 
521                 src.printcolors.printcLabel(runner.cfg.VARS.application), 1)
522     
523     info = [
524             (_("SOURCE directory"),
525              os.path.join(runner.cfg.APPLICATION.workdir, 'SOURCES')),
526             (_("BUILD directory"),
527              os.path.join(runner.cfg.APPLICATION.workdir, 'BUILD'))
528             ]
529     src.print_info(logger, info)
530     
531     # Call the function that will loop over all the products and execute
532     # the right command(s)
533     res = compile_all_products(runner, runner.cfg, options, products_infos, logger)
534     
535     # Print the final state
536     nb_products = len(products_infos)
537     if res == 0:
538         final_status = "OK"
539     else:
540         final_status = "KO"
541    
542     logger.write(_("\nCompilation: %(status)s (%(valid_result)d/%(nb_products)d)\n") % \
543         { 'status': src.printcolors.printc(final_status), 
544           'valid_result': nb_products - res,
545           'nb_products': nb_products }, 1)    
546     
547     code = res
548     if code != 0:
549         code = 1
550     return code