Salome HOME
b6da2f326012a9ee9245719c6a4764665f500403
[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 src.product.product_is_configuration(product_info):
249                 check_source = check_source and src.product.check_source(product_info)
250                 if not check_source:
251                     logger.write(_("\nERROR : SOURCES of %s not found! It is required for" 
252                                    " the configuration\n" % product_name))
253                     logger.write(_("        Get it with the command : sat prepare %s -p %s \n" % 
254                                   (config.APPLICATION.name, product_name)))
255                     res += 1
256         if res>0:
257             return res  # error configure dependency : we stop the compilation
258
259     # second loop to compile
260     res = 0
261     for p_name_info in products_infos:
262         
263         p_name, p_info = p_name_info
264         
265         # Logging
266         len_end_line = 30
267         header = _("Compilation of %s") % src.printcolors.printcLabel(p_name)
268         header += " %s " % ("." * (len_end_line - len(p_name)))
269         logger.write(header, 3)
270         logger.flush()
271
272         # Do nothing if the product is not compilable
273         if not src.product.product_compiles(p_info):
274             log_step(logger, header, "ignored")
275             logger.write("\n", 3, False)
276             continue
277
278         # Do nothing if the product is native
279         if src.product.product_is_native(p_info):
280             log_step(logger, header, "native")
281             logger.write("\n", 3, False)
282             continue
283
284         # Do nothing if the product is fixed (already compiled by third party)
285         if src.product.product_is_fixed(p_info):
286             log_step(logger, header, "native")
287             logger.write("\n", 3, False)
288             continue
289
290
291         # Recompute the product information to get the right install_dir
292         # (it could change if there is a clean of the install directory)
293         p_info = src.product.get_product_config(config, p_name)
294         
295         # Check if sources was already successfully installed
296         check_source = src.product.check_source(p_info)
297         is_pip= (src.appli_test_property(config,"pip", "yes") and src.product.product_test_property(p_info,"pip", "yes"))
298         # don't check sources with option --show 
299         # or for products managed by pip (there sources are in wheels stored in LOCAL.ARCHIVE
300         if not (options.no_compile or is_pip): 
301             if not check_source:
302                 logger.write(_("Sources of product not found (try 'sat -h prepare') \n"))
303                 res += 1 # one more error
304                 continue
305         
306         # if we don't force compilation, check if the was already successfully installed.
307         # we don't compile in this case.
308         if (not options.force) and src.product.check_installation(config, p_info):
309             logger.write(_("Already installed"))
310             logger.write(_(" in %s" % p_info.install_dir), 4)
311             logger.write(_("\n"))
312             continue
313         
314         # If the show option was called, do not launch the compilation
315         if options.no_compile:
316             logger.write(_("Not installed in %s\n" % p_info.install_dir))
317             continue
318         
319         # Check if the dependencies are installed
320         l_depends_not_installed = check_dependencies(config, p_name_info, all_products_dict)
321         if len(l_depends_not_installed) > 0:
322             log_step(logger, header, "")
323             logger.write(src.printcolors.printcError(
324                     _("ERROR : the following mandatory product(s) is(are) not installed: ")))
325             for prod_name in l_depends_not_installed:
326                 logger.write(src.printcolors.printcError(prod_name + " "))
327             logger.write("\n")
328             continue
329         
330         # Call the function to compile the product
331         res_prod, len_end_line, error_step = compile_product(
332              sat, p_name_info, config, options, logger, header, len_end_line)
333         
334         if res_prod != 0:
335             res += 1
336             # there was an error, we clean install dir, unless :
337             #  - the error step is "check", or
338             #  - the product is managed by pip and installed in python dir
339             do_not_clean_install=False
340             is_single_dir=(src.appli_test_property(config,"single_install_dir", "yes") and \
341                            src.product.product_test_property(p_info,"single_install_dir", "yes"))
342               
343             if (error_step == "CHECK") or (is_pip and src.appli_test_property(config,"pip_install_dir", "python")) or is_single_dir  :
344                 # cases for which we do not want to remove install dir
345                 #   for is_single_dir and is_pip, the test to determine if the product is already 
346                 #   compiled is based on configuration file, not the directory
347                 do_not_clean_install=True 
348
349             if not do_not_clean_install:
350                 # Clean the install directory if there is any
351                 logger.write(_(
352                             "Cleaning the install directory if there is any\n"),
353                              5)
354                 sat.clean(config.VARS.application + 
355                           " --products " + p_name + 
356                           " --install",
357                           batch=True,
358                           verbose=0,
359                           logger_add_link = logger)
360         else:
361             # Clean the build directory if the compilation and tests succeed
362             if options.clean_build_after:
363                 log_step(logger, header, "CLEAN BUILD")
364                 sat.clean(config.VARS.application + 
365                           " --products " + p_name + 
366                           " --build",
367                           batch=True,
368                           verbose=0,
369                           logger_add_link = logger)
370
371         # Log the result
372         if res_prod > 0:
373             logger.write("\r%s%s" % (header, " " * len_end_line), 3)
374             logger.write("\r" + header + src.printcolors.printcError("KO ") + error_step)
375             logger.write("\n==== %(KO)s in compile of %(name)s \n" %
376                 { "name" : p_name , "KO" : src.printcolors.printcInfo("ERROR")}, 4)
377             if error_step == "CHECK":
378                 logger.write(_("\nINSTALL directory = %s" % 
379                            src.printcolors.printcInfo(p_info.install_dir)), 3)
380             logger.flush()
381         else:
382             logger.write("\r%s%s" % (header, " " * len_end_line), 3)
383             logger.write("\r" + header + src.printcolors.printcSuccess("OK"))
384             logger.write(_("\nINSTALL directory = %s" % 
385                            src.printcolors.printcInfo(p_info.install_dir)), 3)
386             logger.write("\n==== %s \n" % src.printcolors.printcInfo("OK"), 4)
387             logger.write("\n==== Compilation of %(name)s %(OK)s \n" %
388                 { "name" : p_name , "OK" : src.printcolors.printcInfo("OK")}, 4)
389             logger.flush()
390         logger.write("\n", 3, False)
391         
392         
393         if res_prod != 0 and options.stop_first_fail:
394             break
395         
396     return res
397
398 def compile_product(sat, p_name_info, config, options, logger, header, len_end):
399     '''Execute the proper configuration command(s) 
400        in the product build directory.
401     
402     :param p_name_info tuple: (str, Config) => (product_name, product_info)
403     :param config Config: The global configuration
404     :param logger Logger: The logger instance to use for the display 
405                           and logging
406     :param header Str: the header to display when logging
407     :param len_end Int: the lenght of the the end of line (used in display)
408     :return: 1 if it fails, else 0.
409     :rtype: int
410     '''
411     
412     p_name, p_info = p_name_info
413           
414     # Get the build procedure from the product configuration.
415     # It can be :
416     # build_sources : autotools -> build_configure, configure, make, make install
417     # build_sources : cmake     -> cmake, make, make install
418     # build_sources : script    -> script executions
419     res = 0
420
421     
422     # check if pip should be used : the application and product have pip property
423     if (src.appli_test_property(config,"pip", "yes") and 
424        src.product.product_test_property(p_info,"pip", "yes")):
425             res, len_end_line, error_step = compile_product_pip(sat,
426                                                                 p_name_info,
427                                                                 config,
428                                                                 options,
429                                                                 logger,
430                                                                 header,
431                                                                 len_end)
432     else:
433         if (src.product.product_is_autotools(p_info) or 
434                                               src.product.product_is_cmake(p_info)):
435             res, len_end_line, error_step = compile_product_cmake_autotools(sat,
436                                                                       p_name_info,
437                                                                       config,
438                                                                       options,
439                                                                       logger,
440                                                                       header,
441                                                                       len_end)
442         if src.product.product_has_script(p_info):
443             res, len_end_line, error_step = compile_product_script(sat,
444                                                                    p_name_info,
445                                                                    config,
446                                                                    options,
447                                                                    logger,
448                                                                    header,
449                                                                    len_end)
450
451     # Check that the install directory exists
452     if res==0 and not(os.path.exists(p_info.install_dir)):
453         res = 1
454         error_step = "NO INSTALL DIR"
455         msg = _("Error: despite the fact that all the steps ended successfully,"
456                 " no install directory was found !")
457         logger.write(src.printcolors.printcError(msg), 4)
458         logger.write("\n", 4)
459         return res, len_end, error_step
460     
461     # Add the config file corresponding to the dependencies/versions of the 
462     # product that have been successfully compiled
463     if res==0:       
464         logger.write(_("Add the config file in installation directory\n"), 5)
465         # for git bases : add the description of git tag
466         src_sha1=src.system.git_describe(p_info.source_dir)
467         if src_sha1:
468             p_info.git_tag_description=src_sha1
469         src.product.add_compile_config_file(p_info, config)
470         
471         if options.check:
472             # Do the unit tests (call the check command)
473             log_step(logger, header, "CHECK")
474             res_check = sat.check(
475                               config.VARS.application + " --products " + p_name,
476                               verbose = 0,
477                               logger_add_link = logger)
478             if res_check != 0:
479                 error_step = "CHECK"
480                 
481             res += res_check
482     
483     return res, len_end_line, error_step
484
485
486 def compile_product_pip(sat,
487                         p_name_info,
488                         config,
489                         options,
490                         logger,
491                         header,
492                         len_end):
493     '''Execute the proper build procedure for pip products
494     :param p_name_info tuple: (str, Config) => (product_name, product_info)
495     :param config Config: The global configuration
496     :param logger Logger: The logger instance to use for the display 
497                           and logging
498     :param header Str: the header to display when logging
499     :param len_end Int: the lenght of the the end of line (used in display)
500     :return: 1 if it fails, else 0.
501     :rtype: int
502     '''
503     # pip needs openssl-dev. If openssl is declared in the application, we check it!
504     if "openssl" in config.APPLICATION.products:
505         openssl_cfg = src.product.get_product_config(config, "openssl")
506         if not src.product.check_installation(config, openssl_cfg):
507             raise src.SatException(_("please install system openssl development package, it is required for products managed by pip."))
508     # a) initialisation
509     p_name, p_info = p_name_info
510     res = 0
511     error_step = ""
512     pip_install_in_python=False
513     pip_wheels_dir=os.path.join(config.LOCAL.archive_dir,"wheels")
514     pip_install_cmd=config.INTERNAL.command.pip_install # parametrized in src/internal
515
516     # b) get the build environment (useful to get the installed python & pip3)
517     build_environ = src.environment.SalomeEnviron(config,
518                              src.environment.Environ(dict(os.environ)),
519                              True)
520     environ_info = src.product.get_product_dependencies(config,
521                                                         p_name,
522                                                         p_info)
523     build_environ.silent = (config.USER.output_verbose_level < 5)
524     build_environ.set_full_environ(logger, environ_info)
525
526     # c- download : check/get pip wheel in pip_wheels_dir
527     pip_download_cmd=config.INTERNAL.command.pip_download +\
528                      " --destination-directory %s --no-deps %s==%s " %\
529                      (pip_wheels_dir, p_info.name, p_info.version)
530     logger.write("\n"+pip_download_cmd+"\n", 4, False) 
531     res_pip_dwl = (subprocess.call(pip_download_cmd, 
532                                    shell=True, 
533                                    cwd=config.LOCAL.workdir,
534                                    env=build_environ.environ.environ,
535                                    stdout=logger.logTxtFile, 
536                                    stderr=subprocess.STDOUT) == 0)
537     # error is not managed at the stage. error will be handled by pip install
538     # here we just print a message
539     if not res_pip_dwl:
540         logger.write("Error in pip download\n", 4, False)
541     try:
542         pip_version_cmd = 'python -c "import pip;print(pip.__version__)"'
543         res_pip_version = subprocess.check_output(pip_version_cmd,
544                                shell=True,
545                                cwd=config.LOCAL.workdir,
546                                env=build_environ.environ.environ,
547                                stderr=subprocess.STDOUT).strip()
548         pip_build_options=res_pip_version.split('.')[0] < 21
549     except:
550         pip_build_options= True
551     # d- install (in python or in separate product directory)
552     if src.appli_test_property(config,"pip_install_dir", "python"):
553         # pip will install product in python directory"
554         if pip_build_options:
555             pip_install_cmd+=" --find-links=%s --build %s %s==%s" %\
556                 (pip_wheels_dir, p_info.build_dir, p_info.name, p_info.version)
557         else:
558             pip_install_cmd+=" --find-links=%s --cache-dir %s %s==%s" %\
559                 (pip_wheels_dir, p_info.build_dir, p_info.name, p_info.version)
560         pip_install_in_python=True
561     else: 
562         # pip will install product in product install_dir
563         pip_install_dir=os.path.join(p_info.install_dir, "lib", "python${PYTHON}", "site-packages")
564         if pip_build_options:
565             pip_install_cmd+=" --find-links=%s --build %s --target %s %s==%s" %\
566                 (pip_wheels_dir, p_info.build_dir, pip_install_dir, p_info.name, p_info.version)
567         else:
568             pip_install_cmd+=" --find-links=%s --cache-dir %s --target %s %s==%s" %\
569                 (pip_wheels_dir,  p_info.build_dir, pip_install_dir, p_info.name, p_info.version)
570     log_step(logger, header, "PIP")
571     logger.write("\n"+pip_install_cmd+"\n", 4)
572     len_end_line = len_end + 3
573     error_step = ""
574
575     res_pip = (subprocess.call(pip_install_cmd, 
576                                shell=True, 
577                                cwd=config.LOCAL.workdir,
578                                env=build_environ.environ.environ,
579                                stdout=logger.logTxtFile, 
580                                stderr=subprocess.STDOUT) == 0)        
581     if res_pip:
582         res=0
583     else:
584         #log_res_step(logger, res)
585         res=1
586         error_step = "PIP"
587         logger.write("\nError in pip command, please consult details with sat log command's internal traces\n", 3)
588
589     return res, len_end_line, error_step 
590
591
592
593 def compile_product_cmake_autotools(sat,
594                                     p_name_info,
595                                     config,
596                                     options,
597                                     logger,
598                                     header,
599                                     len_end):
600     '''Execute the proper build procedure for autotools or cmake
601        in the product build directory.
602     
603     :param p_name_info tuple: (str, Config) => (product_name, product_info)
604     :param config Config: The global configuration
605     :param logger Logger: The logger instance to use for the display 
606                           and logging
607     :param header Str: the header to display when logging
608     :param len_end Int: the lenght of the the end of line (used in display)
609     :return: 1 if it fails, else 0.
610     :rtype: int
611     '''
612     p_name, p_info = p_name_info
613     
614     # Execute "sat configure", "sat make" and "sat install"
615     res = 0
616     error_step = ""
617     
618     # Logging and sat command call for configure step
619     len_end_line = len_end
620     log_step(logger, header, "CONFIGURE")
621     res_c = sat.configure(config.VARS.application + " --products " + p_name,
622                           verbose = 0,
623                           logger_add_link = logger)
624     log_res_step(logger, res_c)
625     res += res_c
626     
627     if res_c > 0:
628         error_step = "CONFIGURE"
629     else:
630         # Logging and sat command call for make step
631         # Logging take account of the fact that the product has a compilation 
632         # script or not
633         if src.product.product_has_script(p_info):
634             # if the product has a compilation script, 
635             # it is executed during make step
636             scrit_path_display = src.printcolors.printcLabel(
637                                                         p_info.compil_script)
638             log_step(logger, header, "SCRIPT " + scrit_path_display)
639             len_end_line = len(scrit_path_display)
640         else:
641             log_step(logger, header, "MAKE")
642         make_arguments = config.VARS.application + " --products " + p_name
643         # Get the make_flags option if there is any
644         if options.makeflags:
645             make_arguments += " --option -j" + options.makeflags
646         res_m = sat.make(make_arguments,
647                          verbose = 0,
648                          logger_add_link = logger)
649         log_res_step(logger, res_m)
650         res += res_m
651         
652         if res_m > 0:
653             error_step = "MAKE"
654         else: 
655             # Logging and sat command call for make install step
656             log_step(logger, header, "MAKE INSTALL")
657             res_mi = sat.makeinstall(config.VARS.application + 
658                                      " --products " + 
659                                      p_name,
660                                     verbose = 0,
661                                     logger_add_link = logger)
662
663             log_res_step(logger, res_mi)
664             res += res_mi
665             
666             if res_mi > 0:
667                 error_step = "MAKE INSTALL"
668                 
669     return res, len_end_line, error_step 
670
671 def compile_product_script(sat,
672                            p_name_info,
673                            config,
674                            options,
675                            logger,
676                            header,
677                            len_end):
678     '''Execute the script build procedure in the product build directory.
679     
680     :param p_name_info tuple: (str, Config) => (product_name, product_info)
681     :param config Config: The global configuration
682     :param logger Logger: The logger instance to use for the display 
683                           and logging
684     :param header Str: the header to display when logging
685     :param len_end Int: the lenght of the the end of line (used in display)
686     :return: 1 if it fails, else 0.
687     :rtype: int
688     '''
689     p_name, p_info = p_name_info
690     
691     # Execute "sat configure", "sat make" and "sat install"
692     error_step = ""
693     
694     # Logging and sat command call for the script step
695     scrit_path_display = src.printcolors.printcLabel(p_info.compil_script)
696     log_step(logger, header, "SCRIPT " + scrit_path_display)
697     len_end_line = len_end + len(scrit_path_display)
698     res = sat.script(config.VARS.application + " --products " + p_name,
699                      verbose = 0,
700                      logger_add_link = logger)
701     log_res_step(logger, res)
702               
703     return res, len_end_line, error_step 
704
705     
706 def description():
707     '''method that is called when salomeTools is called with --help option.
708     
709     :return: The text to display for the compile command description.
710     :rtype: str
711     '''
712     return _("The compile command constructs the products of the application"
713              "\n\nexample:\nsat compile SALOME-master --products KERNEL,GUI,"
714              "MEDCOUPLING --clean_all")
715   
716 def run(args, runner, logger):
717     '''method that is called when salomeTools is called with compile parameter.
718     '''
719     # Parse the options
720     (options, args) = parser.parse_args(args)
721
722     # Warn the user if he invoked the clean_all option 
723     # without --products option
724     if (options.clean_all and 
725         options.products is None and 
726         not runner.options.batch):
727         rep = input(_("You used --clean_all without specifying a product"
728                           " are you sure you want to continue? [Yes/No] "))
729         if rep.upper() != _("YES").upper():
730             return 0
731         
732     if options.update and (options.clean_all or options.force or options.clean_install):
733         options.update=False  # update is useless in this case
734
735     # check that the command has been called with an application
736     src.check_config_has_application( runner.cfg )
737
738     # write warning if platform is not declared as supported
739     src.check_platform_is_supported( runner.cfg, logger )
740
741     # Print some informations
742     logger.write(_('Executing the compile commands in the build '
743                                 'directories of the products of '
744                                 'the application %s\n') % 
745                 src.printcolors.printcLabel(runner.cfg.VARS.application), 1)
746     
747     info = [
748             (_("SOURCE directory"),
749              os.path.join(runner.cfg.APPLICATION.workdir, 'SOURCES')),
750             (_("BUILD directory"),
751              os.path.join(runner.cfg.APPLICATION.workdir, 'BUILD'))
752             ]
753     src.print_info(logger, info)
754
755     # Get the list of all application products, and create its dependency graph
756     all_products_infos = src.product.get_products_infos(runner.cfg.APPLICATION.products,
757                                                         runner.cfg)
758     all_products_graph=get_dependencies_graph(all_products_infos)
759     #logger.write("Dependency graph of all application products : %s\n" % all_products_graph, 6)
760     DBG.write("Dependency graph of all application products : ", all_products_graph)
761
762     # Get the list of products we have to compile
763     products_infos = src.product.get_products_list(options, runner.cfg, logger)
764     products_list = [pi[0] for pi in products_infos]
765
766     logger.write("Product we have to compile (as specified by user) : %s\n" % products_list, 5)
767     if options.fathers:
768         # Extend the list with all recursive dependencies of the given products
769         visited=[]
770         for p_name in products_list:
771             visited=depth_search_graph(all_products_graph, p_name, visited)
772         products_list = visited
773
774     logger.write("Product list to compile with fathers : %s\n" % products_list, 5)
775     if options.children:
776         # Extend the list with all products that depends upon the given products
777         children=[]
778         for n in all_products_graph:
779             # for all products (that are not in products_list):
780             # if we we find a path from the product to the product list,
781             # then we product is a child and we add it to the children list 
782             if (n not in children) and (n not in products_list):
783                 if find_path_graph(all_products_graph, n, products_list):
784                     children = children + [n]
785         # complete products_list (the products we have to compile) with the list of children
786         products_list = products_list + children
787         logger.write("Product list to compile with children : %s\n" % products_list, 5)
788
789     # Sort the list of all products (topological sort).
790     # the products listed first do not depend upon products listed after
791     visited_nodes=[]
792     sorted_nodes=[]
793     for n in all_products_graph:
794         if n not in visited_nodes:
795             visited_nodes,sorted_nodes=depth_first_topo_graph(all_products_graph, n, visited_nodes,sorted_nodes)
796     logger.write("Complete dependency graph topological search (sorting): %s\n" % sorted_nodes, 6)
797
798     #  Create a dict of all products to facilitate products_infos sorting
799     all_products_dict={}
800     for (pname,pinfo) in all_products_infos:
801         all_products_dict[pname]=(pname,pinfo)
802
803     # Use the sorted list of all products to sort the list of products we have to compile
804     sorted_product_list=[]
805     product_list_runtime=[]
806     product_list_compiletime=[]
807
808     # store at beginning compile time products, we need to compile them before!
809     for n in sorted_nodes:
810         if n in products_list:
811             sorted_product_list.append(n)
812     logger.write("Sorted list of products to compile : %s\n" % sorted_product_list, 5)
813     
814     # from the sorted list of products to compile, build a sorted list of products infos
815     products_infos=[]
816     for product in sorted_product_list:
817         products_infos.append(all_products_dict[product])
818
819     # for all products to compile, store in "depend_all" field the complete dependencies (recursive) 
820     # (will be used by check_dependencies function)
821     for pi in products_infos:
822         dep_prod=[]
823         dep_prod=depth_search_graph(all_products_graph,pi[0], dep_prod)
824         pi[1]["depend_all"]=dep_prod[1:]
825         
826
827     # Call the function that will loop over all the products and execute
828     # the right command(s)
829     res = compile_all_products(runner, runner.cfg, options, products_infos, all_products_dict, all_products_graph, logger)
830     
831     # Print the final state
832     nb_products = len(products_infos)
833     if res == 0:
834         final_status = "OK"
835     else:
836         final_status = "KO"
837    
838     logger.write(_("\nCompilation: %(status)s (%(valid_result)d/%(nb_products)d)\n") % \
839         { 'status': src.printcolors.printc(final_status), 
840           'valid_result': nb_products - res,
841           'nb_products': nb_products }, 1)    
842     
843     code = res
844     if code != 0:
845         code = 1
846     return code