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') 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 fd.write('%s :=\n' % stem) 148 for lang in LANGS: 149 fd.write('%(stem)s.%(lang)s := %(srcs)s\n' % dict(stem=stem, lang=lang, srcs=' '.join(srcs[lang]))) 150 fd.write('%(stem)s += $(%(stem)s.%(lang)s)\n' % dict(stem=stem, lang=lang)) 151 for pkg in PKGS: 152 srcs = self.gen_pkg(pkg) 153 write('srcs-' + pkg, srcs) 154 return self.gendeps 155 156 def gen_ninja(self, fd): 157 libobjs = [] 158 for pkg in PKGS: 159 srcs = self.gen_pkg(pkg) 160 for lang in LANGS: 161 for src in srcs[lang]: 162 obj = '$objdir/%s.o' % src 163 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))) 164 libobjs.append(obj) 165 fd.write('\n') 166 fd.write('build $libdir/libpetsc.so : %s_LINK_SHARED %s\n\n' % ('CF'[self.have_fortran], ' '.join(libobjs))) 167 fd.write('build petsc : phony || $libdir/libpetsc.so\n\n') 168 169 def summary(self): 170 self.mistakes.summary() 171 172def WriteGnuMake(petsc): 173 arch_files = petsc.arch_path('lib','petsc','conf', 'files') 174 fd = open(arch_files, 'w') 175 gendeps = petsc.gen_gnumake(fd) 176 fd.write('\n') 177 fd.write('# Dependency to regenerate this file\n') 178 fd.write('%s : %s %s\n' % (os.path.relpath(arch_files, petsc.petsc_dir), 179 os.path.relpath(__file__, os.path.realpath(petsc.petsc_dir)), 180 ' '.join(gendeps))) 181 fd.write('\n') 182 fd.write('# Dummy dependencies in case makefiles are removed\n') 183 fd.write(''.join([dep + ':\n' for dep in gendeps])) 184 fd.close() 185 186def WriteNinja(petsc): 187 conf = dict() 188 parse_makefile(os.path.join(petsc.petsc_dir, 'lib', 'petsc','conf', 'variables'), conf) 189 parse_makefile(petsc.arch_path('lib','petsc','conf', 'petscvariables'), conf) 190 build_ninja = petsc.arch_path('build.ninja') 191 fd = open(build_ninja, 'w') 192 fd.write('objdir = obj-ninja\n') 193 fd.write('libdir = lib\n') 194 fd.write('c_compile = %(PCC)s\n' % conf) 195 fd.write('c_flags = %(PETSC_CC_INCLUDES)s %(PCC_FLAGS)s %(CCPPFLAGS)s\n' % conf) 196 fd.write('c_link = %(PCC_LINKER)s\n' % conf) 197 fd.write('c_link_flags = %(PCC_LINKER_FLAGS)s\n' % conf) 198 if petsc.have_fortran: 199 fd.write('f_compile = %(FC)s\n' % conf) 200 fd.write('f_flags = %(PETSC_FC_INCLUDES)s %(FC_FLAGS)s %(FCPPFLAGS)s\n' % conf) 201 fd.write('f_link = %(FC_LINKER)s\n' % conf) 202 fd.write('f_link_flags = %(FC_LINKER_FLAGS)s\n' % conf) 203 fd.write('petsc_external_lib = %(PETSC_EXTERNAL_LIB_BASIC)s\n' % conf) 204 fd.write('python = %(PYTHON)s\n' % conf) 205 fd.write('\n') 206 fd.write('rule C_COMPILE\n' 207 ' command = $c_compile -MMD -MF $out.d $c_flags -c $in -o $out\n' 208 ' description = CC $out\n' 209 ' depfile = $out.d\n' 210 # ' deps = gcc\n') # 'gcc' is default, 'msvc' only recognized by newer versions of ninja 211 '\n') 212 fd.write('rule C_LINK_SHARED\n' 213 ' command = $c_link $c_link_flags -shared -o $out $in $petsc_external_lib\n' 214 ' description = CLINK_SHARED $out\n' 215 '\n') 216 if petsc.have_fortran: 217 fd.write('rule F_COMPILE\n' 218 ' command = $f_compile -MMD -MF $out.d $f_flags -c $in -o $out\n' 219 ' description = FC $out\n' 220 ' depfile = $out.d\n' 221 '\n') 222 fd.write('rule F_LINK_SHARED\n' 223 ' command = $f_link $f_link_flags -shared -o $out $in $petsc_external_lib\n' 224 ' description = FLINK_SHARED $out\n' 225 '\n') 226 fd.write('rule GEN_NINJA\n' 227 ' command = $python $in --output=ninja\n' 228 ' generator = 1\n' 229 '\n') 230 petsc.gen_ninja(fd) 231 fd.write('\n') 232 fd.write('build %s : GEN_NINJA | %s %s %s %s\n' % (build_ninja, 233 os.path.abspath(__file__), 234 os.path.join(petsc.petsc_dir, 'lib','petsc','conf', 'variables'), 235 petsc.arch_path('lib','petsc','conf', 'petscvariables'), 236 ' '.join(os.path.join(petsc.petsc_dir, dep) for dep in petsc.gendeps))) 237 238def main(petsc_dir=None, petsc_arch=None, output=None, verbose=False): 239 if output is None: 240 output = 'gnumake' 241 writer = dict(gnumake=WriteGnuMake, ninja=WriteNinja) 242 petsc = Petsc(petsc_dir=petsc_dir, petsc_arch=petsc_arch, verbose=verbose) 243 writer[output](petsc) 244 petsc.summary() 245 246if __name__ == '__main__': 247 import optparse 248 parser = optparse.OptionParser() 249 parser.add_option('--verbose', help='Show mismatches between makefiles and the filesystem', action='store_true', default=False) 250 parser.add_option('--petsc-arch', help='Set PETSC_ARCH different from environment', default=os.environ.get('PETSC_ARCH')) 251 parser.add_option('--output', help='Location to write output file', default=None) 252 opts, extra_args = parser.parse_args() 253 if extra_args: 254 import sys 255 sys.stderr.write('Unknown arguments: %s\n' % ' '.join(extra_args)) 256 exit(1) 257 main(petsc_arch=opts.petsc_arch, output=opts.output, verbose=opts.verbose) 258