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