Salome HOME
Add the patch command
[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
22 import src
23
24 # Define all possible option for log command :  sat log <options>
25 parser = src.options.Options()
26 parser.add_option('m', 'module', 'list2', 'modules',
27     _('modules to get the sources. This option can be'
28     ' passed several time to get the sources of several modules.'))
29 parser.add_option('', 'no_sample', 'boolean', 'no_sample', 
30     _("do not get sources from sample modules."))
31
32 def apply_patch(config, module_info, logger):
33     if not "patches" in module_info or len(module_info.patches) == 0:
34         msg = _("No patch for the %s module") % module_info.name
35         logger.write(msg, 3)
36         logger.write("\n", 1)
37         return True, ""
38
39     if not os.path.exists(module_info.source_dir):
40         msg = _("No sources found for the %s module\n") % module_info.name
41         logger.write(src.printcolors.printcWarning(msg), 1)
42         return False, ""
43
44     retcode = []
45     res = []
46     for patch in module_info.patches:
47         details = []
48
49         if os.path.isfile(patch) and patch.endswith(".patch"):
50             #patch_exe = "patch" # old patch command (now replace by patch.py)
51             patch_exe = os.path.join(config.VARS.srcDir, "patching.py")
52             patch_cmd = "python %s -p1 -- < %s" % (patch_exe, patch)
53
54             logger.write(("    >%s\n" % patch_cmd),5)
55             res_cmd = (subprocess.call(patch_cmd, 
56                                    shell=True, 
57                                    cwd=module_info.source_dir,
58                                    stdout=logger.logTxtFile, 
59                                    stderr=subprocess.STDOUT) == 0)        
60         else:
61             res_cmd = False
62             details.append("  " + 
63                 src.printcolors.printcError(_("Not a valid patch: %s") % patch))
64
65         res.append(res_cmd)
66         
67         if res_cmd:
68             message = (_("Apply patch %s") % 
69                        src.printcolors.printcHighlight(patch))
70         else:
71             message = src.printcolors.printcWarning(
72                                         _("Failed to apply patch %s") % patch)
73
74         if config.USER.output_level >= 3:
75             retcode.append("  %s" % message)
76         else:
77             retcode.append("%s: %s" % (module_info.name, message))
78         
79         if len(details) > 0:
80             retcode.extend(details)
81
82     res = not (False in res)
83     
84     return res, "\n".join(retcode) + "\n"
85
86 def description():
87     '''method that is called when salomeTools is called with --help option.
88     
89     :return: The text to display for the patch command description.
90     :rtype: str
91     '''
92     return _("The patch command apply the patches on the sources of "
93              "the application modules if there is any")
94   
95 def run(args, runner, logger):
96     '''method that is called when salomeTools is called with patch parameter.
97     '''
98     # Parse the options
99     (options, args) = parser.parse_args(args)
100     
101     # check that the command has been called with an application
102     src.check_config_has_application( runner.cfg )
103
104     # Print some informations
105     logger.write('Patching sources of the application %s\n' % 
106                 src.printcolors.printcLabel(runner.cfg.VARS.application), 1)
107
108     src.printcolors.print_value(logger, 'out_dir', 
109                                 runner.cfg.APPLICATION.out_dir, 2)
110     logger.write("\n", 2, False)
111
112     # Get the modules to be prepared, regarding the options
113     if options.modules is None:
114         # No options, get all modules sources
115         modules = runner.cfg.APPLICATION.modules
116     else:
117         # if option --modules, check that all modules of the command line
118         # are present in the application.
119         modules = options.modules
120         for m in modules:
121             if m not in runner.cfg.APPLICATION.modules:
122                 raise src.SatException(_("Module %(module)s "
123                             "not defined in appplication %(application)s") %
124                 { 'module': m, 'application': runner.cfg.VARS.application} )
125     
126     # Construct the list of tuple containing 
127     # the modules name and their definition
128     modules_infos = src.module.get_modules_infos(modules, runner.cfg)
129
130     # if the --no_sample option is invoked, suppress the sample modules from 
131     # the list
132     if options.no_sample:
133         modules_infos = filter(lambda l: not src.module.module_is_sample(l[1]),
134                          modules_infos)
135     
136     # Get the maximum name length in order to format the terminal display
137     max_module_name_len = 1
138     if len(modules_infos) > 0:
139         max_module_name_len = max(map(lambda l: len(l), modules_infos[0])) + 4
140     
141     # The loop on all the modules on which to apply the patches
142     good_result = 0
143     for module_name, module_info in modules_infos:
144         # display and log
145         logger.write('%s: ' % src.printcolors.printcLabel(module_name), 3)
146         logger.write(' ' * (max_module_name_len - len(module_name)), 3, False)
147         logger.write("\n", 4, False)
148         return_code, patch_res = apply_patch(runner.cfg, module_info, logger)
149         logger.write(patch_res, 1, False)
150         if return_code:
151             good_result += 1
152     
153     # Display the results (how much passed, how much failed, etc...)
154
155     logger.write("\n", 2, False)
156     if good_result == len(modules_infos):
157         status = src.OK_STATUS
158         res_count = "%d / %d" % (good_result, good_result)
159     else:
160         status = src.KO_STATUS
161         res_count = "%d / %d" % (good_result, len(modules))
162     
163     # write results
164     logger.write("Patching sources of the application:", 1)
165     logger.write(" " + src.printcolors.printc(status), 1, False)
166     logger.write(" (%s)\n" % res_count, 1, False)
167     
168     return len(modules_infos) - good_result