xref: /petsc/config/install.py (revision d393f697103937f5c80360d45fcf77652c8a7976)
1#!/usr/bin/env python
2import re, os, sys, shutil
3
4if os.environ.has_key('PETSC_DIR'):
5  PETSC_DIR = os.environ['PETSC_DIR']
6else:
7  fd = file(os.path.join('conf','petscvariables'))
8  a = fd.readline()
9  a = fd.readline()
10  PETSC_DIR = a.split('=')[1][0:-1]
11  fd.close()
12
13if os.environ.has_key('PETSC_ARCH'):
14  PETSC_ARCH = os.environ['PETSC_ARCH']
15else:
16  fd = file(os.path.join('conf','petscvariables'))
17  a = fd.readline()
18  PETSC_ARCH = a.split('=')[1][0:-1]
19  fd.close()
20
21print '*** using PETSC_DIR='+PETSC_DIR+' PETSC_ARCH='+PETSC_ARCH+' ***'
22sys.path.insert(0, os.path.join(PETSC_DIR, 'config'))
23sys.path.insert(0, os.path.join(PETSC_DIR, 'config', 'BuildSystem'))
24
25import script
26
27try:
28  WindowsError
29except NameError:
30  WindowsError = None
31
32class Installer(script.Script):
33  def __init__(self, clArgs = None):
34    import RDict
35    argDB = RDict.RDict(None, None, 0, 0, readonly = True)
36    if os.environ.has_key('PETSC_DIR'):
37      PETSC_DIR = os.environ['PETSC_DIR']
38    else:
39      fd = file(os.path.join('conf','petscvariables'))
40      a = fd.readline()
41      a = fd.readline()
42      PETSC_DIR = a.split('=')[1][0:-1]
43      fd.close()
44    argDB.saveFilename = os.path.join(PETSC_DIR, PETSC_ARCH, 'conf', 'RDict.db')
45    argDB.load()
46    script.Script.__init__(self, argDB = argDB)
47    if not clArgs is None: self.clArgs = clArgs
48    self.copies = []
49    return
50
51  def setupHelp(self, help):
52    import nargs
53    script.Script.setupHelp(self, help)
54    help.addArgument('Installer', '-destDir=<path>', nargs.Arg(None, None, 'Destination Directory for install'))
55    return
56
57
58  def setupModules(self):
59    self.setCompilers  = self.framework.require('config.setCompilers',         None)
60    self.arch          = self.framework.require('PETSc.utilities.arch',        None)
61    self.petscdir      = self.framework.require('PETSc.utilities.petscdir',    None)
62    self.makesys       = self.framework.require('config.programs',        None)
63    self.compilers     = self.framework.require('config.compilers',            None)
64    return
65
66  def setup(self):
67    script.Script.setup(self)
68    self.framework = self.loadConfigure()
69    self.setupModules()
70    return
71
72  def setupDirectories(self):
73    self.rootDir    = self.petscdir.dir
74    self.destDir    = os.path.abspath(self.argDB['destDir'])
75    self.installDir = self.framework.argDB['prefix']
76    print self.installDir
77    self.arch       = self.arch.arch
78    self.rootIncludeDir    = os.path.join(self.rootDir, 'include')
79    self.archIncludeDir    = os.path.join(self.rootDir, self.arch, 'include')
80    self.rootConfDir       = os.path.join(self.rootDir, 'conf')
81    self.archConfDir       = os.path.join(self.rootDir, self.arch, 'conf')
82    self.rootBinDir        = os.path.join(self.rootDir, 'bin')
83    self.archBinDir        = os.path.join(self.rootDir, self.arch, 'bin')
84    self.archLibDir        = os.path.join(self.rootDir, self.arch, 'lib')
85    self.destIncludeDir    = os.path.join(self.destDir, 'include')
86    self.destConfDir       = os.path.join(self.destDir, 'conf')
87    self.destLibDir        = os.path.join(self.destDir, 'lib')
88    self.destBinDir        = os.path.join(self.destDir, 'bin')
89    self.installIncludeDir = os.path.join(self.installDir, 'include')
90    self.installBinDir     = os.path.join(self.installDir, 'bin')
91    self.rootShareDir      = os.path.join(self.rootDir, 'share')
92    self.destShareDir      = os.path.join(self.destDir, 'share')
93
94    self.make      = self.makesys.make+' '+self.makesys.flags
95    self.ranlib    = self.compilers.RANLIB
96    self.libSuffix = self.compilers.AR_LIB_SUFFIX
97    return
98
99  def copytree(self, src, dst, symlinks = False, copyFunc = shutil.copy2):
100    """Recursively copy a directory tree using copyFunc, which defaults to shutil.copy2().
101
102    The destination directory must not already exist.
103    If exception(s) occur, an shutil.Error is raised with a list of reasons.
104
105    If the optional symlinks flag is true, symbolic links in the
106    source tree result in symbolic links in the destination tree; if
107    it is false, the contents of the files pointed to by symbolic
108    links are copied.
109    """
110    copies = []
111    names  = os.listdir(src)
112    if not os.path.exists(dst):
113      os.makedirs(dst)
114    elif not os.path.isdir(dst):
115      raise shutil.Error, 'Destination is not a directory'
116    errors = []
117    for name in names:
118      srcname = os.path.join(src, name)
119      dstname = os.path.join(dst, name)
120      try:
121        if symlinks and os.path.islink(srcname):
122          linkto = os.readlink(srcname)
123          os.symlink(linkto, dstname)
124        elif os.path.isdir(srcname):
125          copies.extend(self.copytree(srcname, dstname, symlinks))
126        else:
127          copyFunc(srcname, dstname)
128          copies.append((srcname, dstname))
129        # XXX What about devices, sockets etc.?
130      except (IOError, os.error), why:
131        errors.append((srcname, dstname, str(why)))
132      # catch the Error from the recursive copytree so that we can
133      # continue with other files
134      except shutil.Error, err:
135        errors.extend((srcname,dstname,str(err.args[0])))
136    try:
137      shutil.copystat(src, dst)
138    except OSError, e:
139      if WindowsError is not None and isinstance(e, WindowsError):
140        # Copying file access times may fail on Windows
141        pass
142      else:
143        errors.extend((src, dst, str(e)))
144    if errors:
145      raise shutil.Error, errors
146    return copies
147
148
149  def fixConfFile(self, src):
150    lines   = []
151    oldFile = open(src, 'r')
152    for line in oldFile.readlines():
153      # paths generated by configure could be different link-path than whats used by user, so fix both
154      line = re.sub(re.escape(os.path.join(self.rootDir, self.arch)), self.installDir, line)
155      line = re.sub(re.escape(os.path.realpath(os.path.join(self.rootDir, self.arch))), self.installDir, line)
156      line = re.sub(re.escape(os.path.join(self.rootDir, 'bin')), self.installBinDir, line)
157      line = re.sub(re.escape(os.path.realpath(os.path.join(self.rootDir, 'bin'))), self.installBinDir, line)
158      line = re.sub(re.escape(os.path.join(self.rootDir, 'include')), self.installIncludeDir, line)
159      line = re.sub(re.escape(os.path.realpath(os.path.join(self.rootDir, 'include'))), self.installIncludeDir, line)
160      # remove PETSC_DIR/PETSC_ARCH variables from conf-makefiles. They are no longer necessary
161      line = re.sub('\$\{PETSC_DIR\}/\$\{PETSC_ARCH\}', self.installDir, line)
162      line = re.sub('PETSC_ARCH=\$\{PETSC_ARCH\}', '', line)
163      line = re.sub('\$\{PETSC_DIR\}', self.installDir, line)
164      lines.append(line)
165    oldFile.close()
166    newFile = open(src, 'w')
167    newFile.write(''.join(lines))
168    newFile.close()
169    return
170
171  def fixConf(self):
172    import shutil
173    # copy standard rules and variables file so that we can change them in place
174    for file in ['rules', 'variables']:
175      shutil.copy2(os.path.join(self.rootConfDir,file),os.path.join(self.archConfDir,file))
176    for file in ['rules', 'variables','petscrules', 'petscvariables']:
177      self.fixConfFile(os.path.join(self.archConfDir,file))
178
179  def createUninstaller(self):
180    uninstallscript = os.path.join(self.archConfDir, 'uninstall.py')
181    f = open(uninstallscript, 'w')
182    # Could use the Python AST to do this
183    f.write('#!'+sys.executable+'\n')
184    f.write('import os\n')
185
186    f.write('copies = '+re.sub(self.destDir,self.installDir,repr(self.copies)))
187    f.write('''
188for src, dst in copies:
189  if os.path.exists(dst):
190    os.remove(dst)
191''')
192    f.close()
193    os.chmod(uninstallscript,0744)
194    return
195
196  def installIncludes(self):
197    self.copies.extend(self.copytree(self.rootIncludeDir, self.destIncludeDir))
198    self.copies.extend(self.copytree(self.archIncludeDir, self.destIncludeDir))
199    return
200
201  def installConf(self):
202    self.copies.extend(self.copytree(self.rootConfDir, self.destConfDir))
203    self.copies.extend(self.copytree(self.archConfDir, self.destConfDir))
204
205  def installBin(self):
206    self.copies.extend(self.copytree(self.rootBinDir, self.destBinDir))
207    self.copies.extend(self.copytree(self.archBinDir, self.destBinDir))
208    return
209
210  def installShare(self):
211    self.copies.extend(self.copytree(self.rootShareDir, self.destShareDir))
212    return
213
214  def copyLib(self, src, dst):
215    '''Run ranlib on the destination library if it is an archive. Also run install_name_tool on dylib on Mac'''
216    shutil.copy2(src, dst)
217    if os.path.splitext(dst)[1] == '.'+self.libSuffix:
218      self.executeShellCommand(self.ranlib+' '+dst)
219    if os.path.splitext(dst)[1] == '.dylib' and os.path.isfile('/usr/bin/install_name_tool'):
220      installName = re.sub(self.destDir, self.installDir, dst)
221      self.executeShellCommand('/usr/bin/install_name_tool -id ' + installName + ' ' + dst)
222    return
223
224  def installLib(self):
225    self.copies.extend(self.copytree(self.archLibDir, self.destLibDir, copyFunc = self.copyLib))
226    return
227
228
229  def outputDone(self):
230    print '''\
231====================================
232Install complete. It is useable with PETSC_DIR=%s [and no more PETSC_ARCH].
233Now to check if the libraries are working do (in current directory):
234make PETSC_DIR=%s test
235====================================\
236''' % (self.installDir,self.installDir)
237    return
238
239  def runfix(self):
240    self.setup()
241    self.setupDirectories()
242    self.createUninstaller()
243    self.fixConf()
244
245  def runcopy(self):
246    if os.path.exists(self.destDir) and os.path.samefile(self.destDir, os.path.join(self.rootDir,self.arch)):
247      print '********************************************************************'
248      print 'Install directory is current directory; nothing needs to be done'
249      print '********************************************************************'
250      return
251    print '*** Installing PETSc at',self.destDir, ' ***'
252    if not os.path.exists(self.destDir):
253      try:
254        os.makedirs(self.destDir)
255      except:
256        print '********************************************************************'
257        print 'Unable to create', self.destDir, 'Perhaps you need to do "sudo make install"'
258        print '********************************************************************'
259        return
260    if not os.path.isdir(os.path.realpath(self.destDir)):
261      print '********************************************************************'
262      print 'Specified destDir', self.destDir, 'is not a directory. Cannot proceed!'
263      print '********************************************************************'
264      return
265    if not os.access(self.destDir, os.W_OK):
266      print '********************************************************************'
267      print 'Unable to write to ', self.destDir, 'Perhaps you need to do "sudo make install"'
268      print '********************************************************************'
269      return
270
271    self.installIncludes()
272    self.installConf()
273    self.installBin()
274    self.installLib()
275    self.installShare()
276    self.outputDone()
277
278    return
279
280  def run(self):
281    self.runfix()
282    self.runcopy()
283
284if __name__ == '__main__':
285  Installer(sys.argv[1:]).run()
286  # temporary hack - delete log files created by BuildSystem - when 'sudo make install' is invoked
287  delfiles=['RDict.db','RDict.log','build.log','default.log','build.log.bkp','default.log.bkp']
288  for delfile in delfiles:
289    if os.path.exists(delfile) and (os.stat(delfile).st_uid==0):
290      os.remove(delfile)
291