xref: /petsc/config/install.py (revision 08917f38f07ae8f31cafc0a85f43479d150262bd)
1#!/usr/bin/env python
2import re, os, sys, shutil
3
4configDir = os.path.abspath('config')
5sys.path.insert(0, configDir)
6bsDir     = os.path.abspath(os.path.join(configDir, 'BuildSystem'))
7sys.path.insert(0, bsDir)
8
9import script
10
11class Installer(script.Script):
12  def __init__(self, clArgs = None):
13    import RDict
14    script.Script.__init__(self, clArgs, RDict.RDict())
15    self.copies = []
16    return
17
18  def setupHelp(self, help):
19    import nargs
20
21    script.Script.setupHelp(self, help)
22    help.addArgument('Installer', '-rootDir=<path>', nargs.Arg(None, None, 'Install Root Directory'))
23    help.addArgument('Installer', '-installDir=<path>', nargs.Arg(None, None, 'Install Target Directory'))
24    help.addArgument('Installer', '-arch=<type>', nargs.Arg(None, None, 'Architecture type'))
25    help.addArgument('Installer', '-ranlib=<prog>', nargs.Arg(None, 'ranlib', 'Ranlib program'))
26    help.addArgument('Installer', '-make=<prog>', nargs.Arg(None, 'make', 'Make program'))
27    help.addArgument('Installer', '-libSuffix=<ext>', nargs.Arg(None, 'make', 'The static library suffix'))
28    return
29
30  def setupDirectories(self):
31    self.rootDir    = os.path.abspath(self.argDB['rootDir'])
32    self.installDir = os.path.abspath(self.argDB['installDir'])
33    self.arch       = self.argDB['arch']
34    self.ranlib     = self.argDB['ranlib']
35    self.make       = self.argDB['make']
36    self.libSuffix  = self.argDB['libSuffix']
37    self.rootIncludeDir    = os.path.join(self.rootDir, 'include')
38    self.archIncludeDir    = os.path.join(self.rootDir, self.arch, 'include')
39    self.rootConfDir       = os.path.join(self.rootDir, 'conf')
40    self.archConfDir       = os.path.join(self.rootDir, self.arch, 'conf')
41    self.rootBinDir        = os.path.join(self.rootDir, 'bin')
42    self.archBinDir        = os.path.join(self.rootDir, self.arch, 'bin')
43    self.archLibDir        = os.path.join(self.rootDir, self.arch, 'lib')
44    self.installIncludeDir = os.path.join(self.installDir, 'include')
45    self.installConfDir    = os.path.join(self.installDir, 'conf')
46    self.installLibDir     = os.path.join(self.installDir, 'lib')
47    self.installBinDir     = os.path.join(self.installDir, 'bin')
48    return
49
50  def copytree(self, src, dst, symlinks = False, copyFunc = shutil.copy2):
51    """Recursively copy a directory tree using copyFunc, which defaults to shutil.copy2().
52
53    The destination directory must not already exist.
54    If exception(s) occur, an shutil.Error is raised with a list of reasons.
55
56    If the optional symlinks flag is true, symbolic links in the
57    source tree result in symbolic links in the destination tree; if
58    it is false, the contents of the files pointed to by symbolic
59    links are copied.
60    """
61    copies = []
62    names  = os.listdir(src)
63    if not os.path.exists(dst):
64      os.makedirs(dst)
65    elif not os.path.isdir(dst):
66      raise shutil.Error, 'Destination is not a directory'
67    errors = []
68    for name in names:
69      srcname = os.path.join(src, name)
70      dstname = os.path.join(dst, name)
71      try:
72        if symlinks and os.path.islink(srcname):
73          linkto = os.readlink(srcname)
74          os.symlink(linkto, dstname)
75        elif os.path.isdir(srcname):
76          copies.extend(self.copytree(srcname, dstname, symlinks))
77        else:
78          copyFunc(srcname, dstname)
79          copies.append((srcname, dstname))
80        # XXX What about devices, sockets etc.?
81      except (IOError, os.error), why:
82        errors.append((srcname, dstname, str(why)))
83      # catch the Error from the recursive copytree so that we can
84      # continue with other files
85      except shutil.Error, err:
86        errors.extend(err.args[0])
87    try:
88      shutil.copystat(src, dst)
89    except WindowsError:
90      # can't copy file access times on Windows
91      pass
92    except OSError, why:
93      errors.extend((src, dst, str(why)))
94    if errors:
95      raise shutil.Error, errors
96    return copies
97
98  def installIncludes(self):
99    self.copies.extend(self.copytree(self.rootIncludeDir, self.installIncludeDir))
100    self.copies.extend(self.copytree(self.archIncludeDir, self.installIncludeDir))
101    return
102
103  def copyConf(self, src, dst):
104    if os.path.isdir(dst):
105      dst = os.path.join(dst, os.path.basename(src))
106    lines   = []
107    oldFile = open(src, 'r')
108    for line in oldFile.readlines():
109      # paths generated by configure could be different link-path than whats used by user, so fix both
110      line = re.sub(re.escape(os.path.join(self.rootDir, self.arch)), self.installDir, line)
111      line = re.sub(re.escape(os.path.realpath(os.path.join(self.rootDir, self.arch))), self.installDir, line)
112      line = re.sub(re.escape(os.path.join(self.rootDir, 'bin')), self.installBinDir, line)
113      line = re.sub(re.escape(os.path.realpath(os.path.join(self.rootDir, 'bin'))), self.installBinDir, line)
114      line = re.sub(re.escape(os.path.join(self.rootDir, 'include')), self.installIncludeDir, line)
115      line = re.sub(re.escape(os.path.realpath(os.path.join(self.rootDir, 'include'))), self.installIncludeDir, line)
116      # remove PETSC_DIR/PETSC_ARCH variables from conf-makefiles. They are no longer necessary
117      line = re.sub('\$\{PETSC_DIR\}/\$\{PETSC_ARCH\}', self.installDir, line)
118      line = re.sub('PETSC_ARCH=\$\{PETSC_ARCH\}', '', line)
119      line = re.sub('\$\{PETSC_DIR\}', self.installDir, line)
120      lines.append(line)
121    oldFile.close()
122    newFile = open(dst, 'w')
123    newFile.write(''.join(lines))
124    newFile.close()
125    shutil.copystat(src, dst)
126    return
127
128  def installConf(self):
129    # rootConfDir can have a duplicate petscvariables - so processing it first removes the appropriate duplicate file.
130    self.copies.extend(self.copytree(self.rootConfDir, self.installConfDir, copyFunc = self.copyConf))
131    self.copies.extend(self.copytree(self.archConfDir, self.installConfDir))
132    # Just copyConf() a couple of files manually [as the rest of the files should not be modified]
133    for file in ['petscrules', 'petscvariables']:
134      self.copyConf(os.path.join(self.archConfDir,file),os.path.join(self.installConfDir,file))
135    return
136
137  def installBin(self):
138    self.copies.extend(self.copytree(self.rootBinDir, self.installBinDir))
139    self.copies.extend(self.copytree(self.archBinDir, self.installBinDir))
140    return
141
142  def copyLib(self, src, dst):
143    '''Run ranlib on the destination library if it is an archive'''
144    shutil.copy2(src, dst)
145    if os.path.splitext(dst)[1] == '.'+self.libSuffix:
146      self.executeShellCommand(self.ranlib+' '+dst)
147    return
148
149  def installLib(self):
150    self.copies.extend(self.copytree(self.archLibDir, self.installLibDir, copyFunc = self.copyLib))
151    return
152
153  def createUninstaller(self):
154    uninstallscript = os.path.join(self.installConfDir, 'uninstall.py')
155    f = open(uninstallscript, 'w')
156    # Could use the Python AST to do this
157    f.write('#!'+sys.executable+'\n')
158    f.write('import os\n')
159
160    f.write('copies = '+repr(self.copies))
161    f.write('''
162for src, dst in copies:
163  if os.path.exists(dst):
164    os.remove(dst)
165''')
166    f.close()
167    os.chmod(uninstallscript,0744)
168    return
169
170  def outputHelp(self):
171    print '''
172====================================
173If using sh/bash, do the following:
174  PETSC_DIR=%s; export PETSC_DIR
175  unset PETSC_ARCH
176If using csh/tcsh, do the following:
177  setenv PETSC_DIR %s
178  unsetenv PETSC_ARCH
179Run the following to verify the install (remain in current directory for the tests):
180  make test
181====================================
182''' % (self.installDir, self.installDir)
183    return
184
185  def run(self):
186    self.setup()
187    self.setupDirectories()
188    if os.path.exists(self.installDir) and os.path.samefile(self.installDir, os.path.join(self.rootDir,self.arch)):
189      print '********************************************************************'
190      print 'Install directory is current directory; nothing needs to be done'
191      print '********************************************************************'
192      return
193    print '*** Installing PETSc at',self.installDir, ' ***'
194    if not os.path.exists(self.installDir):
195      try:
196        os.makedirs(self.installDir)
197      except:
198        print '********************************************************************'
199        print 'Unable to create', self.installDir, 'Perhaps you need to do "sudo make install"'
200        print '********************************************************************'
201        return
202    if not os.path.isdir(os.path.realpath(self.installDir)):
203      print '********************************************************************'
204      print 'Specified prefix', self.installDir, 'is not a directory. Cannot proceed!'
205      print '********************************************************************'
206      return
207    if not os.access(self.installDir, os.W_OK):
208      print '********************************************************************'
209      print 'Unable to write to ', self.installDir, 'Perhaps you need to do "sudo make install"'
210      print '********************************************************************'
211      return
212    self.installIncludes()
213    self.installConf()
214    self.installBin()
215    self.installLib()
216    output = self.executeShellCommand(self.make+' PETSC_ARCH=""'+' PETSC_DIR='+self.installDir+' shared mpi4py petsc4py')[0]
217    print output
218    self.createUninstaller()
219    self.outputHelp()
220    return
221
222if __name__ == '__main__':
223  Installer(sys.argv[1:]).run()
224  # temporary hack - delete log files created by BuildSystem - when 'sudo make install' is invoked
225  delfiles=['RDict.db','RDict.log','build.log','default.log','build.log.bkp','default.log.bkp']
226  for delfile in delfiles:
227    if os.path.exists(delfile) and (os.stat(delfile).st_uid==0):
228      os.remove(delfile)
229