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