Salome HOME
sat #32534 : warning if the application is used on a not supported platform, and...
[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
542
543     # d- install (in python or in separate product directory)
544     if src.appli_test_property(config,"pip_install_dir", "python"):
545         # pip will install product in python directory"
546         pip_install_cmd+=" --find-links=%s --build %s %s==%s" %\
547         (pip_wheels_dir, p_info.build_dir, p_info.name, p_info.version)
548         pip_install_in_python=True
549         
550     else: 
551         # pip will install product in product install_dir
552         pip_install_dir=os.path.join(p_info.install_dir, "lib", "python${PYTHON_VERSION:0:3}", "site-packages")
553         pip_install_cmd+=" --find-links=%s --build %s --target %s %s==%s" %\
554         (pip_wheels_dir, p_info.build_dir, pip_install_dir, p_info.name, p_info.version)
555     log_step(logger, header, "PIP")
556     logger.write("\n"+pip_install_cmd+"\n", 4)
557     len_end_line = len_end + 3
558     error_step = ""
559
560     res_pip = (subprocess.call(pip_install_cmd, 
561                                shell=True, 
562                                cwd=config.LOCAL.workdir,
563                                env=build_environ.environ.environ,
564                                stdout=logger.logTxtFile, 
565                                stderr=subprocess.STDOUT) == 0)        
566     if res_pip:
567         res=0
568     else:
569         #log_res_step(logger, res)
570         res=1
571         error_step = "PIP"
572         logger.write("\nError in pip command, please consult details with sat log command's internal traces\n", 3)
573
574     return res, len_end_line, error_step 
575
576
577
578 def compile_product_cmake_autotools(sat,
579                                     p_name_info,
580                                     config,
581                                     options,
582                                     logger,
583                                     header,
584                                     len_end):
585     '''Execute the proper build procedure for autotools or cmake
586        in the product build directory.
587     
588     :param p_name_info tuple: (str, Config) => (product_name, product_info)
589     :param config Config: The global configuration
590     :param logger Logger: The logger instance to use for the display 
591                           and logging
592     :param header Str: the header to display when logging
593     :param len_end Int: the lenght of the the end of line (used in display)
594     :return: 1 if it fails, else 0.
595     :rtype: int
596     '''
597     p_name, p_info = p_name_info
598     
599     # Execute "sat configure", "sat make" and "sat install"
600     res = 0
601     error_step = ""
602     
603     # Logging and sat command call for configure step
604     len_end_line = len_end
605     log_step(logger, header, "CONFIGURE")
606     res_c = sat.configure(config.VARS.application + " --products " + p_name,
607                           verbose = 0,
608                           logger_add_link = logger)
609     log_res_step(logger, res_c)
610     res += res_c
611     
612     if res_c > 0:
613         error_step = "CONFIGURE"
614     else:
615         # Logging and sat command call for make step
616         # Logging take account of the fact that the product has a compilation 
617         # script or not
618         if src.product.product_has_script(p_info):
619             # if the product has a compilation script, 
620             # it is executed during make step
621             scrit_path_display = src.printcolors.printcLabel(
622                                                         p_info.compil_script)
623             log_step(logger, header, "SCRIPT " + scrit_path_display)
624             len_end_line = len(scrit_path_display)
625         else:
626             log_step(logger, header, "MAKE")
627         make_arguments = config.VARS.application + " --products " + p_name
628         # Get the make_flags option if there is any
629         if options.makeflags:
630             make_arguments += " --option -j" + options.makeflags
631         res_m = sat.make(make_arguments,
632                          verbose = 0,
633                          logger_add_link = logger)
634         log_res_step(logger, res_m)
635         res += res_m
636         
637         if res_m > 0:
638             error_step = "MAKE"
639         else: 
640             # Logging and sat command call for make install step
641             log_step(logger, header, "MAKE INSTALL")
642             res_mi = sat.makeinstall(config.VARS.application + 
643                                      " --products " + 
644                                      p_name,
645                                     verbose = 0,
646                                     logger_add_link = logger)
647
648             log_res_step(logger, res_mi)
649             res += res_mi
650             
651             if res_mi > 0:
652                 error_step = "MAKE INSTALL"
653                 
654     return res, len_end_line, error_step 
655
656 def compile_product_script(sat,
657                            p_name_info,
658                            config,
659                            options,
660                            logger,
661                            header,
662                            len_end):
663     '''Execute the script build procedure in the product build directory.
664     
665     :param p_name_info tuple: (str, Config) => (product_name, product_info)
666     :param config Config: The global configuration
667     :param logger Logger: The logger instance to use for the display 
668                           and logging
669     :param header Str: the header to display when logging
670     :param len_end Int: the lenght of the the end of line (used in display)
671     :return: 1 if it fails, else 0.
672     :rtype: int
673     '''
674     p_name, p_info = p_name_info
675     
676     # Execute "sat configure", "sat make" and "sat install"
677     error_step = ""
678     
679     # Logging and sat command call for the script step
680     scrit_path_display = src.printcolors.printcLabel(p_info.compil_script)
681     log_step(logger, header, "SCRIPT " + scrit_path_display)
682     len_end_line = len_end + len(scrit_path_display)
683     res = sat.script(config.VARS.application + " --products " + p_name,
684                      verbose = 0,
685                      logger_add_link = logger)
686     log_res_step(logger, res)
687               
688     return res, len_end_line, error_step 
689
690     
691 def description():
692     '''method that is called when salomeTools is called with --help option.
693     
694     :return: The text to display for the compile command description.
695     :rtype: str
696     '''
697     return _("The compile command constructs the products of the application"
698              "\n\nexample:\nsat compile SALOME-master --products KERNEL,GUI,"
699              "MEDCOUPLING --clean_all")
700   
701 def run(args, runner, logger):
702     '''method that is called when salomeTools is called with compile parameter.
703     '''
704     # Parse the options
705     (options, args) = parser.parse_args(args)
706
707     # Warn the user if he invoked the clean_all option 
708     # without --products option
709     if (options.clean_all and 
710         options.products is None and 
711         not runner.options.batch):
712         rep = input(_("You used --clean_all without specifying a product"
713                           " are you sure you want to continue? [Yes/No] "))
714         if rep.upper() != _("YES").upper():
715             return 0
716         
717     if options.update and (options.clean_all or options.force or options.clean_install):
718         options.update=False  # update is useless in this case
719
720     # check that the command has been called with an application
721     src.check_config_has_application( runner.cfg )
722
723     # write warning if platform is not declared as supported
724     src.check_platform_is_supported( runner.cfg, logger )
725
726     # Print some informations
727     logger.write(_('Executing the compile commands in the build '
728                                 'directories of the products of '
729                                 'the application %s\n') % 
730                 src.printcolors.printcLabel(runner.cfg.VARS.application), 1)
731     
732     info = [
733             (_("SOURCE directory"),
734              os.path.join(runner.cfg.APPLICATION.workdir, 'SOURCES')),
735             (_("BUILD directory"),
736              os.path.join(runner.cfg.APPLICATION.workdir, 'BUILD'))
737             ]
738     src.print_info(logger, info)
739
740     # Get the list of all application products, and create its dependency graph
741     all_products_infos = src.product.get_products_infos(runner.cfg.APPLICATION.products,
742                                                         runner.cfg)
743     all_products_graph=get_dependencies_graph(all_products_infos)
744     #logger.write("Dependency graph of all application products : %s\n" % all_products_graph, 6)
745     DBG.write("Dependency graph of all application products : ", all_products_graph)
746
747     # Get the list of products we have to compile
748     products_infos = src.product.get_products_list(options, runner.cfg, logger)
749     products_list = [pi[0] for pi in products_infos]
750
751     logger.write("Product we have to compile (as specified by user) : %s\n" % products_list, 5)
752     if options.fathers:
753         # Extend the list with all recursive dependencies of the given products
754         visited=[]
755         for p_name in products_list:
756             visited=depth_search_graph(all_products_graph, p_name, visited)
757         products_list = visited
758
759     logger.write("Product list to compile with fathers : %s\n" % products_list, 5)
760     if options.children:
761         # Extend the list with all products that depends upon the given products
762         children=[]
763         for n in all_products_graph:
764             # for all products (that are not in products_list):
765             # if we we find a path from the product to the product list,
766             # then we product is a child and we add it to the children list 
767             if (n not in children) and (n not in products_list):
768                 if find_path_graph(all_products_graph, n, products_list):
769                     children = children + [n]
770         # complete products_list (the products we have to compile) with the list of children
771         products_list = products_list + children
772         logger.write("Product list to compile with children : %s\n" % products_list, 5)
773
774     # Sort the list of all products (topological sort).
775     # the products listed first do not depend upon products listed after
776     visited_nodes=[]
777     sorted_nodes=[]
778     for n in all_products_graph:
779         if n not in visited_nodes:
780             visited_nodes,sorted_nodes=depth_first_topo_graph(all_products_graph, n, visited_nodes,sorted_nodes)
781     logger.write("Complete dependency graph topological search (sorting): %s\n" % sorted_nodes, 6)
782
783     #  Create a dict of all products to facilitate products_infos sorting
784     all_products_dict={}
785     for (pname,pinfo) in all_products_infos:
786         all_products_dict[pname]=(pname,pinfo)
787
788     # Use the sorted list of all products to sort the list of products we have to compile
789     sorted_product_list=[]
790     product_list_runtime=[]
791     product_list_compiletime=[]
792
793     # store at beginning compile time products, we need to compile them before!
794     for n in sorted_nodes:
795         if n in products_list:
796             sorted_product_list.append(n)
797     logger.write("Sorted list of products to compile : %s\n" % sorted_product_list, 5)
798     
799     # from the sorted list of products to compile, build a sorted list of products infos
800     products_infos=[]
801     for product in sorted_product_list:
802         products_infos.append(all_products_dict[product])
803
804     # for all products to compile, store in "depend_all" field the complete dependencies (recursive) 
805     # (will be used by check_dependencies function)
806     for pi in products_infos:
807         dep_prod=[]
808         dep_prod=depth_search_graph(all_products_graph,pi[0], dep_prod)
809         pi[1]["depend_all"]=dep_prod[1:]
810         
811
812     # Call the function that will loop over all the products and execute
813     # the right command(s)
814     res = compile_all_products(runner, runner.cfg, options, products_infos, all_products_dict, all_products_graph, logger)
815     
816     # Print the final state
817     nb_products = len(products_infos)
818     if res == 0:
819         final_status = "OK"
820     else:
821         final_status = "KO"
822    
823     logger.write(_("\nCompilation: %(status)s (%(valid_result)d/%(nb_products)d)\n") % \
824         { 'status': src.printcolors.printc(final_status), 
825           'valid_result': nb_products - res,
826           'nb_products': nb_products }, 1)    
827     
828     code = res
829     if code != 0:
830         code = 1
831     return code