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