Salome HOME
style: black format
[tools/sat.git] / commands / patch.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 subprocess
21 import re
22
23 import src
24 import prepare
25
26 # Define all possible option for patch command :  sat patch <options>
27 parser = src.options.Options()
28 parser.add_option(
29     "p",
30     "products",
31     "list2",
32     "products",
33     _(
34         "Optional: products to get the sources. This option accepts a comma separated list."
35     ),
36 )
37
38
39 def apply_patch(config, product_info, max_product_name_len, logger):
40     """The method called to apply patches on a product
41
42     :param config Config: The global configuration
43     :param product_info Config: The configuration specific to
44                                the product to be patched
45     :param logger Logger: The logger instance to use for the display and logging
46     :return: (True if it succeed, else False, message to display)
47     :rtype: (boolean, str)
48     """
49
50     # if the product is native, do not apply patch
51     if src.product.product_is_native(product_info):
52         # display and log
53         logger.write("%s: " % src.printcolors.printcLabel(product_info.name), 4)
54         logger.write(" " * (max_product_name_len - len(product_info.name)), 4, False)
55         logger.write("\n", 4, False)
56         msg = (
57             _("The %s product is native. Do not apply " "any patch.")
58             % product_info.name
59         )
60         logger.write(msg, 4)
61         logger.write("\n", 4)
62         return True, ""
63
64     if not "patches" in product_info or len(product_info.patches) == 0:
65         # display and log
66         logger.write("%s: " % src.printcolors.printcLabel(product_info.name), 4)
67         logger.write(" " * (max_product_name_len - len(product_info.name)), 4, False)
68         logger.write("\n", 4, False)
69         msg = _("No patch for the %s product") % product_info.name
70         logger.write(msg, 4)
71         logger.write("\n", 4)
72         return True, ""
73     else:
74         # display and log
75         logger.write("%s: " % src.printcolors.printcLabel(product_info.name), 3)
76         logger.write(" " * (max_product_name_len - len(product_info.name)), 3, False)
77         logger.write("\n", 4, False)
78
79     if not os.path.exists(product_info.source_dir):
80         msg = _("No sources found for the %s product\n") % product_info.name
81         logger.write(src.printcolors.printcWarning(msg), 1)
82         return False, ""
83
84     # At this point, there one or more patches and the source directory exists
85     retcode = []
86     res = []
87     # Loop on all the patches of the product
88     for patch in product_info.patches:
89         details = []
90
91         # Check the existence and apply the patch
92         if os.path.isfile(patch):
93             patch_cmd = "patch -p1 < %s" % patch
94
95             # Write the command in the terminal if verbose level is at 5
96             logger.write(("    >%s\n" % patch_cmd), 5)
97
98             # Write the command in the log file (can be seen using 'sat log')
99             logger.logTxtFile.write("\n    >%s\n" % patch_cmd)
100             logger.logTxtFile.flush()
101
102             # Call the command
103             res_cmd = (
104                 subprocess.call(
105                     patch_cmd,
106                     shell=True,
107                     cwd=product_info.source_dir,
108                     stdout=logger.logTxtFile,
109                     stderr=subprocess.STDOUT,
110                 )
111                 == 0
112             )
113         else:
114             res_cmd = False
115             details.append(
116                 "  " + src.printcolors.printcError(_("Not a valid patch: %s") % patch)
117             )
118
119         res.append(res_cmd)
120
121         if res_cmd:
122             message = _("Apply patch %s") % src.printcolors.printcHighlight(patch)
123         else:
124             message = src.printcolors.printcWarning(
125                 _("Failed to apply patch %s") % patch
126             )
127
128         if config.USER.output_verbose_level >= 3:
129             retcode.append("  %s" % message)
130         else:
131             retcode.append("%s: %s" % (product_info.name, message))
132
133         if len(details) > 0:
134             retcode.extend(details)
135
136     res = not (False in res)
137
138     return res, "\n".join(retcode) + "\n"
139
140
141 def description():
142     """method that is called when salomeTools is called with --help option.
143
144     :return: The text to display for the patch command description.
145     :rtype: str
146     """
147     return _(
148         "The patch command apply the patches on the sources of "
149         "the application products if there is any.\n\nexample:\nsat "
150         "patch SALOME-master --products qt,boost"
151     )
152
153
154 def run(args, runner, logger):
155     """method that is called when salomeTools is called with patch parameter."""
156     # Parse the options
157     (options, args) = parser.parse_args(args)
158
159     # check that the command has been called with an application
160     src.check_config_has_application(runner.cfg)
161
162     # Print some informations
163     logger.write(
164         "Patching sources of the application %s\n"
165         % src.printcolors.printcLabel(runner.cfg.VARS.application),
166         1,
167     )
168
169     src.printcolors.print_value(logger, "workdir", runner.cfg.APPLICATION.workdir, 2)
170     logger.write("\n", 2, False)
171
172     # Get the products list with products informations regarding the options
173     products_infos = src.product.get_products_list(options, runner.cfg, logger)
174
175     # Get the maximum name length in order to format the terminal display
176     max_product_name_len = 1
177     if len(products_infos) > 0:
178         max_product_name_len = max(map(lambda l: len(l), products_infos[0])) + 4
179
180     # The loop on all the products on which to apply the patches
181     good_result = 0
182     for __, product_info in products_infos:
183         # Apply the patch
184         return_code, patch_res = apply_patch(
185             runner.cfg, product_info, max_product_name_len, logger
186         )
187         logger.write(patch_res, 1, False)
188         if return_code:
189             good_result += 1
190
191     # Display the results (how much passed, how much failed, etc...)
192
193     logger.write("\n", 2, False)
194     if good_result == len(products_infos):
195         status = src.OK_STATUS
196         res_count = "%d / %d" % (good_result, good_result)
197     else:
198         status = src.KO_STATUS
199         res_count = "%d / %d" % (good_result, len(products_infos))
200
201     # write results
202     logger.write("Patching sources of the application:", 1)
203     logger.write(" " + src.printcolors.printc(status), 1, False)
204     logger.write(" (%s)\n" % res_count, 1, False)
205
206     return len(products_infos) - good_result