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