]> SALOME platform Git repositories - tools/sat.git/blob - src/compilation.py
Salome HOME
use shutil.move instead of os.remove
[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         if res == 0:
133             self.put_txt_log_in_appli_log_dir("cmake")
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
156         if res == 0:
157             self.put_txt_log_in_appli_log_dir("build_configure")
158             return res
159         else:
160             return 1
161
162     ##
163     # Runs configure with the given options.
164     def configure(self, options=""):
165
166         if 'configure_options' in self.product_info:
167             options += " %s " % self.product_info.configure_options
168
169         command = "%s/configure --prefix=%s" % (self.source_dir, str(self.install_dir))
170
171         command = command + " " + options
172         self.log_command(command)
173
174         res = subprocess.call(command,
175                               shell=True,
176                               cwd=str(self.build_dir),
177                               env=self.build_environ.environ.environ,
178                               stdout=self.logger.logTxtFile,
179                               stderr=subprocess.STDOUT)
180
181         if res == 0:
182             self.put_txt_log_in_appli_log_dir("configure")
183             return res
184         else:
185             return 1
186
187     def hack_libtool(self):
188         if not os.path.exists(str(self.build_dir + 'libtool')):
189             return
190
191         lf = open(os.path.join(str(self.build_dir), "libtool"), 'r')
192         for line in lf.readlines():
193             if 'hack_libtool' in line:
194                 return
195
196         # fix libtool by replacing CC="<compil>" with hack_libtool function
197         hack_command='''sed -i "s%^CC=\\"\(.*\)\\"%hack_libtool() { \\n\\
198 if test \\"\$(echo \$@ | grep -E '\\\\\\-L/usr/lib(/../lib)?(64)? ')\\" == \\\"\\\" \\n\\
199   then\\n\\
200     cmd=\\"\\1 \$@\\"\\n\\
201   else\\n\\
202     cmd=\\"\\1 \\"\`echo \$@ | sed -r -e 's|(.*)-L/usr/lib(/../lib)?(64)? (.*)|\\\\\\1\\\\\\4 -L/usr/lib\\\\\\3|g'\`\\n\\
203   fi\\n\\
204   \$cmd\\n\\
205 }\\n\\
206 CC=\\"hack_libtool\\"%g" libtool'''
207
208         self.log_command(hack_command)
209         subprocess.call(hack_command,
210                         shell=True,
211                         cwd=str(self.build_dir),
212                         env=self.build_environ.environ.environ,
213                         stdout=self.logger.logTxtFile,
214                         stderr=subprocess.STDOUT)
215
216
217     ##
218     # Runs make to build the module.
219     def make(self, nb_proc, make_opt=""):
220
221         # make
222         command = 'make'
223         command = command + " -j" + str(nb_proc)
224         command = command + " " + make_opt
225         self.log_command(command)
226         res = subprocess.call(command,
227                               shell=True,
228                               cwd=str(self.build_dir),
229                               env=self.build_environ.environ.environ,
230                               stdout=self.logger.logTxtFile,
231                               stderr=subprocess.STDOUT)
232
233         if res == 0:
234             self.put_txt_log_in_appli_log_dir("make")
235             return res
236         else:
237             return 1
238     
239     ##
240     # Runs msbuild to build the module.
241     def wmake(self, opt_nb_proc = None):
242         nbproc = self.get_nb_proc(opt_nb_proc)
243
244         hh = 'MSBUILD /m:%s' % str(nbproc)
245         if self.debug_mode:
246             hh += " " + src.printcolors.printcWarning("DEBUG")
247         self.log_step(hh)
248
249         # make
250         command = 'msbuild'
251         if self.options.makeflags:
252             command = command + " " + self.options.makeflags
253         command = command + " /maxcpucount:" + str(nbproc)
254         if self.debug_mode:
255             command = command + " /p:Configuration=Debug"
256         else:
257             command = command + " /p:Configuration=Release"
258         command = command + " ALL_BUILD.vcxproj"
259
260         self.log_command(command)
261         res = subprocess.call(command,
262                               shell=True,
263                               cwd=str(self.build_dir),
264                               env=self.build_environ.environ.environ,
265                               stdout=self.logger.logTxtFile,
266                               stderr=subprocess.STDOUT)
267
268         if res == 0:
269             self.put_txt_log_in_appli_log_dir("make")
270             return res
271         else:
272             return 1
273
274     ##
275     # Runs 'make install'.
276     def install(self):
277         if self.config.VARS.dist_name=="Win":
278             command = 'msbuild INSTALL.vcxproj'
279             if self.debug_mode:
280                 command = command + " /p:Configuration=Debug"
281             else:
282                 command = command + " /p:Configuration=Release"
283         else :
284             command = 'make install'
285
286         self.log_command(command)
287
288         res = subprocess.call(command,
289                               shell=True,
290                               cwd=str(self.build_dir),
291                               env=self.build_environ.environ.environ,
292                               stdout=self.logger.logTxtFile,
293                               stderr=subprocess.STDOUT)
294
295         if res == 0:
296             self.put_txt_log_in_appli_log_dir("makeinstall")
297             return res
298         else:
299             return 1
300
301     ##
302     # Runs 'make_check'.
303     def check(self):
304         if src.architecture.is_windows():
305             command = 'msbuild RUN_TESTS.vcxproj'
306         else :
307             if self.product_info.build_source=="autotools" :
308                 command = 'make check'
309             else:
310                 command = 'make test'
311             
312         self.log_command(command)
313
314         res = subprocess.call(command,
315                               shell=True,
316                               cwd=str(self.build_dir),
317                               env=self.launch_environ.environ.environ,
318                               stdout=self.logger.logTxtFile,
319                               stderr=subprocess.STDOUT)
320
321         if res == 0:
322             return res
323         else:
324             return 1
325       
326     ##
327     # Performs a default build for this module.
328     def do_default_build(self, build_conf_options="", configure_options="", show_warning=True):
329         use_autotools = False
330         if 'use_autotools' in self.product_info:
331             uc = self.product_info.use_autotools
332             if uc in ['always', 'yes']: 
333                 use_autotools = True
334             elif uc == 'option': 
335                 use_autotools = self.options.autotools
336
337
338         self.use_autotools = use_autotools
339
340         use_ctest = False
341         if 'use_ctest' in self.product_info:
342             uc = self.product_info.use_ctest
343             if uc in ['always', 'yes']: 
344                 use_ctest = True
345             elif uc == 'option': 
346                 use_ctest = self.options.ctest
347
348         self.use_ctest = use_ctest
349
350         if show_warning:
351             cmd = ""
352             if use_autotools: cmd = "(autotools)"
353             if use_ctest: cmd = "(ctest)"
354             
355             self.log("\n", 4, False)
356             self.log("%(module)s: Run default compilation method %(cmd)s\n" % \
357                 { "module": self.module, "cmd": cmd }, 4)
358
359         if use_autotools:
360             if not self.prepare(): return self.get_result()
361             if not self.build_configure(build_conf_options): return self.get_result()
362             if not self.configure(configure_options): return self.get_result()
363             if not self.make(): return self.get_result()
364             if not self.install(): return self.get_result()
365             if not self.clean(): return self.get_result()
366            
367         else: # CMake
368             if self.config.VARS.dist_name=='Win':
369                 if not self.wprepare(): return self.get_result()
370                 if not self.cmake(): return self.get_result()
371                 if not self.wmake(): return self.get_result()
372                 if not self.install(): return self.get_result()
373                 if not self.clean(): return self.get_result()
374             else :
375                 if not self.prepare(): return self.get_result()
376                 if not self.cmake(): return self.get_result()
377                 if not self.make(): return self.get_result()
378                 if not self.install(): return self.get_result()
379                 if not self.clean(): return self.get_result()
380
381         return self.get_result()
382
383     ##
384     # Performs a build with a script.
385     def do_python_script_build(self, script, nb_proc):
386         # script found
387         self.logger.write(_("Compile %(product)s using script %(script)s\n") % \
388             { 'product': self.product_info.name,
389              'script': src.printcolors.printcLabel(script) }, 4)
390         try:
391             import imp
392             product = self.product_info.name
393             pymodule = imp.load_source(product + "_compile_script", script)
394             self.nb_proc = nb_proc
395             retcode = pymodule.compil(self.config, self, self.logger)
396             self.put_txt_log_in_appli_log_dir("script")
397         except:
398             __, exceptionValue, exceptionTraceback = sys.exc_info()
399             self.logger.write(str(exceptionValue), 1)
400             import traceback
401             traceback.print_tb(exceptionTraceback)
402             traceback.print_exc()
403             retcode = 1
404
405         return retcode
406
407     def complete_environment(self, make_options):
408         assert self.build_environ is not None
409         # pass additional variables to environment (may be used by the build script)
410         self.build_environ.set("SOURCE_DIR", str(self.source_dir))
411         self.build_environ.set("INSTALL_DIR", str(self.install_dir))
412         self.build_environ.set("PRODUCT_INSTALL", str(self.install_dir))
413         self.build_environ.set("BUILD_DIR", str(self.build_dir))
414         self.build_environ.set("PRODUCT_BUILD", str(self.build_dir))
415         self.build_environ.set("MAKE_OPTIONS", make_options)
416         self.build_environ.set("DIST_NAME", self.config.VARS.dist_name)
417         self.build_environ.set("DIST_VERSION", self.config.VARS.dist_version)
418         self.build_environ.set("DIST", self.config.VARS.dist)
419         self.build_environ.set("VERSION", self.product_info.version)
420
421     def do_batch_script_build(self, script, nb_proc):
422
423         if src.architecture.is_windows():
424             make_options = "/maxcpucount:%s" % nb_proc
425         else :
426             make_options = "-j%s" % nb_proc
427
428         self.log_command("  " + _("Run build script %s\n") % script)
429         self.complete_environment(make_options)
430         res = subprocess.call(script, 
431                               shell=True,
432                               stdout=self.logger.logTxtFile,
433                               stderr=subprocess.STDOUT,
434                               cwd=str(self.build_dir), 
435                               env=self.build_environ.environ.environ)
436
437         if res == 0:
438             self.put_txt_log_in_appli_log_dir("script")
439             return res
440         else:
441             return 1
442     
443     def do_script_build(self, script, number_of_proc=0):
444         # define make options (may not be used by the script)
445         if number_of_proc==0:
446             nb_proc = src.get_cfg_param(self.product_info,"nb_proc", 0)
447             if nb_proc == 0: 
448                 nb_proc = self.config.VARS.nb_proc
449         else:
450             nb_proc = min(number_of_proc, self.config.VARS.nb_proc)
451             
452         extension = script.split('.')[-1]
453         if extension in ["bat","sh"]:
454             return self.do_batch_script_build(script, nb_proc)
455         if extension == "py":
456             return self.do_python_script_build(script, nb_proc)
457         
458         msg = _("The script %s must have .sh, .bat or .py extension." % script)
459         raise src.SatException(msg)
460     
461     def put_txt_log_in_appli_log_dir(self, file_name):
462         '''Put the txt log (that contain the system logs, like make command
463            output) in the directory <APPLICATION DIR>/LOGS/<product_name>/
464     
465         :param file_name Str: the name of the file to write
466         '''
467         if self.logger.logTxtFile == sys.__stdout__:
468             return
469         dir_where_to_put = os.path.join(self.config.APPLICATION.workdir,
470                                         "LOGS",
471                                         self.product_info.name)
472         file_path = os.path.join(dir_where_to_put, file_name)
473         src.ensure_path_exists(dir_where_to_put)
474         # write the logTxtFile copy it to the destination, and then recreate 
475         # it as it was
476         self.logger.logTxtFile.close()
477         shutil.move(self.logger.txtFilePath, file_path)
478         self.logger.logTxtFile = open(str(self.logger.txtFilePath), 'w')
479         self.logger.logTxtFile.write(open(file_path, "r").read())
480