better handling of environment variables, and set more of them
[mass-build.git] / build_system.py
1 import os, shutil, subprocess
2
3 '''A build system must have a "build" method with parameters "reconfigure" and "waitAfterConfig".'''
4
5 # Compile, build, and install cmake projects:
6 class CMake:
7         def __init__(self, sourceFolder, buildFolder, config):
8                 self.sourceFolder = os.path.abspath(sourceFolder)
9                 self.buildFolder = os.path.abspath(buildFolder)
10                 self.config = config
11         
12         def setEnv(self, name, val):
13                 '''Set the given environment variable, return old value'''
14                 oldVal = os.getenv(name)
15                 os.putenv(name, val)
16                 return oldVal
17         
18         def prependDirToEnv(self, name, dir, default):
19                 '''Prepends the given directory to the environment variable. If the variable is empty, dir isprepended to the default.
20                    Returns the old value.'''
21                 oldVal = os.getenv(name)
22                 oldPaths = default if oldVal is None else oldVal
23                 os.putenv(name, dir+':'+oldPaths)
24                 return oldVal
25         
26         def restoreEnv(self, name, oldVal):
27                 '''Restore environment variable to previous value'''
28                 if oldVal is None:
29                         os.unsetenv(name)
30                 else:
31                         os.putenv(name, oldVal)
32         
33         def build(self, reconfigure, waitAfterConfig):
34                 # Make sure we have a build directory
35                 if not os.path.exists(self.buildFolder): os.makedirs(self.buildFolder)
36                 os.chdir(self.buildFolder)
37                 # In case of reconfiguration, delete cache file if it exists
38                 cacheFile = 'CMakeCache.txt'
39                 if os.path.exists(cacheFile) and reconfigure: os.remove(cacheFile)
40                 # Run cmake, in the proper environment, then restore old environment
41                 oldPKGConfigPath = self.setEnv('PKG_CONFIG_PATH', os.path.join(self.config['installDir'], 'lib', 'pkgconfig'))
42                 oldCMakePrefixPath = self.setEnv('CMAKE_PREFIX_PATH', self.config['installDir'])
43                 oldXDGDataDirs = self.prependDirToEnv('XDG_DATA_DIRS', os.path.join(self.config['installDir'], 'share'), '/usr/share')
44                 oldXDGConfigDirs = self.prependDirToEnv('XDG_CONFIG_DIRS', os.path.join(self.config['installDir'], 'etc', 'xdg'), '/etc/xdg')
45                 subprocess.check_call(['cmake', self.sourceFolder, '-DCMAKE_BUILD_TYPE='+self.config['buildType'],
46                         '-DCMAKE_INSTALL_PREFIX='+self.config['installDir']]+self.config.get('cmakeParameters', []))
47                 self.restoreEnv('PKG_CONFIG_PATH', oldPKGConfigPath)
48                 self.restoreEnv('CMAKE_PREFIX_PATH', oldCMakePrefixPath)
49                 self.restoreEnv('XDG_DATA_DIRS', oldXDGDataDirs)
50                 self.restoreEnv('XDG_CONFIG_DIRS', oldXDGConfigDirs)
51                 # if asked to do so, wait
52                 if waitAfterConfig:
53                         raw_input('Configuration done. Hit "Enter" to build the project. ')
54                 # run compilation
55                 subprocess.check_call(self.config.get('buildCmdPrefix', []) + ['make', '-j'+str(self.config['jobs'])])
56                 # run installation
57                 subprocess.check_call(self.config.get('installCmdPrefix', []) + ['make', 'install'])
58
59 # if auto-debuild is available, provide a wrapper for it
60 try:
61         import auto_debuild
62         class AutoDebuild:
63                 def __init__(self, sourceFolder, buildFolder, config, vcs):
64                         self.sourceFolder = os.path.abspath(sourceFolder)
65                         self.buildFolder = os.path.abspath(buildFolder)
66                         self.debFolder = os.path.abspath(config['debDir'])
67                         self.config = config
68                         self.vcs = vcs
69
70                 def build(self, reconfigure, waitAfterConfig): # reconfigure is ignored (we always do a reconfiguration)
71                         # create auto-debuild configuration
72                         versionName = self.config['versionName'] if 'versionName' in self.config else self.vcs.version()
73                         autoDebuildConfig = {
74                                 'sourceName': self.config['name'],
75                                 'buildSystem': self.config['buildSystem'],
76                                 'debDir': self.debFolder,
77                                 'buildDir': self.buildFolder,
78                                 'name': self.config['debName'],
79                                 'email': self.config['debEMail'],
80                                 'parallelJobs': self.config['jobs'],
81                                 'version': versionName,
82                                 'waitAfterConfig': waitAfterConfig,
83                         }
84                         if autoDebuildConfig['version'] is None:
85                                 raise Exception("VCS did not provide us with a proper version number, please fix this")
86                         # copy some more optional configuration
87                         for option in ('dbgPackage', 'section', 'withPython2', 'binarySkipFiles', 'binaryInstallFiles',
88                                         'buildDepends', 'binaryDepends', 'binaryRecommends', 'binaryProvides', 'binaryConflicts', 'binaryBreaks',
89                                         'binaryReplaces', 'binaryBreaksReplaces',
90                                         'alternatives', 'cmakeParameters', 'automakeParameters'):
91                                 if option in self.config:
92                                         autoDebuildConfig[option] = self.config[option]
93                         # create Debian files
94                         os.chdir(self.sourceFolder)
95                         if os.path.isdir('debian'): # clean previous build attempts
96                                 shutil.rmtree('debian')
97                         files = auto_debuild.createDebianFiles(autoDebuildConfig)
98                         # build package(s)
99                         auto_debuild.buildDebianPackage(autoDebuildConfig)
100                         # install package(s)
101                         if self.config.get('debInstall', True):
102                                 subprocess.check_call(['sudo', 'dpkg', '--install'] + files)
103
104 except ImportError:
105         #print "auto_debuild not found, disabling auto-debuild system"
106         pass