Salome HOME
write compilation log enven if the compilation fails
[tools/sat.git] / src / compilation.py
1 #!/usr/bin/env python
2 #-*- coding:utf-8 -*-
3 #  Copyright (C) 2010-2013  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 sys
22 import shutil
23
24 import src
25
26 C_COMPILE_ENV_LIST = ["CC",
27                       "CXX",
28                       "F77",
29                       "CFLAGS",
30                       "CXXFLAGS",
31                       "LIBS",
32                       "LDFLAGS"]
33
34 class Builder:
35     """Class to handle all construction steps, like cmake, configure, make, ...
36     """
37     def __init__(self,
38                  config,
39                  logger,
40                  product_info,
41                  options = src.options.OptResult(),
42                  check_src=True):
43         self.config = config
44         self.logger = logger
45         self.options = options
46         self.product_info = product_info
47         self.build_dir = src.Path(self.product_info.build_dir)
48         self.source_dir = src.Path(self.product_info.source_dir)
49         self.install_dir = src.Path(self.product_info.install_dir)
50         self.header = ""
51         self.debug_mode = False
52         if "debug" in self.product_info and self.product_info.debug == "yes":
53             self.debug_mode = True
54
55     ##
56     # Shortcut method to log in log file.
57     def log(self, text, level, showInfo=True):
58         self.logger.write(text, level, showInfo)
59         self.logger.logTxtFile.write(src.printcolors.cleancolor(text))
60         self.logger.flush()
61
62     ##
63     # Shortcut method to log a command.
64     def log_command(self, command):
65         self.log("> %s\n" % command, 5)
66
67     ##
68     # Prepares the environment.
69     # Build two environment: one for building and one for testing (launch).
70     def prepare(self):
71
72         if not self.build_dir.exists():
73             # create build dir
74             self.build_dir.make()
75
76         self.log('  build_dir   = %s\n' % str(self.build_dir), 4)
77         self.log('  install_dir = %s\n' % str(self.install_dir), 4)
78         self.log('\n', 4)
79
80         # add products in depend and opt_depend list recursively
81         environ_info = src.product.get_product_dependencies(self.config,
82                                                             self.product_info)
83         #environ_info.append(self.product_info.name)
84
85         # create build environment
86         self.build_environ = src.environment.SalomeEnviron(self.config,
87                                       src.environment.Environ(dict(os.environ)),
88                                       True)
89         self.build_environ.silent = (self.config.USER.output_verbose_level < 5)
90         self.build_environ.set_full_environ(self.logger, environ_info)
91         
92         # create runtime environment
93         self.launch_environ = src.environment.SalomeEnviron(self.config,
94                                       src.environment.Environ(dict(os.environ)),
95                                       False)
96         self.launch_environ.silent = True # no need to show here
97         self.launch_environ.set_full_environ(self.logger, environ_info)
98
99         for ee in C_COMPILE_ENV_LIST:
100             vv = self.build_environ.get(ee)
101             if len(vv) > 0:
102                 self.log("  %s = %s\n" % (ee, vv), 4, False)
103
104         return 0
105
106     ##
107     # Runs cmake with the given options.
108     def cmake(self, options=""):
109
110         cmake_option = options
111         # cmake_option +=' -DCMAKE_VERBOSE_MAKEFILE=ON -DSALOME_CMAKE_DEBUG=ON'
112         if 'cmake_options' in self.product_info:
113             cmake_option += " %s " % " ".join(self.product_info.cmake_options.split())
114
115         # add debug option
116         if self.debug_mode:
117             cmake_option += " -DCMAKE_BUILD_TYPE=Debug"
118         else :
119             cmake_option += " -DCMAKE_BUILD_TYPE=Release"
120         
121         command = ("cmake %s -DCMAKE_INSTALL_PREFIX=%s %s" %
122                             (cmake_option, self.install_dir, self.source_dir))
123
124         self.log_command(command)
125         res = subprocess.call(command,
126                               shell=True,
127                               cwd=str(self.build_dir),
128                               env=self.build_environ.environ.environ,
129                               stdout=self.logger.logTxtFile,
130                               stderr=subprocess.STDOUT)
131
132         self.put_txt_log_in_appli_log_dir("cmake")
133         if res == 0:
134             return res
135         else:
136             return 1
137
138     ##
139     # Runs build_configure with the given options.
140     def build_configure(self, options=""):
141
142         if 'buildconfigure_options' in self.product_info:
143             options += " %s " % self.product_info.buildconfigure_options
144
145         command = str('%s/build_configure') % (self.source_dir)
146         command = command + " " + options
147         self.log_command(command)
148
149         res = subprocess.call(command,
150                               shell=True,
151                               cwd=str(self.build_dir),
152                               env=self.build_environ.environ.environ,
153                               stdout=self.logger.logTxtFile,
154                               stderr=subprocess.STDOUT)
155         self.put_txt_log_in_appli_log_dir("build_configure")
156         if res == 0:
157             return res
158         else:
159             return 1
160
161     ##
162     # Runs configure with the given options.
163     def configure(self, options=""):
164
165         if 'configure_options' in self.product_info:
166             options += " %s " % self.product_info.configure_options
167
168         command = "%s/configure --prefix=%s" % (self.source_dir, str(self.install_dir))
169
170         command = command + " " + options
171         self.log_command(command)
172
173         res = subprocess.call(command,
174                               shell=True,
175                               cwd=str(self.build_dir),
176                               env=self.build_environ.environ.environ,
177                               stdout=self.logger.logTxtFile,
178                               stderr=subprocess.STDOUT)
179         
180         self.put_txt_log_in_appli_log_dir("configure")
181         if res == 0:
182             return res
183         else:
184             return 1
185
186     def hack_libtool(self):
187         if not os.path.exists(str(self.build_dir + 'libtool')):
188             return
189
190         lf = open(os.path.join(str(self.build_dir), "libtool"), 'r')
191         for line in lf.readlines():
192             if 'hack_libtool' in line:
193                 return
194
195         # fix libtool by replacing CC="<compil>" with hack_libtool function
196         hack_command='''sed -i "s%^CC=\\"\(.*\)\\"%hack_libtool() { \\n\\
197 if test \\"\$(echo \$@ | grep -E '\\\\\\-L/usr/lib(/../lib)?(64)? ')\\" == \\\"\\\" \\n\\
198   then\\n\\
199     cmd=\\"\\1 \$@\\"\\n\\
200   else\\n\\
201     cmd=\\"\\1 \\"\`echo \$@ | sed -r -e 's|(.*)-L/usr/lib(/../lib)?(64)? (.*)|\\\\\\1\\\\\\4 -L/usr/lib\\\\\\3|g'\`\\n\\
202   fi\\n\\
203   \$cmd\\n\\
204 }\\n\\
205 CC=\\"hack_libtool\\"%g" libtool'''
206
207         self.log_command(hack_command)
208         subprocess.call(hack_command,
209                         shell=True,
210                         cwd=str(self.build_dir),
211                         env=self.build_environ.environ.environ,
212                         stdout=self.logger.logTxtFile,
213                         stderr=subprocess.STDOUT)
214
215
216     ##
217     # Runs make to build the module.
218     def make(self, nb_proc, make_opt=""):
219
220         # make
221         command = 'make'
222         command = command + " -j" + str(nb_proc)
223         command = command + " " + make_opt
224         self.log_command(command)
225         res = subprocess.call(command,
226                               shell=True,
227                               cwd=str(self.build_dir),
228                               env=self.build_environ.environ.environ,
229                               stdout=self.logger.logTxtFile,
230                               stderr=subprocess.STDOUT)
231         self.put_txt_log_in_appli_log_dir("make")
232         if res == 0:
233             return res
234         else:
235             return 1
236     
237     ##
238     # Runs msbuild to build the module.
239     def wmake(self, opt_nb_proc = None):
240         nbproc = self.get_nb_proc(opt_nb_proc)
241
242         hh = 'MSBUILD /m:%s' % str(nbproc)
243         if self.debug_mode:
244             hh += " " + src.printcolors.printcWarning("DEBUG")
245         self.log_step(hh)
246
247         # make
248         command = 'msbuild'
249         if self.options.makeflags:
250             command = command + " " + self.options.makeflags
251         command = command + " /maxcpucount:" + str(nbproc)
252         if self.debug_mode:
253             command = command + " /p:Configuration=Debug"
254         else:
255             command = command + " /p:Configuration=Release"
256         command = command + " ALL_BUILD.vcxproj"
257
258         self.log_command(command)
259         res = subprocess.call(command,
260                               shell=True,
261                               cwd=str(self.build_dir),
262                               env=self.build_environ.environ.environ,
263                               stdout=self.logger.logTxtFile,
264                               stderr=subprocess.STDOUT)
265         
266         self.put_txt_log_in_appli_log_dir("make")
267         if res == 0:
268             return res
269         else:
270             return 1
271
272     ##
273     # Runs 'make install'.
274     def install(self):
275         if self.config.VARS.dist_name=="Win":
276             command = 'msbuild INSTALL.vcxproj'
277             if self.debug_mode:
278                 command = command + " /p:Configuration=Debug"
279             else:
280                 command = command + " /p:Configuration=Release"
281         else :
282             command = 'make install'
283
284         self.log_command(command)
285
286         res = subprocess.call(command,
287                               shell=True,
288                               cwd=str(self.build_dir),
289                               env=self.build_environ.environ.environ,
290                               stdout=self.logger.logTxtFile,
291                               stderr=subprocess.STDOUT)
292         
293         self.put_txt_log_in_appli_log_dir("makeinstall")
294         if res == 0:
295             return res
296         else:
297             return 1
298
299     ##
300     # Runs 'make_check'.
301     def check(self):
302         if src.architecture.is_windows():
303             command = 'msbuild RUN_TESTS.vcxproj'
304         else :
305             if self.product_info.build_source=="autotools" :
306                 command = 'make check'
307             else:
308                 command = 'make test'
309             
310         self.log_command(command)
311
312         res = subprocess.call(command,
313                               shell=True,
314                               cwd=str(self.build_dir),
315                               env=self.launch_environ.environ.environ,
316                               stdout=self.logger.logTxtFile,
317                               stderr=subprocess.STDOUT)
318
319         if res == 0:
320             return res
321         else:
322             return 1
323       
324     ##
325     # Performs a default build for this module.
326     def do_default_build(self, build_conf_options="", configure_options="", show_warning=True):
327         use_autotools = False
328         if 'use_autotools' in self.product_info:
329             uc = self.product_info.use_autotools
330             if uc in ['always', 'yes']: 
331                 use_autotools = True
332             elif uc == 'option': 
333                 use_autotools = self.options.autotools
334
335
336         self.use_autotools = use_autotools
337
338         use_ctest = False
339         if 'use_ctest' in self.product_info:
340             uc = self.product_info.use_ctest
341             if uc in ['always', 'yes']: 
342                 use_ctest = True
343             elif uc == 'option': 
344                 use_ctest = self.options.ctest
345
346         self.use_ctest = use_ctest
347
348         if show_warning:
349             cmd = ""
350             if use_autotools: cmd = "(autotools)"
351             if use_ctest: cmd = "(ctest)"
352             
353             self.log("\n", 4, False)
354             self.log("%(module)s: Run default compilation method %(cmd)s\n" % \
355                 { "module": self.module, "cmd": cmd }, 4)
356
357         if use_autotools:
358             if not self.prepare(): return self.get_result()
359             if not self.build_configure(build_conf_options): return self.get_result()
360             if not self.configure(configure_options): return self.get_result()
361             if not self.make(): return self.get_result()
362             if not self.install(): return self.get_result()
363             if not self.clean(): return self.get_result()
364            
365         else: # CMake
366             if self.config.VARS.dist_name=='Win':
367                 if not self.wprepare(): return self.get_result()
368                 if not self.cmake(): return self.get_result()
369                 if not self.wmake(): return self.get_result()
370                 if not self.install(): return self.get_result()
371                 if not self.clean(): return self.get_result()
372             else :
373                 if not self.prepare(): return self.get_result()
374                 if not self.cmake(): return self.get_result()
375                 if not self.make(): return self.get_result()
376                 if not self.install(): return self.get_result()
377                 if not self.clean(): return self.get_result()
378
379         return self.get_result()
380
381     ##
382     # Performs a build with a script.
383     def do_python_script_build(self, script, nb_proc):
384         # script found
385         self.logger.write(_("Compile %(product)s using script %(script)s\n") % \
386             { 'product': self.product_info.name,
387              'script': src.printcolors.printcLabel(script) }, 4)
388         try:
389             import imp
390             product = self.product_info.name
391             pymodule = imp.load_source(product + "_compile_script", script)
392             self.nb_proc = nb_proc
393             retcode = pymodule.compil(self.config, self, self.logger)
394         except:
395             __, exceptionValue, exceptionTraceback = sys.exc_info()
396             self.logger.write(str(exceptionValue), 1)
397             import traceback
398             traceback.print_tb(exceptionTraceback)
399             traceback.print_exc()
400             retcode = 1
401         finally:
402             self.put_txt_log_in_appli_log_dir("script")
403
404         return retcode
405
406     def complete_environment(self, make_options):
407         assert self.build_environ is not None
408         # pass additional variables to environment (may be used by the build script)
409         self.build_environ.set("SOURCE_DIR", str(self.source_dir))
410         self.build_environ.set("INSTALL_DIR", str(self.install_dir))
411         self.build_environ.set("PRODUCT_INSTALL", str(self.install_dir))
412         self.build_environ.set("BUILD_DIR", str(self.build_dir))
413         self.build_environ.set("PRODUCT_BUILD", str(self.build_dir))
414         self.build_environ.set("MAKE_OPTIONS", make_options)
415         self.build_environ.set("DIST_NAME", self.config.VARS.dist_name)
416         self.build_environ.set("DIST_VERSION", self.config.VARS.dist_version)
417         self.build_environ.set("DIST", self.config.VARS.dist)
418         self.build_environ.set("VERSION", self.product_info.version)
419
420     def do_batch_script_build(self, script, nb_proc):
421
422         if src.architecture.is_windows():
423             make_options = "/maxcpucount:%s" % nb_proc
424         else :
425             make_options = "-j%s" % nb_proc
426
427         self.log_command("  " + _("Run build script %s\n") % script)
428         self.complete_environment(make_options)
429         res = subprocess.call(script, 
430                               shell=True,
431                               stdout=self.logger.logTxtFile,
432                               stderr=subprocess.STDOUT,
433                               cwd=str(self.build_dir), 
434                               env=self.build_environ.environ.environ)
435
436         self.put_txt_log_in_appli_log_dir("script")
437         if res == 0:
438             return res
439         else:
440             return 1
441     
442     def do_script_build(self, script, number_of_proc=0):
443         # define make options (may not be used by the script)
444         if number_of_proc==0:
445             nb_proc = src.get_cfg_param(self.product_info,"nb_proc", 0)
446             if nb_proc == 0: 
447                 nb_proc = self.config.VARS.nb_proc
448         else:
449             nb_proc = min(number_of_proc, self.config.VARS.nb_proc)
450             
451         extension = script.split('.')[-1]
452         if extension in ["bat","sh"]:
453             return self.do_batch_script_build(script, nb_proc)
454         if extension == "py":
455             return self.do_python_script_build(script, nb_proc)
456         
457         msg = _("The script %s must have .sh, .bat or .py extension." % script)
458         raise src.SatException(msg)
459     
460     def put_txt_log_in_appli_log_dir(self, file_name):
461         '''Put the txt log (that contain the system logs, like make command
462            output) in the directory <APPLICATION DIR>/LOGS/<product_name>/
463     
464         :param file_name Str: the name of the file to write
465         '''
466         if self.logger.logTxtFile == sys.__stdout__:
467             return
468         dir_where_to_put = os.path.join(self.config.APPLICATION.workdir,
469                                         "LOGS",
470                                         self.product_info.name)
471         file_path = os.path.join(dir_where_to_put, file_name)
472         src.ensure_path_exists(dir_where_to_put)
473         # write the logTxtFile copy it to the destination, and then recreate 
474         # it as it was
475         self.logger.logTxtFile.close()
476         shutil.move(self.logger.txtFilePath, file_path)
477         self.logger.logTxtFile = open(str(self.logger.txtFilePath), 'w')
478         self.logger.logTxtFile.write(open(file_path, "r").read())
479