1#!/usr/bin/env python 2 3import os 4from distutils.sysconfig import parse_makefile 5import sys 6import logging 7sys.path.insert(0, os.path.abspath(os.path.dirname(__file__))) 8from cmakegen import Mistakes, stripsplit, AUTODIRS, SKIPDIRS 9from cmakegen import defaultdict # collections.defaultdict, with fallback for python-2.4 10 11PKGS = 'sys vec mat dm ksp snes ts tao'.split() 12LANGS = dict(c='C', cxx='CXX', cu='CU', F='F', F90='F90') 13 14try: 15 all([True, True]) 16except NameError: # needs python-2.5 17 def all(iterable): 18 for i in iterable: 19 if not i: 20 return False 21 return True 22 23try: 24 os.path.relpath # needs python-2.6 25except AttributeError: 26 def _relpath(path, start=os.path.curdir): 27 """Return a relative version of a path""" 28 29 from os.path import curdir, abspath, commonprefix, sep, pardir, join 30 if not path: 31 raise ValueError("no path specified") 32 33 start_list = [x for x in abspath(start).split(sep) if x] 34 path_list = [x for x in abspath(path).split(sep) if x] 35 36 # Work out how much of the filepath is shared by start and path. 37 i = len(commonprefix([start_list, path_list])) 38 39 rel_list = [pardir] * (len(start_list)-i) + path_list[i:] 40 if not rel_list: 41 return curdir 42 return join(*rel_list) 43 os.path.relpath = _relpath 44 45class debuglogger(object): 46 def __init__(self, log): 47 self._log = log 48 49 def write(self, string): 50 self._log.debug(string) 51 52class Petsc(object): 53 def __init__(self, petsc_dir=None, petsc_arch=None, verbose=False): 54 if petsc_dir is None: 55 petsc_dir = os.environ.get('PETSC_DIR') 56 if petsc_dir is None: 57 try: 58 petsc_dir = parse_makefile(os.path.join('lib','petsc','conf', 'petscvariables')).get('PETSC_DIR') 59 finally: 60 if petsc_dir is None: 61 raise RuntimeError('Could not determine PETSC_DIR, please set in environment') 62 if petsc_arch is None: 63 petsc_arch = os.environ.get('PETSC_ARCH') 64 if petsc_arch is None: 65 try: 66 petsc_arch = parse_makefile(os.path.join(petsc_dir, 'lib','petsc','conf', 'petscvariables')).get('PETSC_ARCH') 67 finally: 68 if petsc_arch is None: 69 raise RuntimeError('Could not determine PETSC_ARCH, please set in environment') 70 self.petsc_dir = petsc_dir 71 self.petsc_arch = petsc_arch 72 self.read_conf() 73 logging.basicConfig(filename=self.arch_path('lib','petsc','conf', 'gmake.log'), level=logging.DEBUG) 74 self.log = logging.getLogger('gmakegen') 75 self.mistakes = Mistakes(debuglogger(self.log), verbose=verbose) 76 self.gendeps = [] 77 78 def arch_path(self, *args): 79 return os.path.join(self.petsc_dir, self.petsc_arch, *args) 80 81 def read_conf(self): 82 self.conf = dict() 83 for line in open(self.arch_path('include', 'petscconf.h')): 84 if line.startswith('#define '): 85 define = line[len('#define '):] 86 space = define.find(' ') 87 key = define[:space] 88 val = define[space+1:] 89 self.conf[key] = val 90 self.conf.update(parse_makefile(self.arch_path('lib','petsc','conf', 'petscvariables'))) 91 self.have_fortran = int(self.conf.get('PETSC_HAVE_FORTRAN', '0')) 92 93 def inconf(self, key, val): 94 if key in ['package', 'function', 'define']: 95 return self.conf.get(val) 96 elif key == 'precision': 97 return val == self.conf['PETSC_PRECISION'] 98 elif key == 'scalar': 99 return val == self.conf['PETSC_SCALAR'] 100 elif key == 'language': 101 return val == self.conf['PETSC_LANGUAGE'] 102 raise RuntimeError('Unknown conf check: %s %s' % (key, val)) 103 104 def relpath(self, root, src): 105 return os.path.relpath(os.path.join(root, src), self.petsc_dir) 106 107 def get_sources(self, makevars): 108 """Return dict {lang: list_of_source_files}""" 109 source = dict() 110 for lang, sourcelang in LANGS.items(): 111 source[lang] = [f for f in makevars.get('SOURCE'+sourcelang,'').split() if f.endswith(lang)] 112 return source 113 114 def gen_pkg(self, pkg): 115 pkgsrcs = dict() 116 for lang in LANGS: 117 pkgsrcs[lang] = [] 118 for root, dirs, files in os.walk(os.path.join(self.petsc_dir, 'src', pkg)): 119 makefile = os.path.join(root,'makefile') 120 if not os.path.exists(makefile): 121 dirs[:] = [] 122 continue 123 mklines = open(makefile) 124 conditions = set(tuple(stripsplit(line)) for line in mklines if line.startswith('#requires')) 125 mklines.close() 126 if not all(self.inconf(key, val) for key, val in conditions): 127 dirs[:] = [] 128 continue 129 makevars = parse_makefile(makefile) 130 mdirs = makevars.get('DIRS','').split() # Directories specified in the makefile 131 self.mistakes.compareDirLists(root, mdirs, dirs) # diagnostic output to find unused directories 132 candidates = set(mdirs).union(AUTODIRS).difference(SKIPDIRS) 133 dirs[:] = list(candidates.intersection(dirs)) 134 allsource = [] 135 def mkrel(src): 136 return self.relpath(root, src) 137 source = self.get_sources(makevars) 138 for lang, s in source.items(): 139 pkgsrcs[lang] += map(mkrel, s) 140 allsource += s 141 self.mistakes.compareSourceLists(root, allsource, files) # Diagnostic output about unused source files 142 self.gendeps.append(self.relpath(root, 'makefile')) 143 return pkgsrcs 144 145 def gen_gnumake(self, fd): 146 def write(stem, srcs): 147 for lang in LANGS: 148 fd.write('%(stem)s.%(lang)s := %(srcs)s\n' % dict(stem=stem, lang=lang, srcs=' '.join(srcs[lang]))) 149 for pkg in PKGS: 150 srcs = self.gen_pkg(pkg) 151 write('srcs-' + pkg, srcs) 152 return self.gendeps 153 154 def gen_ninja(self, fd): 155 libobjs = [] 156 for pkg in PKGS: 157 srcs = self.gen_pkg(pkg) 158 for lang in LANGS: 159 for src in srcs[lang]: 160 obj = '$objdir/%s.o' % src 161 fd.write('build %(obj)s : %(lang)s_COMPILE %(src)s\n' % dict(obj=obj, lang=lang.upper(), src=os.path.join(self.petsc_dir,src))) 162 libobjs.append(obj) 163 fd.write('\n') 164 fd.write('build $libdir/libpetsc.so : %s_LINK_SHARED %s\n\n' % ('CF'[self.have_fortran], ' '.join(libobjs))) 165 fd.write('build petsc : phony || $libdir/libpetsc.so\n\n') 166 167 def summary(self): 168 self.mistakes.summary() 169 170def WriteGnuMake(petsc): 171 arch_files = petsc.arch_path('lib','petsc','conf', 'files') 172 fd = open(arch_files, 'w') 173 gendeps = petsc.gen_gnumake(fd) 174 fd.write('\n') 175 fd.write('# Dependency to regenerate this file\n') 176 fd.write('%s : %s %s\n' % (os.path.relpath(arch_files, petsc.petsc_dir), 177 os.path.relpath(__file__, os.path.realpath(petsc.petsc_dir)), 178 ' '.join(gendeps))) 179 fd.write('\n') 180 fd.write('# Dummy dependencies in case makefiles are removed\n') 181 fd.write(''.join([dep + ':\n' for dep in gendeps])) 182 fd.close() 183 184def WriteNinja(petsc): 185 conf = dict() 186 parse_makefile(os.path.join(petsc.petsc_dir, 'lib', 'petsc','conf', 'variables'), conf) 187 parse_makefile(petsc.arch_path('lib','petsc','conf', 'petscvariables'), conf) 188 build_ninja = petsc.arch_path('build.ninja') 189 fd = open(build_ninja, 'w') 190 fd.write('objdir = obj-ninja\n') 191 fd.write('libdir = lib\n') 192 fd.write('c_compile = %(PCC)s\n' % conf) 193 fd.write('c_flags = %(PETSC_CC_INCLUDES)s %(PCC_FLAGS)s %(CCPPFLAGS)s\n' % conf) 194 fd.write('c_link = %(PCC_LINKER)s\n' % conf) 195 fd.write('c_link_flags = %(PCC_LINKER_FLAGS)s\n' % conf) 196 if petsc.have_fortran: 197 fd.write('f_compile = %(FC)s\n' % conf) 198 fd.write('f_flags = %(PETSC_FC_INCLUDES)s %(FC_FLAGS)s %(FCPPFLAGS)s\n' % conf) 199 fd.write('f_link = %(FC_LINKER)s\n' % conf) 200 fd.write('f_link_flags = %(FC_LINKER_FLAGS)s\n' % conf) 201 fd.write('petsc_external_lib = %(PETSC_EXTERNAL_LIB_BASIC)s\n' % conf) 202 fd.write('python = %(PYTHON)s\n' % conf) 203 fd.write('\n') 204 fd.write('rule C_COMPILE\n' 205 ' command = $c_compile -MMD -MF $out.d $c_flags -c $in -o $out\n' 206 ' description = CC $out\n' 207 ' depfile = $out.d\n' 208 # ' deps = gcc\n') # 'gcc' is default, 'msvc' only recognized by newer versions of ninja 209 '\n') 210 fd.write('rule C_LINK_SHARED\n' 211 ' command = $c_link $c_link_flags -shared -o $out $in $petsc_external_lib\n' 212 ' description = CLINK_SHARED $out\n' 213 '\n') 214 if petsc.have_fortran: 215 fd.write('rule F_COMPILE\n' 216 ' command = $f_compile -MMD -MF $out.d $f_flags -c $in -o $out\n' 217 ' description = FC $out\n' 218 ' depfile = $out.d\n' 219 '\n') 220 fd.write('rule F_LINK_SHARED\n' 221 ' command = $f_link $f_link_flags -shared -o $out $in $petsc_external_lib\n' 222 ' description = FLINK_SHARED $out\n' 223 '\n') 224 fd.write('rule GEN_NINJA\n' 225 ' command = $python $in --output=ninja\n' 226 ' generator = 1\n' 227 '\n') 228 petsc.gen_ninja(fd) 229 fd.write('\n') 230 fd.write('build %s : GEN_NINJA | %s %s %s %s\n' % (build_ninja, 231 os.path.abspath(__file__), 232 os.path.join(petsc.petsc_dir, 'lib','petsc','conf', 'variables'), 233 petsc.arch_path('lib','petsc','conf', 'petscvariables'), 234 ' '.join(os.path.join(petsc.petsc_dir, dep) for dep in petsc.gendeps))) 235 236def main(petsc_dir=None, petsc_arch=None, output=None, verbose=False): 237 if output is None: 238 output = 'gnumake' 239 writer = dict(gnumake=WriteGnuMake, ninja=WriteNinja) 240 petsc = Petsc(petsc_dir=petsc_dir, petsc_arch=petsc_arch, verbose=verbose) 241 writer[output](petsc) 242 petsc.summary() 243 244if __name__ == '__main__': 245 import optparse 246 parser = optparse.OptionParser() 247 parser.add_option('--verbose', help='Show mismatches between makefiles and the filesystem', action='store_true', default=False) 248 parser.add_option('--petsc-arch', help='Set PETSC_ARCH different from environment', default=os.environ.get('PETSC_ARCH')) 249 parser.add_option('--output', help='Location to write output file', default=None) 250 opts, extra_args = parser.parse_args() 251 if extra_args: 252 import sys 253 sys.stderr.write('Unknown arguments: %s\n' % ' '.join(extra_args)) 254 exit(1) 255 main(petsc_arch=opts.petsc_arch, output=opts.output, verbose=opts.verbose) 256