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