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