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