xref: /petsc/systems/Apple/iOS/bin/iosbuilder.py (revision a95d84e0230cb0d652d808aead973c41ec535430)
1#!/usr/bin/env python
2#
3#   Builds a iOS static library of PETSc
4#
5#   Before using remove /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 systems/Apple/iOS/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', '-skipXCode',  nargs.ArgBool(None, False, 'Do not run XCode application/files have not been added/removed', isTemporary = 1))
67   help.addArgument('RepManager', '-verbose', nargs.ArgInt(None, 0, 'The verbosity level', min = 0, isTemporary = 1))
68   return help
69
70 def setup(self):
71   script.Script.setup(self)
72   self.framework = self.loadConfigure()
73   self.setupModules()
74   return
75
76 @property
77 def verbose(self):
78   '''The verbosity level'''
79   return self.argDB['verbose']
80
81 @property
82 def skipXCode(self):
83   '''Skip XCode application'''
84   return self.argDB['skipXCode']
85
86 @property
87 def dryRun(self):
88   '''Flag for only output of what would be run'''
89   return self.argDB['dryRun']
90
91 def getPackageInfo(self):
92   packageIncludes = []
93   packageLibs     = []
94   for p in self.framework.packages:
95     # Could put on compile line, self.addDefine('HAVE_'+i.PACKAGE, 1)
96     if hasattr(p, 'lib'):
97       if not isinstance(p.lib, list):
98         packageLibs.append(p.lib)
99       else:
100         packageLibs.extend(p.lib)
101     if hasattr(p, 'include'):
102       if not isinstance(p.include, list):
103         packageIncludes.append(p.include)
104       else:
105         packageIncludes.extend(p.include)
106   packageLibs     = self.libraries.toStringNoDupes(packageLibs+self.libraries.math)
107   packageIncludes = self.headers.toStringNoDupes(packageIncludes)
108   return packageIncludes, packageLibs
109
110 def buildDir(self, dirname):
111   ''' This is run in a PETSc source directory'''
112   if self.verbose: print 'Entering '+dirname
113   os.chdir(dirname)
114   l = len(os.environ['PETSC_DIR'])
115   basedir = os.path.join(os.environ['PETSC_DIR'],os.environ['PETSC_ARCH'],'xcode-links')
116   #newdirname = os.path.join(basedir,dirname[l+1:])
117   #os.mkdir(newdirname)
118
119
120   # Get list of source files in the directory
121   cnames = []
122   onames = []
123   fnames = []
124   hnames = []
125   for f in os.listdir(dirname):
126     ext = os.path.splitext(f)[1]
127     if ext == '.c':
128       cnames.append(f)
129       onames.append(f.replace('.c', '.o'))
130     if ext == '.h':
131       hnames.append(f)
132   if cnames:
133     if self.verbose: print 'Linking C files',cnames
134     for i in cnames:
135       j = i[l+1:]
136       if not os.path.islink(os.path.join(basedir,i)) and not i.startswith('.') and i.find(".BACKUP") == -1 and i.find(".LOCAL") == -1 and i.find(".BASE") == -1:
137         if i.endswith('openglops.c') and not os.path.islink(os.path.join(basedir,'openglops.m')):
138           os.symlink(os.path.join(dirname,i),os.path.join(basedir,'openglops.m'))
139         else:
140           os.symlink(os.path.join(dirname,i),os.path.join(basedir,i))
141   # do not need to link these because xcode project points to original source code directory
142   #if hnames:
143   #  if self.verbose: print 'Linking h files',hnames
144   #  for i in hnames:
145   #    if not os.path.islink(os.path.join(basedir,i)):
146   #      os.symlink(os.path.join(dirname,i),os.path.join(basedir,i))
147   return
148
149 def checkDir(self, dirname):
150   '''Checks whether we should recurse into this directory
151   - Excludes projects directory
152   - Excludes examples directory
153   - Excludes contrib directory
154   - Excludes tutorials directory
155   - Excludes benchmarks directory
156   - Checks makefile to see if compiler is allowed to visit this directory for this configuration'''
157#   print self.functions.functions
158#   print self.base.defines
159   base = os.path.basename(dirname)
160
161   if base == 'examples': return False
162   if base == 'projects': return False
163   if base.startswith('ftn-') or base.startswith('f90-'): return False
164   if base == 'contrib':  return False
165   if base == 'tutorials':  return False
166   if base == 'benchmarks':  return False
167   if base == 'systems':  return False
168# for some reason agrmes is in the repository but not used!
169   if base == 'agmres':  return False
170   if base == 'test-dir':  return False
171   if base.startswith('arch-'):  return False
172
173   import re
174   reg   = re.compile(' [ ]*')
175   fname = os.path.join(dirname, 'makefile')
176   if not os.path.isfile(fname):
177     if os.path.isfile(os.path.join(dirname, 'Makefile')): print 'ERROR: Change Makefile to makefile in',dirname
178     return False
179   fd = open(fname)
180   text = fd.readline()
181   while text:
182     if text.startswith('#requires'):
183       text = text[9:-1].strip()
184       text = reg.sub(' ',text)
185       rtype = text.split(' ')[0]
186       rvalue = text.split(' ')[1]
187
188       if rvalue == "'"+'PETSC_HAVE_FORTRAN'+"'" or rvalue == "'"+'PETSC_USING_F90'+"'" or rvalue == "'"+'PETSC_USING_F2003'+"'":
189         if not hasattr(self.compilers, 'FC'):
190           if self.verbose: print 'Rejecting',dirname,'because fortran is not being used'
191           return 0
192       elif rvalue == "'"+'PETSC_USE_LOG'+"'":
193         if not self.libraryOptions.useLog:
194           if self.verbose: print 'Rejecting',dirname,'because logging is turned off'
195           return 0
196       elif rvalue == "'"+'PETSC_USE_FORTRAN_KERNELS'+"'":
197         if not self.libraryOptions.useFortranKernels:
198           if self.verbose: print 'Rejecting',dirname,'because fortran kernels are turned off'
199           return 0
200       elif rtype == 'scalar' and not self.scalarType.scalartype == rvalue:
201         if self.verbose: print 'Rejecting',dirname,'because scalar type '+self.scalarType.scalartype+' is not '+rvalue
202         return 0
203       elif rtype == 'language':
204         if rvalue == 'CXXONLY' and self.languages.clanguage == 'C':
205           if self.verbose: print 'Rejecting',dirname,'because language is '+self.languages.clanguage+' is not C++'
206           return 0
207       elif rtype == 'precision' and not rvalue == self.scalarType.precision:
208         if self.verbose: print 'Rejecting',dirname,'because precision '+self.scalarType.precision+' is not '+rvalue
209         return 0
210       elif rtype == 'package':
211         found = 0
212         if self.mpi.usingMPIUni:
213           pname = 'PETSC_HAVE_MPIUNI'
214           pname = "'"+pname+"'"
215           if pname == rvalue: found = 1
216         for i in self.framework.packages:
217           pname = 'PETSC_HAVE_'+i.PACKAGE
218           pname = "'"+pname+"'"
219           if pname == rvalue: found = 1
220         if not found:
221           for i in self.base.defines:
222             pname = 'PETSC_'+i.upper()
223             pname = "'"+pname+"'"
224             if pname == rvalue: found = 1
225           if not found:
226             if self.verbose: print 'Rejecting',dirname,'because package '+rvalue+' does not exist'
227             return 0
228       elif rtype == 'define':
229         found = 0
230         for i in self.base.defines:
231           pname = 'PETSC_'+i.upper()
232           pname = "'"+pname+"'"
233           if pname == rvalue: found = 1
234         if not found:
235           if self.verbose: print 'Rejecting',dirname,'because define '+rvalue+' does not exist'
236           return 0
237       elif rtype == 'function':
238         found = 0
239         for i in self.functions.functions:
240           pname = 'PETSC_HAVE_'+i.upper()
241           pname = "'"+pname+"'"
242#           print pname
243#           print rvalue
244           if pname == rvalue: found = 1
245         if not found:
246           if self.verbose: print 'Rejecting',dirname,'because function '+rvalue+' does not exist'
247           return 0
248
249     text = fd.readline()
250   fd.close()
251   return True
252
253 def buildAll(self, rootDir = None):
254   import shutil
255   self.setup()
256   if rootDir is None:
257     rootDir = self.argDB['rootDir']
258   if not self.checkDir(rootDir):
259     print 'Nothing to be done'
260   if rootDir == os.environ['PETSC_DIR']:
261     basedir = os.path.join(self.petscdir.dir, self.arch.arch, 'xcode-links')
262     if os.path.isdir(basedir):
263       if self.verbose: print 'Removing '+basedir
264       shutil.rmtree(basedir)
265   os.mkdir(basedir)
266   for root, dirs, files in os.walk(rootDir):
267     self.buildDir(root)
268     for badDir in [d for d in dirs if not self.checkDir(os.path.join(root, d))]:
269       dirs.remove(badDir)
270
271   if not self.skipXCode:
272
273     print 'In Xcode mouse click on Other Sources then xcode-links and the delete key, then'
274     print 'control mouse click on "Other Sources" and select "Add files to PETSc ...", then'
275     print 'in the finder window locate ${PETSC_DIR}/arch-ios/xcode-links and select it. Now'
276     print 'exit Xcode'
277
278     try:
279       import subprocess
280       subprocess.call('cd '+os.path.join(os.environ['PETSC_DIR'],'systems','Apple','iOS','PETSc')+';open -W PETSc.xcodeproj', shell=True)
281     except RuntimeError, e:
282       raise RuntimeError('Error opening xcode project '+str(e))
283
284
285   sdk         = ' -sdk iphonesimulator7.1 '
286   destination = 'iphonesimulator'
287   debug       = 'Debug'
288   debugdir    = 'Debug-'+destination
289   if not self.compilerFlags.debugging:
290     debug = 'Release'
291     debugdir = 'Release-'+destination
292   try:
293     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)
294   except RuntimeError, e:
295     raise RuntimeError('Error making iPhone/iPad version of PETSc libraries: '+str(e))
296
297   liblocation = os.path.join(os.environ['PETSC_DIR'],'systems','Apple','iOS','PETSc','build',debugdir,'libPETSc.a')
298   if not os.path.exists(liblocation):
299     raise RuntimeError('Error library '+liblocation+' not created')
300   try:
301     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)
302   except RuntimeError, e:
303     raise RuntimeError('Error copying iPhone/iPad version of PETSc libraries: '+str(e))
304
305   return
306
307def noCheckCommand(command, status, output, error):
308  ''' Do no check result'''
309  return
310  noCheckCommand = staticmethod(noCheckCommand)
311
312if __name__ == '__main__':
313  PETScMaker().buildAll()
314