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