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