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