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