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