Salome HOME
sat #29553 : integrate patch provided by Emilio on Forum, to correct an error on...
[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 import re
21 import subprocess
22 import src
23 import src.debug as DBG
24
25 # Compatibility python 2/3 for input function
26 # input stays input for python 3 and input = raw_input for python 2
27 try: 
28     input = raw_input
29 except NameError: 
30     pass
31
32
33 # Define all possible option for the compile command :  sat compile <options>
34 parser = src.options.Options()
35 parser.add_option('p', 'products', 'list2', 'products',
36     _('Optional: products to compile. This option accepts a comma separated list.'))
37 parser.add_option('f', 'force', 'boolean', 'force',
38     'Optional: force the compilation of product, even if it is already installed. The BUILD directory is cleaned before compilation.')
39 parser.add_option('u', 'update', 'boolean', 'update',
40     'Optional: update mode, compile only products which sources has changed, including the dependencies.')
41 parser.add_option('', 'with_fathers', 'boolean', 'fathers',
42     _("Optional: build all necessary products to the given product (KERNEL is "
43       "build before building GUI)."), False)
44 parser.add_option('', 'with_children', 'boolean', 'children',
45     _("Optional: build all products using the given product (all SMESH plugins"
46       " are build after SMESH)."), False)
47 parser.add_option('', 'clean_all', 'boolean', 'clean_all',
48     _("Optional: clean BUILD dir and INSTALL dir before building product."),
49     False)
50 parser.add_option('', 'clean_install', 'boolean', 'clean_install',
51     _("Optional: clean INSTALL dir before building product."), False)
52 parser.add_option('', 'make_flags', 'string', 'makeflags',
53     _("Optional: add extra options to the 'make' command."))
54 parser.add_option('', 'show', 'boolean', 'no_compile',
55     _("Optional: DO NOT COMPILE just show if products are installed or not."),
56     False)
57 parser.add_option('', 'stop_first_fail', 'boolean', 'stop_first_fail', _(
58                   "Optional: Stops the command at first product compilation"
59                   " fail."), False)
60 parser.add_option('', 'check', 'boolean', 'check', _(
61                   "Optional: execute the unit tests after compilation"), False)
62
63 parser.add_option('', 'clean_build_after', 'boolean', 'clean_build_after', 
64                   _('Optional: remove the build directory after successful compilation'), False)
65
66
67 # from sat product infos, represent the product dependencies in a simple python graph
68 # keys are nodes, the list of dependencies are values
69 def get_dependencies_graph(p_infos, compile_time=True):
70     graph={}
71     for (p_name,p_info) in p_infos:
72         depprod=[]
73         for d in p_info.depend:
74             depprod.append(d)
75         if compile_time and "build_depend" in p_info:
76             for d in p_info.build_depend:
77                 depprod.append(d)
78         graph[p_name]=depprod
79     return graph
80
81 # this recursive function calculates all the dependencies of node start
82 def depth_search_graph(graph, start, visited=[]):
83     visited= visited+ [start]
84     for node in graph[start]:  # for all nodes in start dependencies
85         if node not in visited:
86             visited=depth_search_graph(graph, node, visited)
87     return visited
88
89 # find a path from start node to end (a group of nodes)
90 def find_path_graph(graph, start, end, path=[]):
91     path = path + [start]
92     if start in end:
93         return path
94     if start not in graph:
95         return None
96     for node in graph[start]:
97         if node not in path:
98             newpath = find_path_graph(graph, node, end, path)
99             if newpath: return newpath
100     return None
101
102 # Topological sorting algo
103 # return in sorted_nodes the list of sorted nodes
104 def depth_first_topo_graph(graph, start, visited=[], sorted_nodes=[]):
105     visited = visited + [start]
106     if start not in graph:
107         # get more explicit error
108         where = [k for k in graph if start in graph[k]]
109         raise src.SatException('Error in product dependencies : %s product is referenced in products dependencies, but is not present in the application, from %s' % (start, where))
110         # may be in debug mode, continue loop to get all problems, (if comment raise)
111         # print("WARNING : %s product is referenced in products dependencies but is not present in the application, from %s" % (start, where))
112         # sorted_nodes = sorted_nodes + [start]
113         # return visited, sorted_nodes
114     for node in graph[start]:
115         if node not in visited:
116             visited,sorted_nodes=depth_first_topo_graph(graph, node, visited,sorted_nodes)
117         else:
118             if node not in sorted_nodes:
119                 raise src.SatException('Error in product dependencies : cycle detection for node %s and %s' % (start,node))
120     
121     sorted_nodes = sorted_nodes + [start]
122     return visited, sorted_nodes
123
124
125 # check for p_name that all dependencies are installed
126 def check_dependencies(config, p_name_p_info, all_products_dict):
127     l_depends_not_installed = []
128     for prod in p_name_p_info[1]["depend_all"]:
129         # for each dependency, check the install
130         prod_name, prod_info=all_products_dict[prod]
131         if not(src.product.check_installation(config, prod_info)):
132             l_depends_not_installed.append(prod_name)
133     return l_depends_not_installed   # non installed deps
134
135 def log_step(logger, header, step):
136     logger.write("\r%s%s" % (header, " " * 30), 3)
137     logger.write("\r%s%s" % (header, step), 3)
138     logger.flush()
139
140 def log_res_step(logger, res):
141     if res == 0:
142         logger.write("%s \n" % src.printcolors.printcSuccess("OK"), 4)
143         logger.flush()
144     else:
145         logger.write("%s \n" % src.printcolors.printcError("KO"), 4)
146         logger.flush()
147
148 def compile_all_products(sat, config, options, products_infos, all_products_dict, all_products_graph, logger):
149     '''Execute the proper configuration commands 
150        in each product build directory.
151
152     :param config Config: The global configuration
153     :param products_info list: List of 
154                                  (str, Config) => (product_name, product_info)
155     :param all_products_dict: Dict of all products 
156     :param all_products_graph: graph of all products 
157     :param logger Logger: The logger instance to use for the display and logging
158     :return: the number of failing commands.
159     :rtype: int
160     '''
161     # first loop for the cleaning 
162     check_salome_configuration=False
163     updated_products=[]
164     for p_name_info in products_infos:
165         
166         p_name, p_info = p_name_info
167         if src.product.product_is_salome(p_info):
168             check_salome_configuration=True
169         
170         # nothing to clean for native or fixed products
171         if (not src.product.product_compiles(p_info)) or\
172            src.product.product_is_native(p_info) or\
173            src.product.product_is_fixed(p_info):
174             continue
175
176         # Clean the build and the install directories 
177         # if the corresponding options was called
178         if options.clean_all:
179             sat.clean(config.VARS.application + 
180                       " --products " + p_name + 
181                       " --build --install",
182                       batch=True,
183                       verbose=0,
184                       logger_add_link = logger)
185
186         else:
187             # Clean the the install directory 
188             # if the corresponding option was called
189             if options.clean_install:
190                 sat.clean(config.VARS.application + 
191                           " --products " + p_name + 
192                           " --install",
193                           batch=True,
194                           verbose=0,
195                           logger_add_link = logger)
196             
197             # Clean the the install directory 
198             # if the corresponding option was called
199             if options.force:
200                 sat.clean(config.VARS.application + 
201                           " --products " + p_name + 
202                           " --build",
203                           batch=True,
204                           verbose=0,
205                           logger_add_link = logger)
206
207             if options.update and src.product.product_is_vcs(p_info):
208             # only VCS products are concerned by update option
209                 try: 
210                     do_update=False
211                     if len(updated_products)>0:
212                         # if other products where updated, check that the current product is a child 
213                         # in this case it will be also updated
214                         if find_path_graph(all_products_graph, p_name, updated_products):
215                             logger.write("\nUpdate product %s (child)" % p_name, 5)
216                             do_update=True
217                     if (not do_update) and os.path.isdir(p_info.source_dir) \
218                                        and os.path.isdir(p_info.install_dir):
219                         source_time=os.path.getmtime(p_info.source_dir)
220                         install_time=os.path.getmtime(p_info.install_dir)
221                         if install_time<source_time:
222                             logger.write("\nupdate product %s" % p_name, 5)
223                             do_update=True
224                     if do_update:
225                         updated_products.append(p_name) 
226                         sat.clean(config.VARS.application + 
227                                   " --products " + p_name + 
228                                   " --build --install",
229                                   batch=True,
230                                   verbose=0,
231                                   logger_add_link = logger)
232                 except:
233                     pass
234
235     if check_salome_configuration:
236         # For salome applications, we check if the sources of configuration modules are present
237         # configuration modules have the property "configure_dependency"
238         # they are implicit prerequisites of the compilation.
239         res=0
240
241         # get the list of all modules in application 
242         all_products_infos = src.product.get_products_infos(config.APPLICATION.products,
243                                                             config)
244         check_source = True
245         # for configuration modules, check if sources are present
246         for prod in all_products_dict:
247             product_name, product_info = all_products_dict[prod]
248             if ("properties" in product_info and
249                 "configure_dependency" in product_info.properties and
250                 product_info.properties.configure_dependency == "yes"):
251                 check_source = check_source and src.product.check_source(product_info)
252                 if not check_source:
253                     logger.write(_("\nERROR : SOURCES of %s not found! It is required for" 
254                                    " the configuration\n" % product_name))
255                     logger.write(_("        Get it with the command : sat prepare %s -p %s \n" % 
256                                   (config.APPLICATION.name, product_name)))
257                     res += 1
258         if res>0:
259             return res  # error configure dependency : we stop the compilation
260
261     # second loop to compile
262     res = 0
263     for p_name_info in products_infos:
264         
265         p_name, p_info = p_name_info
266         
267         # Logging
268         len_end_line = 30
269         header = _("Compilation of %s") % src.printcolors.printcLabel(p_name)
270         header += " %s " % ("." * (len_end_line - len(p_name)))
271         logger.write(header, 3)
272         logger.flush()
273
274         # Do nothing if the product is not compilable
275         if not src.product.product_compiles(p_info):
276             log_step(logger, header, "ignored")
277             logger.write("\n", 3, False)
278             continue
279
280         # Do nothing if the product is native
281         if src.product.product_is_native(p_info):
282             log_step(logger, header, "native")
283             logger.write("\n", 3, False)
284             continue
285
286         # Do nothing if the product is fixed (already compiled by third party)
287         if src.product.product_is_fixed(p_info):
288             log_step(logger, header, "native")
289             logger.write("\n", 3, False)
290             continue
291
292
293         # Recompute the product information to get the right install_dir
294         # (it could change if there is a clean of the install directory)
295         p_info = src.product.get_product_config(config, p_name)
296         
297         # Check if sources was already successfully installed
298         check_source = src.product.check_source(p_info)
299         is_pip= (src.appli_test_property(config,"pip", "yes") and src.product.product_test_property(p_info,"pip", "yes"))
300         # don't check sources with option --show 
301         # or for products managed by pip (there sources are in wheels stored in LOCAL.ARCHIVE
302         if not (options.no_compile or is_pip): 
303             if not check_source:
304                 logger.write(_("Sources of product not found (try 'sat -h prepare') \n"))
305                 res += 1 # one more error
306                 continue
307         
308         # if we don't force compilation, check if the was already successfully installed.
309         # we don't compile in this case.
310         if (not options.force) and src.product.check_installation(config, p_info):
311             logger.write(_("Already installed"))
312             logger.write(_(" in %s" % p_info.install_dir), 4)
313             logger.write(_("\n"))
314             continue
315         
316         # If the show option was called, do not launch the compilation
317         if options.no_compile:
318             logger.write(_("Not installed in %s\n" % p_info.install_dir))
319             continue
320         
321         # Check if the dependencies are installed
322         l_depends_not_installed = check_dependencies(config, p_name_info, all_products_dict)
323         if len(l_depends_not_installed) > 0:
324             log_step(logger, header, "")
325             logger.write(src.printcolors.printcError(
326                     _("ERROR : the following mandatory product(s) is(are) not installed: ")))
327             for prod_name in l_depends_not_installed:
328                 logger.write(src.printcolors.printcError(prod_name + " "))
329             logger.write("\n")
330             continue
331         
332         # Call the function to compile the product
333         res_prod, len_end_line, error_step = compile_product(
334              sat, p_name_info, config, options, logger, header, len_end_line)
335         
336         if res_prod != 0:
337             res += 1
338             # there was an error, we clean install dir, unless :
339             #  - the error step is "check", or
340             #  - the product is managed by pip and installed in python dir
341             do_not_clean_install=False
342             is_single_dir=(src.appli_test_property(config,"single_install_dir", "yes") and \
343                            src.product.product_test_property(p_info,"single_install_dir", "yes"))
344               
345             if (error_step == "CHECK") or (is_pip and src.appli_test_property(config,"pip_install_dir", "python")) or is_single_dir  :
346                 # cases for which we do not want to remove install dir
347                 #   for is_single_dir and is_pip, the test to determine if the product is already 
348                 #   compiled is based on configuration file, not the directory
349                 do_not_clean_install=True 
350
351             if not do_not_clean_install:
352                 # Clean the install directory if there is any
353                 logger.write(_(
354                             "Cleaning the install directory if there is any\n"),
355                              5)
356                 sat.clean(config.VARS.application + 
357                           " --products " + p_name + 
358                           " --install",
359                           batch=True,
360                           verbose=0,
361                           logger_add_link = logger)
362         else:
363             # Clean the build directory if the compilation and tests succeed
364             if options.clean_build_after:
365                 log_step(logger, header, "CLEAN BUILD")
366                 sat.clean(config.VARS.application + 
367                           " --products " + p_name + 
368                           " --build",
369                           batch=True,
370                           verbose=0,
371                           logger_add_link = logger)
372
373         # Log the result
374         if res_prod > 0:
375             logger.write("\r%s%s" % (header, " " * len_end_line), 3)
376             logger.write("\r" + header + src.printcolors.printcError("KO ") + error_step)
377             logger.write("\n==== %(KO)s in compile of %(name)s \n" %
378                 { "name" : p_name , "KO" : src.printcolors.printcInfo("ERROR")}, 4)
379             if error_step == "CHECK":
380                 logger.write(_("\nINSTALL directory = %s" % 
381                            src.printcolors.printcInfo(p_info.install_dir)), 3)
382             logger.flush()
383         else:
384             logger.write("\r%s%s" % (header, " " * len_end_line), 3)
385             logger.write("\r" + header + src.printcolors.printcSuccess("OK"))
386             logger.write(_("\nINSTALL directory = %s" % 
387                            src.printcolors.printcInfo(p_info.install_dir)), 3)
388             logger.write("\n==== %s \n" % src.printcolors.printcInfo("OK"), 4)
389             logger.write("\n==== Compilation of %(name)s %(OK)s \n" %
390                 { "name" : p_name , "OK" : src.printcolors.printcInfo("OK")}, 4)
391             logger.flush()
392         logger.write("\n", 3, False)
393         
394         
395         if res_prod != 0 and options.stop_first_fail:
396             break
397         
398     return res
399
400 def compile_product(sat, p_name_info, config, options, logger, header, len_end):
401     '''Execute the proper configuration command(s) 
402        in the product build directory.
403     
404     :param p_name_info tuple: (str, Config) => (product_name, product_info)
405     :param config Config: The global configuration
406     :param logger Logger: The logger instance to use for the display 
407                           and logging
408     :param header Str: the header to display when logging
409     :param len_end Int: the lenght of the the end of line (used in display)
410     :return: 1 if it fails, else 0.
411     :rtype: int
412     '''
413     
414     p_name, p_info = p_name_info
415           
416     # Get the build procedure from the product configuration.
417     # It can be :
418     # build_sources : autotools -> build_configure, configure, make, make install
419     # build_sources : cmake     -> cmake, make, make install
420     # build_sources : script    -> script executions
421     res = 0
422
423     
424     # check if pip should be used : the application and product have pip property
425     if (src.appli_test_property(config,"pip", "yes") and 
426        src.product.product_test_property(p_info,"pip", "yes")):
427             res, len_end_line, error_step = compile_product_pip(sat,
428                                                                 p_name_info,
429                                                                 config,
430                                                                 options,
431                                                                 logger,
432                                                                 header,
433                                                                 len_end)
434     else:
435         if (src.product.product_is_autotools(p_info) or 
436                                               src.product.product_is_cmake(p_info)):
437             res, len_end_line, error_step = compile_product_cmake_autotools(sat,
438                                                                       p_name_info,
439                                                                       config,
440                                                                       options,
441                                                                       logger,
442                                                                       header,
443                                                                       len_end)
444         if src.product.product_has_script(p_info):
445             res, len_end_line, error_step = compile_product_script(sat,
446                                                                    p_name_info,
447                                                                    config,
448                                                                    options,
449                                                                    logger,
450                                                                    header,
451                                                                    len_end)
452
453     # Check that the install directory exists
454     if res==0 and not(os.path.exists(p_info.install_dir)):
455         res = 1
456         error_step = "NO INSTALL DIR"
457         msg = _("Error: despite the fact that all the steps ended successfully,"
458                 " no install directory was found !")
459         logger.write(src.printcolors.printcError(msg), 4)
460         logger.write("\n", 4)
461         return res, len_end, error_step
462     
463     # Add the config file corresponding to the dependencies/versions of the 
464     # product that have been successfully compiled
465     if res==0:       
466         logger.write(_("Add the config file in installation directory\n"), 5)
467         src.product.add_compile_config_file(p_info, config)
468         
469         if options.check:
470             # Do the unit tests (call the check command)
471             log_step(logger, header, "CHECK")
472             res_check = sat.check(
473                               config.VARS.application + " --products " + p_name,
474                               verbose = 0,
475                               logger_add_link = logger)
476             if res_check != 0:
477                 error_step = "CHECK"
478                 
479             res += res_check
480     
481     return res, len_end_line, error_step
482
483
484 def compile_product_pip(sat,
485                         p_name_info,
486                         config,
487                         options,
488                         logger,
489                         header,
490                         len_end):
491     '''Execute the proper build procedure for pip products
492     :param p_name_info tuple: (str, Config) => (product_name, product_info)
493     :param config Config: The global configuration
494     :param logger Logger: The logger instance to use for the display 
495                           and logging
496     :param header Str: the header to display when logging
497     :param len_end Int: the lenght of the the end of line (used in display)
498     :return: 1 if it fails, else 0.
499     :rtype: int
500     '''
501     # pip needs openssl-dev. If openssl is declared in the application, we check it!
502     if "openssl" in config.APPLICATION.products:
503         openssl_cfg = src.product.get_product_config(config, "openssl")
504         if not src.product.check_installation(config, openssl_cfg):
505             raise src.SatException(_("please install system openssl development package, it is required for products managed by pip."))
506     # a) initialisation
507     p_name, p_info = p_name_info
508     res = 0
509     error_step = ""
510     pip_install_in_python=False
511     pip_wheels_dir=os.path.join(config.LOCAL.archive_dir,"wheels")
512     pip_install_cmd=config.INTERNAL.command.pip_install # parametrized in src/internal
513
514     # b) get the build environment (useful to get the installed python & pip3)
515     build_environ = src.environment.SalomeEnviron(config,
516                              src.environment.Environ(dict(os.environ)),
517                              True)
518     environ_info = src.product.get_product_dependencies(config,
519                                                         p_name,
520                                                         p_info)
521     build_environ.silent = (config.USER.output_verbose_level < 5)
522     build_environ.set_full_environ(logger, environ_info)
523
524     # c- download : check/get pip wheel in pip_wheels_dir
525     pip_download_cmd=config.INTERNAL.command.pip_download +\
526                      " --destination-directory %s --no-deps %s==%s " %\
527                      (pip_wheels_dir, p_info.name, p_info.version)
528     logger.write("\n"+pip_download_cmd+"\n", 4, False) 
529     res_pip_dwl = (subprocess.call(pip_download_cmd, 
530                                    shell=True, 
531                                    cwd=config.LOCAL.workdir,
532                                    env=build_environ.environ.environ,
533                                    stdout=logger.logTxtFile, 
534                                    stderr=subprocess.STDOUT) == 0)
535     # error is not managed at the stage. error will be handled by pip install
536     # here we just print a message
537     if not res_pip_dwl:
538         logger.write("Error in pip download\n", 4, False)
539
540
541     # d- install (in python or in separate product directory)
542     if src.appli_test_property(config,"pip_install_dir", "python"):
543         # pip will install product in python directory"
544         pip_install_cmd+=" --find-links=%s --build %s %s==%s" %\
545         (pip_wheels_dir, p_info.build_dir, p_info.name, p_info.version)
546         pip_install_in_python=True
547         
548     else: 
549         # pip will install product in product install_dir
550         pip_install_dir=os.path.join(p_info.install_dir, "lib", "python${PYTHON_VERSION:0:3}", "site-packages")
551         pip_install_cmd+=" --find-links=%s --build %s --target %s %s==%s" %\
552         (pip_wheels_dir, p_info.build_dir, pip_install_dir, p_info.name, p_info.version)
553     log_step(logger, header, "PIP")
554     logger.write("\n"+pip_install_cmd+"\n", 4)
555     len_end_line = len_end + 3
556     error_step = ""
557
558     res_pip = (subprocess.call(pip_install_cmd, 
559                                shell=True, 
560                                cwd=config.LOCAL.workdir,
561                                env=build_environ.environ.environ,
562                                stdout=logger.logTxtFile, 
563                                stderr=subprocess.STDOUT) == 0)        
564     if res_pip:
565         res=0
566     else:
567         #log_res_step(logger, res)
568         res=1
569         error_step = "PIP"
570         logger.write("\nError in pip command, please consult details with sat log command's internal traces\n", 3)
571
572     return res, len_end_line, error_step 
573
574
575
576 def compile_product_cmake_autotools(sat,
577                                     p_name_info,
578                                     config,
579                                     options,
580                                     logger,
581                                     header,
582                                     len_end):
583     '''Execute the proper build procedure for autotools or cmake
584        in the product build directory.
585     
586     :param p_name_info tuple: (str, Config) => (product_name, product_info)
587     :param config Config: The global configuration
588     :param logger Logger: The logger instance to use for the display 
589                           and logging
590     :param header Str: the header to display when logging
591     :param len_end Int: the lenght of the the end of line (used in display)
592     :return: 1 if it fails, else 0.
593     :rtype: int
594     '''
595     p_name, p_info = p_name_info
596     
597     # Execute "sat configure", "sat make" and "sat install"
598     res = 0
599     error_step = ""
600     
601     # Logging and sat command call for configure step
602     len_end_line = len_end
603     log_step(logger, header, "CONFIGURE")
604     res_c = sat.configure(config.VARS.application + " --products " + p_name,
605                           verbose = 0,
606                           logger_add_link = logger)
607     log_res_step(logger, res_c)
608     res += res_c
609     
610     if res_c > 0:
611         error_step = "CONFIGURE"
612     else:
613         # Logging and sat command call for make step
614         # Logging take account of the fact that the product has a compilation 
615         # script or not
616         if src.product.product_has_script(p_info):
617             # if the product has a compilation script, 
618             # it is executed during make step
619             scrit_path_display = src.printcolors.printcLabel(
620                                                         p_info.compil_script)
621             log_step(logger, header, "SCRIPT " + scrit_path_display)
622             len_end_line = len(scrit_path_display)
623         else:
624             log_step(logger, header, "MAKE")
625         make_arguments = config.VARS.application + " --products " + p_name
626         # Get the make_flags option if there is any
627         if options.makeflags:
628             make_arguments += " --option -j" + options.makeflags
629         res_m = sat.make(make_arguments,
630                          verbose = 0,
631                          logger_add_link = logger)
632         log_res_step(logger, res_m)
633         res += res_m
634         
635         if res_m > 0:
636             error_step = "MAKE"
637         else: 
638             # Logging and sat command call for make install step
639             log_step(logger, header, "MAKE INSTALL")
640             res_mi = sat.makeinstall(config.VARS.application + 
641                                      " --products " + 
642                                      p_name,
643                                     verbose = 0,
644                                     logger_add_link = logger)
645
646             log_res_step(logger, res_mi)
647             res += res_mi
648             
649             if res_mi > 0:
650                 error_step = "MAKE INSTALL"
651                 
652     return res, len_end_line, error_step 
653
654 def compile_product_script(sat,
655                            p_name_info,
656                            config,
657                            options,
658                            logger,
659                            header,
660                            len_end):
661     '''Execute the script build procedure in the product build directory.
662     
663     :param p_name_info tuple: (str, Config) => (product_name, product_info)
664     :param config Config: The global configuration
665     :param logger Logger: The logger instance to use for the display 
666                           and logging
667     :param header Str: the header to display when logging
668     :param len_end Int: the lenght of the the end of line (used in display)
669     :return: 1 if it fails, else 0.
670     :rtype: int
671     '''
672     p_name, p_info = p_name_info
673     
674     # Execute "sat configure", "sat make" and "sat install"
675     error_step = ""
676     
677     # Logging and sat command call for the script step
678     scrit_path_display = src.printcolors.printcLabel(p_info.compil_script)
679     log_step(logger, header, "SCRIPT " + scrit_path_display)
680     len_end_line = len_end + len(scrit_path_display)
681     res = sat.script(config.VARS.application + " --products " + p_name,
682                      verbose = 0,
683                      logger_add_link = logger)
684     log_res_step(logger, res)
685               
686     return res, len_end_line, error_step 
687
688     
689 def description():
690     '''method that is called when salomeTools is called with --help option.
691     
692     :return: The text to display for the compile command description.
693     :rtype: str
694     '''
695     return _("The compile command constructs the products of the application"
696              "\n\nexample:\nsat compile SALOME-master --products KERNEL,GUI,"
697              "MEDCOUPLING --clean_all")
698   
699 def run(args, runner, logger):
700     '''method that is called when salomeTools is called with compile parameter.
701     '''
702     # Parse the options
703     (options, args) = parser.parse_args(args)
704
705     # Warn the user if he invoked the clean_all option 
706     # without --products option
707     if (options.clean_all and 
708         options.products is None and 
709         not runner.options.batch):
710         rep = input(_("You used --clean_all without specifying a product"
711                           " are you sure you want to continue? [Yes/No] "))
712         if rep.upper() != _("YES").upper():
713             return 0
714         
715     if options.update and (options.clean_all or options.force or options.clean_install):
716         options.update=False  # update is useless in this case
717
718     # check that the command has been called with an application
719     src.check_config_has_application( runner.cfg )
720
721     # Print some informations
722     logger.write(_('Executing the compile commands in the build '
723                                 'directories of the products of '
724                                 'the application %s\n') % 
725                 src.printcolors.printcLabel(runner.cfg.VARS.application), 1)
726     
727     info = [
728             (_("SOURCE directory"),
729              os.path.join(runner.cfg.APPLICATION.workdir, 'SOURCES')),
730             (_("BUILD directory"),
731              os.path.join(runner.cfg.APPLICATION.workdir, 'BUILD'))
732             ]
733     src.print_info(logger, info)
734
735     # Get the list of all application products, and create its dependency graph
736     all_products_infos = src.product.get_products_infos(runner.cfg.APPLICATION.products,
737                                                         runner.cfg)
738     all_products_graph=get_dependencies_graph(all_products_infos)
739     #logger.write("Dependency graph of all application products : %s\n" % all_products_graph, 6)
740     DBG.write("Dependency graph of all application products : ", all_products_graph)
741
742     # Get the list of products we have to compile
743     products_infos = src.product.get_products_list(options, runner.cfg, logger)
744     products_list = [pi[0] for pi in products_infos]
745
746     logger.write("Product we have to compile (as specified by user) : %s\n" % products_list, 5)
747     if options.fathers:
748         # Extend the list with all recursive dependencies of the given products
749         visited=[]
750         for p_name in products_list:
751             visited=depth_search_graph(all_products_graph, p_name, visited)
752         products_list = visited
753
754     logger.write("Product list to compile with fathers : %s\n" % products_list, 5)
755     if options.children:
756         # Extend the list with all products that depends upon the given products
757         children=[]
758         for n in all_products_graph:
759             # for all products (that are not in products_list):
760             # if we we find a path from the product to the product list,
761             # then we product is a child and we add it to the children list 
762             if (n not in children) and (n not in products_list):
763                 if find_path_graph(all_products_graph, n, products_list):
764                     children = children + [n]
765         # complete products_list (the products we have to compile) with the list of children
766         products_list = products_list + children
767         logger.write("Product list to compile with children : %s\n" % products_list, 5)
768
769     # Sort the list of all products (topological sort).
770     # the products listed first do not depend upon products listed after
771     visited_nodes=[]
772     sorted_nodes=[]
773     for n in all_products_graph:
774         if n not in visited_nodes:
775             visited_nodes,sorted_nodes=depth_first_topo_graph(all_products_graph, n, visited_nodes,sorted_nodes)
776     logger.write("Complete dependency graph topological search (sorting): %s\n" % sorted_nodes, 6)
777
778     #  Create a dict of all products to facilitate products_infos sorting
779     all_products_dict={}
780     for (pname,pinfo) in all_products_infos:
781         all_products_dict[pname]=(pname,pinfo)
782
783     # Use the sorted list of all products to sort the list of products we have to compile
784     sorted_product_list=[]
785     product_list_runtime=[]
786     product_list_compiletime=[]
787
788     # store at beginning compile time products, we need to compile them before!
789     for n in sorted_nodes:
790         if n in products_list:
791             sorted_product_list.append(n)
792     logger.write("Sorted list of products to compile : %s\n" % sorted_product_list, 5)
793     
794     # from the sorted list of products to compile, build a sorted list of products infos
795     products_infos=[]
796     for product in sorted_product_list:
797         products_infos.append(all_products_dict[product])
798
799     # for all products to compile, store in "depend_all" field the complete dependencies (recursive) 
800     # (will be used by check_dependencies function)
801     for pi in products_infos:
802         dep_prod=[]
803         dep_prod=depth_search_graph(all_products_graph,pi[0], dep_prod)
804         pi[1]["depend_all"]=dep_prod[1:]
805         
806
807     # Call the function that will loop over all the products and execute
808     # the right command(s)
809     res = compile_all_products(runner, runner.cfg, options, products_infos, all_products_dict, all_products_graph, logger)
810     
811     # Print the final state
812     nb_products = len(products_infos)
813     if res == 0:
814         final_status = "OK"
815     else:
816         final_status = "KO"
817    
818     logger.write(_("\nCompilation: %(status)s (%(valid_result)d/%(nb_products)d)\n") % \
819         { 'status': src.printcolors.printc(final_status), 
820           'valid_result': nb_products - res,
821           'nb_products': nb_products }, 1)    
822     
823     code = res
824     if code != 0:
825         code = 1
826     return code