Salome HOME
Add the script command, change the compile command in order to take the script comman...
[tools/sat.git] / commands / script.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 import re
21
22 import src
23
24 # Define all possible option for the script command :  sat script <options>
25 parser = src.options.Options()
26 parser.add_option('p', 'products', 'list2', 'products',
27     _('Optional: products to configure. This option can be'
28     ' passed several time to configure several products.'))
29 parser.add_option('', 'nb_proc', 'int', 'nb_proc',
30     _('Optional: The number of processors to use in the script if the make '
31       'command is used in it.\n\tWarning: the script has to be correctly written '
32       'if you want this option to work.\n\tThe $MAKE_OPTIONS has to be '
33       'used.'), "")
34
35 def get_products_list(options, cfg, logger):
36     '''method that gives the product list with their informations from 
37        configuration regarding the passed options.
38     
39     :param options Options: The Options instance that stores the commands 
40                             arguments
41     :param cfg Config: The global configuration
42     :param logger Logger: The logger instance to use for the display and 
43                           logging
44     :return: The list of (product name, product_informations).
45     :rtype: List
46     '''
47     # Get the products to be prepared, regarding the options
48     if options.products is None:
49         # No options, get all products sources
50         products = cfg.APPLICATION.products
51     else:
52         # if option --products, check that all products of the command line
53         # are present in the application.
54         products = options.products
55         for p in products:
56             if p not in cfg.APPLICATION.products:
57                 raise src.SatException(_("Product %(product)s "
58                             "not defined in application %(application)s") %
59                         { 'product': p, 'application': cfg.VARS.application} )
60     
61     # Construct the list of tuple containing 
62     # the products name and their definition
63     products_infos = src.product.get_products_infos(products, cfg)
64     
65     products_infos = [pi for pi in products_infos if not(
66                                      src.product.product_is_native(pi[1]) or 
67                                      src.product.product_is_fixed(pi[1]))]
68     
69     return products_infos
70
71 def log_step(logger, header, step):
72     logger.write("\r%s%s" % (header, " " * 20), 3)
73     logger.write("\r%s%s" % (header, step), 3)
74     logger.write("\n==== %s \n" % src.printcolors.printcInfo(step), 4)
75     logger.flush()
76
77 def log_res_step(logger, res):
78     if res == 0:
79         logger.write("%s \n" % src.printcolors.printcSuccess("OK"), 4)
80         logger.flush()
81     else:
82         logger.write("%s \n" % src.printcolors.printcError("KO"), 4)
83         logger.flush()
84
85 def run_script_all_products(config, products_infos, nb_proc, logger):
86     '''Execute the script in each product build directory.
87
88     :param config Config: The global configuration
89     :param products_info list: List of 
90                                  (str, Config) => (product_name, product_info)
91     :param nb_proc int: The number of processors to use
92     :param logger Logger: The logger instance to use for the display and logging
93     :return: the number of failing commands.
94     :rtype: int
95     '''
96     res = 0
97     for p_name_info in products_infos:
98         res_prod = run_script_of_product(p_name_info,
99                                       nb_proc,
100                                       config,
101                                       logger)
102         if res_prod != 0:
103             res += 1 
104     return res
105
106 def run_script_of_product(p_name_info, nb_proc, config, logger):
107     '''Execute the proper configuration command(s) 
108        in the product build directory.
109     
110     :param p_name_info tuple: (str, Config) => (product_name, product_info)
111     :param nb_proc int: The number of processors to use
112     :param config Config: The global configuration
113     :param logger Logger: The logger instance to use for the display 
114                           and logging
115     :return: 1 if it fails, else 0.
116     :rtype: int
117     '''
118     
119     p_name, p_info = p_name_info
120     
121     # Logging
122     logger.write("\n", 4, False)
123     logger.write("################ ", 4)
124     header = _("Running script of %s") % src.printcolors.printcLabel(p_name)
125     header += " %s " % ("." * (20 - len(p_name)))
126     logger.write(header, 3)
127     logger.write("\n", 4, False)
128     logger.flush()
129
130     # Do nothing if he product is not compilable or has no compilation script
131     if (("properties" in p_info and "compilation" in p_info.properties and 
132                                   p_info.properties.compilation == "no") or
133                                   (not src.product.product_has_script(p_info))):
134         log_step(logger, header, "ignored")
135         logger.write("\n", 3, False)
136         return 0
137
138     # Instantiate the class that manages all the construction commands
139     # like cmake, make, make install, make test, environment management, etc...
140     builder = src.compilation.Builder(config, logger, p_info)
141     
142     # Prepare the environment
143     log_step(logger, header, "PREPARE ENV")
144     res_prepare = builder.prepare()
145     log_res_step(logger, res_prepare)
146     
147     # Execute the script
148     len_end_line = 20
149     script_path_display = src.printcolors.printcLabel(p_info.compil_script)
150     log_step(logger, header, "SCRIPT " + script_path_display)
151     len_end_line += len(script_path_display)
152     res = builder.do_script_build(p_info.compil_script, number_of_proc=nb_proc)
153     log_res_step(logger, res)
154     
155     # Log the result
156     if res > 0:
157         logger.write("\r%s%s" % (header, " " * len_end_line), 3)
158         logger.write("\r" + header + src.printcolors.printcError("KO"))
159         logger.write("==== %(KO)s in script execution of %(name)s \n" %
160             { "name" : p_name , "KO" : src.printcolors.printcInfo("ERROR")}, 4)
161         logger.flush()
162     else:
163         logger.write("\r%s%s" % (header, " " * len_end_line), 3)
164         logger.write("\r" + header + src.printcolors.printcSuccess("OK"))
165         logger.write("==== %s \n" % src.printcolors.printcInfo("OK"), 4)
166         logger.write("==== Script execution of %(name)s %(OK)s \n" %
167             { "name" : p_name , "OK" : src.printcolors.printcInfo("OK")}, 4)
168         logger.flush()
169     logger.write("\n", 3, False)
170
171     return res
172
173 def description():
174     '''method that is called when salomeTools is called with --help option.
175     
176     :return: The text to display for the script command description.
177     :rtype: str
178     '''
179     return _("The script command executes the script(s) of the the given "
180              "products in the build directory.\nThis is done only for the "
181              "products that are constructed using a script (build_source "
182              ": \"script\").\nOtherwise, nothing is done."
183              "\n\nexample:\nsat script SALOME-master --products Python,numpy")
184   
185 def run(args, runner, logger):
186     '''method that is called when salomeTools is called with make parameter.
187     '''
188     
189     # Parse the options
190     (options, args) = parser.parse_args(args)
191
192     # check that the command has been called with an application
193     src.check_config_has_application( runner.cfg )
194
195     # Get the list of products to treat
196     products_infos = get_products_list(options, runner.cfg, logger)
197     
198     # Print some informations
199     logger.write(_('Executing the script in the build '
200                                 'directories of the application %s\n') % 
201                 src.printcolors.printcLabel(runner.cfg.VARS.application), 1)
202     
203     info = [(_("BUILD directory"),
204              os.path.join(runner.cfg.APPLICATION.workdir, 'BUILD'))]
205     src.print_info(logger, info)
206     
207     # Call the function that will loop over all the products and execute
208     # the right command(s)
209     if options.nb_proc is None:
210         options.nb_proc = 0
211     res = run_script_all_products(runner.cfg,
212                                   products_infos,
213                                   options.nb_proc,
214                                   logger)
215     
216     # Print the final state
217     nb_products = len(products_infos)
218     if res == 0:
219         final_status = "OK"
220     else:
221         final_status = "KO"
222    
223     logger.write(_("\nScript: %(status)s "
224                    "(%(valid_result)d/%(nb_products)d)\n") % \
225         { 'status': src.printcolors.printc(final_status), 
226           'valid_result': nb_products - res,
227           'nb_products': nb_products }, 1)    
228     
229     return res