xref: /petsc/systems/Apple/iOS/bin/iosbuilder.py (revision a8a8f36618f536eff5e4c1df78b3fdf9dd5d254e)
1#!/usr/bin/env python
2#
3#   Builds a iPhone/iPad static library of PETSc
4#
5#   Before using removed /usr/include/mpi.h and /Developer/SDKs/MacOSX10.5.sdk/usr/include/mpi.h or
6#      Xcode will use those instead of the MPIuni one we point to
7#
8#   export PETSC_ARCH=arch-ios
9
10#   ./systems/Apple/iOS/bin/arch-ios.py [use --with-debugging=0 to get iPhone/iPad version, otherwise creates simulator version]
11#      this sets up the appropriate configuration file
12#
13#   ./systems/Apple/iOS/bin/iosbuilder.py
14#      this creates the PETSc iPhone/iPad library
15#      this will open Xcode and give you directions to follow
16#
17#   open xcode/examples/examples.xcodeproj
18#       Project -> Edit Project Setting  -> Configuration (make sure it is Release or Debug depending on if you used --with-debugging=0)
19#       Build -> Build and Debug
20#
21import os, sys
22
23sys.path.insert(0, os.path.join(os.environ['PETSC_DIR'], 'config'))
24sys.path.insert(0, os.path.join(os.environ['PETSC_DIR'], 'config', 'BuildSystem'))
25
26import script
27
28class PETScMaker(script.Script):
29 def __init__(self):
30   import RDict
31   import os
32
33   argDB = RDict.RDict(None, None, 0, 0, readonly = True)
34   argDB.saveFilename = os.path.join(os.environ['PETSC_DIR'], os.environ['PETSC_ARCH'], 'conf', 'RDict.db')
35   argDB.load()
36   script.Script.__init__(self, argDB = argDB)
37   self.log = sys.stdout
38   return
39
40 def setupModules(self):
41   self.mpi           = self.framework.require('config.packages.MPI',         None)
42   self.base          = self.framework.require('config.base',                 None)
43   self.setCompilers  = self.framework.require('config.setCompilers',         None)
44   self.arch          = self.framework.require('PETSc.utilities.arch',        None)
45   self.petscdir      = self.framework.require('PETSc.utilities.petscdir',    None)
46   self.languages     = self.framework.require('PETSc.utilities.languages',   None)
47   self.debugging     = self.framework.require('PETSc.utilities.debugging',   None)
48   self.make          = self.framework.require('config.programs',             None)
49   self.compilers     = self.framework.require('config.compilers',            None)
50   self.types         = self.framework.require('config.types',                None)
51   self.headers       = self.framework.require('config.headers',              None)
52   self.functions     = self.framework.require('config.functions',            None)
53   self.libraries     = self.framework.require('config.libraries',            None)
54   self.scalarType    = self.framework.require('PETSc.utilities.scalarTypes', None)
55   self.memAlign      = self.framework.require('PETSc.utilities.memAlign',    None)
56   self.libraryOptions= self.framework.require('PETSc.utilities.libraryOptions', None)
57   self.compilerFlags = self.framework.require('config.compilerFlags', self)
58   return
59
60 def setupHelp(self, help):
61   import nargs
62
63   help = script.Script.setupHelp(self, help)
64   help.addArgument('RepManager', '-rootDir', nargs.ArgDir(None, os.environ['PETSC_DIR'], 'The root directory for this build', isTemporary = 1))
65   help.addArgument('RepManager', '-dryRun',  nargs.ArgBool(None, False, 'Only output what would be run', isTemporary = 1))
66   help.addArgument('RepManager', '-verbose', nargs.ArgInt(None, 0, 'The verbosity level', min = 0, isTemporary = 1))
67   return help
68
69 def setup(self):
70   script.Script.setup(self)
71   self.framework = self.loadConfigure()
72   self.setupModules()
73   return
74
75 @property
76 def verbose(self):
77   '''The verbosity level'''
78   return self.argDB['verbose']
79
80 @property
81 def dryRun(self):
82   '''Flag for only output of what would be run'''
83   return self.argDB['dryRun']
84
85 def getPackageInfo(self):
86   packageIncludes = []
87   packageLibs     = []
88   for p in self.framework.packages:
89     # Could put on compile line, self.addDefine('HAVE_'+i.PACKAGE, 1)
90     if hasattr(p, 'lib'):
91       if not isinstance(p.lib, list):
92         packageLibs.append(p.lib)
93       else:
94         packageLibs.extend(p.lib)
95     if hasattr(p, 'include'):
96       if not isinstance(p.include, list):
97         packageIncludes.append(p.include)
98       else:
99         packageIncludes.extend(p.include)
100   packageLibs     = self.libraries.toStringNoDupes(packageLibs+self.libraries.math)
101   packageIncludes = self.headers.toStringNoDupes(packageIncludes)
102   return packageIncludes, packageLibs
103
104 def buildDir(self, dirname):
105   ''' This is run in a PETSc source directory'''
106   if self.verbose: print 'Entering '+dirname
107   os.chdir(dirname)
108   l = len(os.environ['PETSC_DIR'])
109   basedir = os.path.join(os.environ['PETSC_DIR'],os.environ['PETSC_ARCH'],'xcode-links')
110   #newdirname = os.path.join(basedir,dirname[l+1:])
111   #os.mkdir(newdirname)
112
113
114   # Get list of source files in the directory
115   cnames = []
116   onames = []
117   fnames = []
118   hnames = []
119   for f in os.listdir(dirname):
120     ext = os.path.splitext(f)[1]
121     if ext == '.c':
122       cnames.append(f)
123       onames.append(f.replace('.c', '.o'))
124     if ext == '.h':
125       hnames.append(f)
126   if cnames:
127     if self.verbose: print 'Linking C files',cnames
128     for i in cnames:
129       j = i[l+1:]
130       if not os.path.islink(os.path.join(basedir,i)):
131         os.symlink(os.path.join(dirname,i),os.path.join(basedir,i))
132   # do not need to link these because xcode project points to original source code directory
133   #if hnames:
134   #  if self.verbose: print 'Linking h files',hnames
135   #  for i in hnames:
136   #    if not os.path.islink(os.path.join(basedir,i)):
137   #      os.symlink(os.path.join(dirname,i),os.path.join(basedir,i))
138   return
139
140 def checkDir(self, dirname):
141   '''Checks whether we should recurse into this directory
142   - Excludes projects directory
143   - Excludes examples directory
144   - Excludes contrib directory
145   - Excludes tutorials directory
146   - Excludes benchmarks directory
147   - Checks whether fortran bindings are necessary
148   - Checks makefile to see if compiler is allowed to visit this directory for this configuration'''
149#   print self.functions.functions
150#   print self.base.defines
151   base = os.path.basename(dirname)
152
153   if base == 'examples': return False
154   if base == 'projects': return False
155   if not hasattr(self.compilers, 'FC'):
156     if base.startswith('ftn-') or base.startswith('f90-'): return False
157   if base == 'contrib':  return False
158   if base == 'tutorials':  return False
159   if base == 'benchmarks':  return False
160   if base == 'xcode':  return False
161   if base.startswith('arch-'):  return False
162
163   import re
164   reg   = re.compile(' [ ]*')
165   fname = os.path.join(dirname, 'makefile')
166   if not os.path.isfile(fname):
167     if os.path.isfile(os.path.join(dirname, 'Makefile')): print 'ERROR: Change Makefile to makefile in',dirname
168     return False
169   fd = open(fname)
170   text = fd.readline()
171   while text:
172     if text.startswith('#requires'):
173       text = text[9:-1].strip()
174       text = reg.sub(' ',text)
175       rtype = text.split(' ')[0]
176       rvalue = text.split(' ')[1]
177
178       if rvalue == "'"+'PETSC_HAVE_FORTRAN'+"'" or rvalue == "'"+'PETSC_USING_F90'+"'" or rvalue == "'"+'PETSC_USING_F2003'+"'":
179         if not hasattr(self.compilers, 'FC'):
180           if self.verbose: print 'Rejecting',dirname,'because fortran is not being used'
181           return 0
182       elif rvalue == "'"+'PETSC_USE_LOG'+"'":
183         if not self.libraryOptions.useLog:
184           if self.verbose: print 'Rejecting',dirname,'because logging is turned off'
185           return 0
186       elif rvalue == "'"+'PETSC_USE_FORTRAN_KERNELS'+"'":
187         if not self.libraryOptions.useFortranKernels:
188           if self.verbose: print 'Rejecting',dirname,'because fortran kernels are turned off'
189           return 0
190       elif rtype == 'scalar' and not self.scalarType.scalartype == rvalue:
191         if self.verbose: print 'Rejecting',dirname,'because scalar type '+self.scalarType.scalartype+' is not '+rvalue
192         return 0
193       elif rtype == 'language':
194         if rvalue == 'CXXONLY' and self.languages.clanguage == 'C':
195           if self.verbose: print 'Rejecting',dirname,'because language is '+self.languages.clanguage+' is not C++'
196           return 0
197       elif rtype == 'precision' and not rvalue == self.scalarType.precision:
198         if self.verbose: print 'Rejecting',dirname,'because precision '+self.scalarType.precision+' is not '+rvalue
199         return 0
200       elif rtype == 'package':
201         found = 0
202         if self.mpi.usingMPIUni:
203           pname = 'PETSC_HAVE_MPIUNI'
204           pname = "'"+pname+"'"
205           if pname == rvalue: found = 1
206         for i in self.framework.packages:
207           pname = 'PETSC_HAVE_'+i.PACKAGE
208           pname = "'"+pname+"'"
209           if pname == rvalue: found = 1
210         if not found:
211           if self.verbose: print 'Rejecting',dirname,'because package '+rvalue+' does not exist'
212           return 0
213       elif rtype == 'define':
214         found = 0
215         for i in self.base.defines:
216           pname = 'PETSC_'+i.upper()
217           pname = "'"+pname+"'"
218           if pname == rvalue: found = 1
219         if not found:
220           if self.verbose: print 'Rejecting',dirname,'because define '+rvalue+' does not exist'
221           return 0
222       elif rtype == 'function':
223         found = 0
224         for i in self.functions.functions:
225           pname = 'PETSC_HAVE_'+i.upper()
226           pname = "'"+pname+"'"
227#           print pname
228#           print rvalue
229           if pname == rvalue: found = 1
230         if not found:
231           if self.verbose: print 'Rejecting',dirname,'because function '+rvalue+' does not exist'
232           return 0
233
234     text = fd.readline()
235   fd.close()
236   return True
237
238 def buildAll(self, rootDir = None):
239   import shutil
240   self.setup()
241   if rootDir is None:
242     rootDir = self.argDB['rootDir']
243   if not self.checkDir(rootDir):
244     print 'Nothing to be done'
245   if rootDir == os.environ['PETSC_DIR']:
246     basedir = os.path.join(self.petscdir.dir, self.arch.arch, 'xcode-links')
247     if os.path.isdir(basedir):
248       if self.verbose: print 'Removing '+basedir
249       shutil.rmtree(basedir)
250   os.mkdir(basedir)
251   for root, dirs, files in os.walk(rootDir):
252     self.buildDir(root)
253     for badDir in [d for d in dirs if not self.checkDir(os.path.join(root, d))]:
254       dirs.remove(badDir)
255
256   print 'In Xcode mouse click on xcode-links and the delete key, then'
257   print 'control mouse click on "Other Sources" and select "Add files to PETSc ...", then'
258   print 'in the finder window locate ${PETSC_DIR}/arch-ios/xcode-links and select it. Now'
259   print 'exit Xcode'
260
261   try:
262     import subprocess
263     subprocess.call('cd '+os.path.join(os.environ['PETSC_DIR'],'systems','Apple','iOS','PETSc')+';open -W PETSc.xcodeproj', shell=True)
264   except RuntimeError, e:
265     raise RuntimeError('Error opening xcode project '+str(e))
266
267
268   sdk         = ' -sdk iphonesimulator5.1 '
269   destination = 'iphonesimulator'
270   debug       = 'Debug'
271   debugdir    = 'Debug-'+destination
272   if not self.compilerFlags.debugging:
273     debug = 'Release'
274     debugdir = 'Release-'+destination
275   try:
276     output,err,ret  = self.executeShellCommand('cd '+os.path.join(os.environ['PETSC_DIR'],'systems','Apple','iOS','PETSc')+';xcodebuild -configuration '+debug+sdk, timeout=3000, log = self.log)
277   except RuntimeError, e:
278     raise RuntimeError('Error making iPhone/iPad version of PETSc libraries: '+str(e))
279
280   liblocation = os.path.join(os.environ['PETSC_DIR'],'systems','Apple','iOS','PETSc','build',debugdir,'libPETSc.a')
281   if not os.path.exists(liblocation):
282     raise RuntimeError('Error library '+liblocation+' not created')
283   try:
284     output,err,ret  = self.executeShellCommand('mv -f '+liblocation+' '+os.path.join(os.environ['PETSC_DIR'],os.environ['PETSC_ARCH'],'lib'), timeout=30, log = self.log)
285   except RuntimeError, e:
286     raise RuntimeError('Error copying iPhone/iPad version of PETSc libraries: '+str(e))
287
288   return
289
290def noCheckCommand(command, status, output, error):
291  ''' Do no check result'''
292  return
293  noCheckCommand = staticmethod(noCheckCommand)
294
295if __name__ == '__main__':
296  PETScMaker().buildAll()
297