xref: /petsc/src/binding/petsc4py/conf/confpetsc.py (revision a68bbae58a07f2fb515cab24a67de1159d72e8a2)
1# --------------------------------------------------------------------
2
3import re
4import os
5import sys
6import glob
7import copy
8import warnings
9
10try:
11    from cStringIO import StringIO
12except ImportError:
13    from io import StringIO
14
15try:
16    import setuptools
17except ImportError:
18    setuptools = None
19
20if setuptools:
21    from setuptools import setup as _setup
22    from setuptools import Extension as _Extension
23    from setuptools import Command
24else:
25    from distutils.core import setup as _setup
26    from distutils.core import Extension as _Extension
27    from distutils.core import Command
28
29def import_command(cmd):
30    try:
31        from importlib import import_module
32    except ImportError:
33        def import_module(n):
34            return __import__(n, fromlist=[None])
35    try:
36        if not setuptools: raise ImportError
37        mod = import_module('setuptools.command.' + cmd)
38        return getattr(mod, cmd)
39    except ImportError:
40        mod = import_module('distutils.command.' + cmd)
41        return getattr(mod, cmd)
42
43_config    = import_command('config')
44_build     = import_command('build')
45_build_ext = import_command('build_ext')
46_install   = import_command('install')
47
48from distutils import log
49from distutils import sysconfig
50from distutils.util import execute
51from distutils.util import split_quoted
52from distutils.errors import DistutilsError
53
54try:
55    from setuptools import dep_util
56except ImportError:
57    from distutils import dep_util
58
59try:
60    from packaging.version import Version
61except ImportError:
62    try:
63        from setuptools.extern.packaging.version import Version
64    except ImportError:
65        from distutils.version import StrictVersion as Version
66
67# --------------------------------------------------------------------
68
69# Cython
70
71CYTHON = '0.29.32'
72
73def cython_req():
74    return CYTHON
75
76def cython_chk(VERSION, verbose=True):
77    #
78    def warn(message):
79        if not verbose: return
80        ruler, ws, nl = "*"*80, " " ,"\n"
81        pyexe = sys.executable
82        advise = "$ %s -m pip install --upgrade cython" % pyexe
83        def printer(*s): sys.stderr.write(" ".join(s)+"\n")
84        printer(ruler, nl)
85        printer(ws, message, nl)
86        printer(ws, ws, advise, nl)
87        printer(ruler)
88    #
89    try:
90        import Cython
91    except ImportError:
92        warn("You need Cython to generate C source files.")
93        return False
94    #
95    CYTHON_VERSION = Cython.__version__
96    m = re.match(r"(\d+\.\d+(?:\.\d+)?).*", CYTHON_VERSION)
97    if not m:
98        warn("Cannot parse Cython version string {0!r}"
99             .format(CYTHON_VERSION))
100        return False
101    REQUIRED = Version(VERSION)
102    PROVIDED = Version(m.groups()[0])
103    if PROVIDED < REQUIRED:
104        warn("You need Cython >= {0} (you have version {1})"
105             .format(VERSION, CYTHON_VERSION))
106        return False
107    #
108    if verbose:
109        log.info("using Cython %s" % CYTHON_VERSION)
110    return True
111
112def cython_run(
113    source, target=None,
114    depends=(), includes=(),
115    workdir=None, force=False,
116    VERSION="0.0",
117):
118    if target is None:
119        target = os.path.splitext(source)[0]+'.c'
120    cwd = os.getcwd()
121    try:
122        if workdir:
123            os.chdir(workdir)
124        alldeps = [source]
125        for dep in depends:
126            alldeps += glob.glob(dep)
127        if not (force or dep_util.newer_group(alldeps, target)):
128            log.debug("skipping '%s' -> '%s' (up-to-date)",
129                      source, target)
130            return
131    finally:
132        os.chdir(cwd)
133    require = 'Cython >= %s' % VERSION
134    if setuptools and not cython_chk(VERSION, verbose=False):
135        if sys.modules.get('Cython'):
136            removed = getattr(sys.modules['Cython'], '__version__', '')
137            log.info("removing Cython %s from sys.modules" % removed)
138            pkgname = re.compile(r'cython(\.|$)', re.IGNORECASE)
139            for modname in list(sys.modules.keys()):
140                if pkgname.match(modname):
141                    del sys.modules[modname]
142        try:
143            install_setup_requires = setuptools._install_setup_requires
144            with warnings.catch_warnings():
145                if hasattr(setuptools, 'SetuptoolsDeprecationWarning'):
146                    category = setuptools.SetuptoolsDeprecationWarning
147                    warnings.simplefilter('ignore', category)
148                log.info("fetching build requirement '%s'" % require)
149                install_setup_requires(dict(setup_requires=[require]))
150        except Exception:
151            log.info("failed to fetch build requirement '%s'" % require)
152    if not cython_chk(VERSION):
153        raise DistutilsError("unsatisfied build requirement '%s'" % require)
154    #
155    log.info("cythonizing '%s' -> '%s'", source, target)
156    from cythonize import cythonize
157    args = []
158    if workdir:
159        args += ['--working', workdir]
160    args += [source]
161    if target:
162        args += ['--output-file', target]
163    err = cythonize(args)
164    if err:
165        raise DistutilsError(
166            "Cython failure: '%s' -> '%s'" % (source, target)
167        )
168
169
170# --------------------------------------------------------------------
171
172def fix_config_vars(names, values):
173    values = list(values)
174    if 'CONDA_BUILD' in os.environ:
175        return values
176    if sys.platform == 'darwin':
177        if 'ARCHFLAGS' in os.environ:
178            ARCHFLAGS = os.environ['ARCHFLAGS']
179            for i, flag in enumerate(list(values)):
180                flag, count = re.subn('-arch\s+\w+', ' ', str(flag))
181                if count and ARCHFLAGS:
182                    flag = flag + ' ' + ARCHFLAGS
183                values[i] = flag
184        if 'SDKROOT' in os.environ:
185            SDKROOT = os.environ['SDKROOT']
186            for i, flag in enumerate(list(values)):
187                flag, count = re.subn('-isysroot [^ \t]*', ' ', str(flag))
188                if count and SDKROOT:
189                    flag = flag + ' ' + '-isysroot ' + SDKROOT
190                values[i] = flag
191    return values
192
193def get_config_vars(*names):
194    # Core Python configuration
195    values = sysconfig.get_config_vars(*names)
196    # Do any distutils flags fixup right now
197    values = fix_config_vars(names, values)
198    return values
199
200from distutils.unixccompiler import UnixCCompiler
201rpath_option_orig = UnixCCompiler.runtime_library_dir_option
202def rpath_option(compiler, dir):
203    option = rpath_option_orig(compiler, dir)
204    if sys.platform[:5] == 'linux':
205        if option.startswith('-R'):
206            option =  option.replace('-R', '-Wl,-rpath,', 1)
207        elif option.startswith('-Wl,-R'):
208            option =  option.replace('-Wl,-R', '-Wl,-rpath,', 1)
209    return option
210UnixCCompiler.runtime_library_dir_option = rpath_option
211
212# --------------------------------------------------------------------
213
214class PetscConfig:
215
216    def __init__(self, petsc_dir, petsc_arch, dest_dir=None):
217        if dest_dir is None:
218            dest_dir = os.environ.get('DESTDIR')
219        self.configdict = { }
220        if not petsc_dir:
221            raise DistutilsError("PETSc not found")
222        if not os.path.isdir(petsc_dir):
223            raise DistutilsError("invalid PETSC_DIR: %s" % petsc_dir)
224        self.version    = self._get_petsc_version(petsc_dir)
225        self.configdict = self._get_petsc_config(petsc_dir, petsc_arch)
226        self.PETSC_DIR  = self['PETSC_DIR']
227        self.PETSC_ARCH = self['PETSC_ARCH']
228        self.DESTDIR = dest_dir
229        language_map = {'CONLY':'c', 'CXXONLY':'c++'}
230        self.language = language_map[self['PETSC_LANGUAGE']]
231
232    def __getitem__(self, item):
233        return self.configdict[item]
234
235    def get(self, item, default=None):
236        return self.configdict.get(item, default)
237
238    def configure(self, extension, compiler=None):
239        self.configure_extension(extension)
240        if compiler is not None:
241            self.configure_compiler(compiler)
242
243    def _get_petsc_version(self, petsc_dir):
244        import re
245        version_re = {
246            'major'  : re.compile(r"#define\s+PETSC_VERSION_MAJOR\s+(\d+)"),
247            'minor'  : re.compile(r"#define\s+PETSC_VERSION_MINOR\s+(\d+)"),
248            'micro'  : re.compile(r"#define\s+PETSC_VERSION_SUBMINOR\s+(\d+)"),
249            'release': re.compile(r"#define\s+PETSC_VERSION_RELEASE\s+(-*\d+)"),
250            }
251        petscversion_h = os.path.join(petsc_dir, 'include', 'petscversion.h')
252        with open(petscversion_h, 'rt') as f: data = f.read()
253        major = int(version_re['major'].search(data).groups()[0])
254        minor = int(version_re['minor'].search(data).groups()[0])
255        micro = int(version_re['micro'].search(data).groups()[0])
256        release = int(version_re['release'].search(data).groups()[0])
257        return  (major, minor, micro), (release == 1)
258
259    def _get_petsc_config(self, petsc_dir, petsc_arch):
260        from os.path import join, isdir, exists
261        PETSC_DIR  = petsc_dir
262        PETSC_ARCH = petsc_arch
263        #
264        confdir = join('lib', 'petsc', 'conf')
265        if not (PETSC_ARCH and isdir(join(PETSC_DIR, PETSC_ARCH))):
266            petscvars = join(PETSC_DIR, confdir, 'petscvariables')
267            PETSC_ARCH = makefile(open(petscvars, 'rt')).get('PETSC_ARCH')
268        if not (PETSC_ARCH and isdir(join(PETSC_DIR, PETSC_ARCH))):
269            PETSC_ARCH = ''
270        #
271        variables = join(PETSC_DIR, confdir, 'variables')
272        if not exists(variables):
273            variables  = join(PETSC_DIR, PETSC_ARCH, confdir, 'variables')
274        petscvariables = join(PETSC_DIR, PETSC_ARCH, confdir, 'petscvariables')
275        #
276        with open(variables) as f:
277            contents = f.read()
278        with open(petscvariables) as f:
279            contents += f.read()
280        #
281        confstr  = 'PETSC_DIR  = %s\n' % PETSC_DIR
282        confstr += 'PETSC_ARCH = %s\n' % PETSC_ARCH
283        confstr += contents
284        confdict = makefile(StringIO(confstr))
285        return confdict
286
287    def _configure_ext(self, ext, dct, append=False):
288        extdict = ext.__dict__
289        for key, values in dct.items():
290            if key in extdict:
291                for value in values:
292                    if value not in extdict[key]:
293                        if not append:
294                            extdict[key].insert(0, value)
295                        else:
296                            extdict[key].append(value)
297
298    def configure_extension(self, extension):
299        # includes and libraries
300        # paths in PETSc config files point to final installation location, but
301        # we might be building against PETSc in staging location (DESTDIR) when
302        # DESTDIR is set, so append DESTDIR (if nonempty) to those paths
303        petsc_inc = flaglist(prepend_to_flags(self.DESTDIR, self['PETSC_CC_INCLUDES']))
304        lib_flags = prepend_to_flags(self.DESTDIR, '-L%s %s' % \
305                (self['PETSC_LIB_DIR'], self['PETSC_LIB_BASIC']))
306        petsc_lib = flaglist(lib_flags)
307        # runtime_library_dirs is not supported on Windows
308        if sys.platform != 'win32':
309            # if DESTDIR is set, then we're building against PETSc in a staging
310            # directory, but rpath needs to point to final install directory.
311            rpath = strip_prefix(self.DESTDIR, self['PETSC_LIB_DIR'])
312            petsc_lib['runtime_library_dirs'].append(rpath)
313
314        # Link in extra libraries on static builds
315        if self['BUILDSHAREDLIB'] != 'yes':
316            petsc_ext_lib = split_quoted(self['PETSC_EXTERNAL_LIB_BASIC'])
317            petsc_lib['extra_link_args'].extend(petsc_ext_lib)
318        self._configure_ext(extension, petsc_inc, append=True)
319        self._configure_ext(extension, petsc_lib)
320
321    def configure_compiler(self, compiler):
322        if compiler.compiler_type != 'unix': return
323        getenv = os.environ.get
324        # distutils C/C++ compiler
325        (cc, cflags, ccshared, cxx) = get_config_vars(
326            'CC', 'CFLAGS',  'CCSHARED', 'CXX')
327        ccshared = getenv('CCSHARED', ccshared or '')
328        cflags = getenv('CFLAGS', cflags or '')
329        cflags = cflags.replace('-Wstrict-prototypes', '')
330        # distutils linker
331        (ldflags, ldshared, so_ext) = get_config_vars(
332            'LDFLAGS', 'LDSHARED', 'SO')
333        ld = cc
334        ldshared = getenv('LDSHARED', ldshared)
335        ldflags = getenv('LDFLAGS', cflags + ' ' + (ldflags or ''))
336        ldcmd = split_quoted(ld) + split_quoted(ldflags)
337        ldshared = [flg for flg in split_quoted(ldshared) if flg not in ldcmd and (flg.find('/lib/spack/env')<0)]
338        ldshared = str.join(' ', ldshared)
339        #
340        def get_flags(cmd):
341            if not cmd: return ''
342            cmd = split_quoted(cmd)
343            if os.path.basename(cmd[0]) == 'xcrun':
344                del cmd[0]
345                while True:
346                    if cmd[0] == '-sdk':
347                        del cmd[0:2]
348                        continue
349                    if cmd[0] == '-log':
350                        del cmd[0]
351                        continue
352                    break
353            return ' '.join(cmd[1:])
354        # PETSc C compiler
355        PCC = self['PCC']
356        PCC_FLAGS = get_flags(cc) + ' ' + self['PCC_FLAGS']
357        PCC_FLAGS = PCC_FLAGS.replace('-fvisibility=hidden', '')
358        PCC = getenv('PCC', PCC) + ' ' +  getenv('PCCFLAGS', PCC_FLAGS)
359        PCC_SHARED = str.join(' ', (PCC, ccshared, cflags))
360        # PETSc C++ compiler
361        PCXX = PCC if self.language == 'c++' else self.get('CXX', cxx)
362        # PETSc linker
363        PLD = self['PCC_LINKER']
364        PLD_FLAGS = get_flags(ld) + ' ' + self['PCC_LINKER_FLAGS']
365        PLD_FLAGS = PLD_FLAGS.replace('-fvisibility=hidden', '')
366        PLD = getenv('PLD', PLD) + ' ' + getenv('PLDFLAGS', PLD_FLAGS)
367        PLD_SHARED = str.join(' ', (PLD, ldshared, ldflags))
368        #
369        compiler.set_executables(
370            compiler     = PCC,
371            compiler_cxx = PCXX,
372            linker_exe   = PLD,
373            compiler_so  = PCC_SHARED,
374            linker_so    = PLD_SHARED,
375            )
376        compiler.shared_lib_extension = so_ext
377        #
378        if sys.platform == 'darwin':
379            for attr in ('preprocessor',
380                         'compiler', 'compiler_cxx', 'compiler_so',
381                         'linker_so', 'linker_exe'):
382                compiler_cmd = getattr(compiler, attr, [])
383                while '-mno-fused-madd' in compiler_cmd:
384                    compiler_cmd.remove('-mno-fused-madd')
385
386    def log_info(self):
387        PETSC_DIR  = self['PETSC_DIR']
388        PETSC_ARCH = self['PETSC_ARCH']
389        version = ".".join([str(i) for i in self.version[0]])
390        release = ("development", "release")[self.version[1]]
391        version_info = version + ' ' + release
392        integer_size = '%s-bit' % self['PETSC_INDEX_SIZE']
393        scalar_type  = self['PETSC_SCALAR']
394        precision    = self['PETSC_PRECISION']
395        language     = self['PETSC_LANGUAGE']
396        compiler     = self['PCC']
397        linker       = self['PCC_LINKER']
398        log.info('PETSC_DIR:    %s' % PETSC_DIR )
399        log.info('PETSC_ARCH:   %s' % PETSC_ARCH )
400        log.info('version:      %s' % version_info)
401        log.info('integer-size: %s' % integer_size)
402        log.info('scalar-type:  %s' % scalar_type)
403        log.info('precision:    %s' % precision)
404        log.info('language:     %s' % language)
405        log.info('compiler:     %s' % compiler)
406        log.info('linker:       %s' % linker)
407
408# --------------------------------------------------------------------
409
410class Extension(_Extension):
411    pass
412
413# --------------------------------------------------------------------
414
415cmd_petsc_opts = [
416    ('petsc-dir=', None,
417     "define PETSC_DIR, overriding environmental variables"),
418    ('petsc-arch=', None,
419     "define PETSC_ARCH, overriding environmental variables"),
420    ]
421
422
423class config(_config):
424
425    Configure = PetscConfig
426
427    user_options = _config.user_options + cmd_petsc_opts
428
429    def initialize_options(self):
430        _config.initialize_options(self)
431        self.petsc_dir  = None
432        self.petsc_arch = None
433
434    def get_config_arch(self, arch):
435        return config.Configure(self.petsc_dir, arch)
436
437    def run(self):
438        _config.run(self)
439        self.petsc_dir = config.get_petsc_dir(self.petsc_dir)
440        if self.petsc_dir is None: return
441        petsc_arch = config.get_petsc_arch(self.petsc_dir, self.petsc_arch)
442        log.info('-' * 70)
443        log.info('PETSC_DIR:   %s' % self.petsc_dir)
444        arch_list = petsc_arch
445        if not arch_list :
446            arch_list = [ None ]
447        for arch in arch_list:
448            conf = self.get_config_arch(arch)
449            archname    = conf.PETSC_ARCH or conf['PETSC_ARCH']
450            scalar_type = conf['PETSC_SCALAR']
451            precision   = conf['PETSC_PRECISION']
452            language    = conf['PETSC_LANGUAGE']
453            compiler    = conf['PCC']
454            linker      = conf['PCC_LINKER']
455            log.info('-'*70)
456            log.info('PETSC_ARCH:  %s' % archname)
457            log.info(' * scalar-type: %s' % scalar_type)
458            log.info(' * precision:   %s' % precision)
459            log.info(' * language:    %s' % language)
460            log.info(' * compiler:    %s' % compiler)
461            log.info(' * linker:      %s' % linker)
462        log.info('-' * 70)
463
464    #@staticmethod
465    def get_petsc_dir(petsc_dir):
466        if not petsc_dir: return None
467        petsc_dir = os.path.expandvars(petsc_dir)
468        if not petsc_dir or '$PETSC_DIR' in petsc_dir:
469            try:
470                import petsc
471                petsc_dir = petsc.get_petsc_dir()
472            except ImportError:
473                log.warn("PETSC_DIR not specified")
474                return None
475        petsc_dir = os.path.expanduser(petsc_dir)
476        petsc_dir = os.path.abspath(petsc_dir)
477        return config.chk_petsc_dir(petsc_dir)
478    get_petsc_dir = staticmethod(get_petsc_dir)
479
480    #@staticmethod
481    def chk_petsc_dir(petsc_dir):
482        if not os.path.isdir(petsc_dir):
483            log.error('invalid PETSC_DIR: %s (ignored)' % petsc_dir)
484            return None
485        return petsc_dir
486    chk_petsc_dir = staticmethod(chk_petsc_dir)
487
488    #@staticmethod
489    def get_petsc_arch(petsc_dir, petsc_arch):
490        if not petsc_dir: return None
491        petsc_arch = os.path.expandvars(petsc_arch)
492        if (not petsc_arch or '$PETSC_ARCH' in petsc_arch):
493            petsc_arch = ''
494            petsc_conf = os.path.join(petsc_dir, 'lib', 'petsc', 'conf')
495            if os.path.isdir(petsc_conf):
496                petscvariables = os.path.join(petsc_conf, 'petscvariables')
497                if os.path.exists(petscvariables):
498                    conf = makefile(open(petscvariables, 'rt'))
499                    petsc_arch = conf.get('PETSC_ARCH', '')
500        petsc_arch = petsc_arch.split(os.pathsep)
501        petsc_arch = unique(petsc_arch)
502        petsc_arch = [arch for arch in petsc_arch if arch]
503        return config.chk_petsc_arch(petsc_dir, petsc_arch)
504    get_petsc_arch = staticmethod(get_petsc_arch)
505
506    #@staticmethod
507    def chk_petsc_arch(petsc_dir, petsc_arch):
508        valid_archs = []
509        for arch in petsc_arch:
510            arch_path = os.path.join(petsc_dir, arch)
511            if os.path.isdir(arch_path):
512                valid_archs.append(arch)
513            else:
514                log.warn("invalid PETSC_ARCH: %s (ignored)" % arch)
515        return valid_archs
516    chk_petsc_arch = staticmethod(chk_petsc_arch)
517
518
519class build(_build):
520
521    user_options = _build.user_options + cmd_petsc_opts
522
523    def initialize_options(self):
524        _build.initialize_options(self)
525        self.petsc_dir  = None
526        self.petsc_arch = None
527
528    def finalize_options(self):
529        _build.finalize_options(self)
530        self.set_undefined_options('config',
531                                   ('petsc_dir',  'petsc_dir'),
532                                   ('petsc_arch', 'petsc_arch'))
533        self.petsc_dir  = config.get_petsc_dir(self.petsc_dir)
534        self.petsc_arch = config.get_petsc_arch(self.petsc_dir,
535                                                self.petsc_arch)
536
537    sub_commands = \
538        [('build_src', lambda *args: True)] + \
539        _build.sub_commands
540
541
542class build_src(Command):
543    description = "build C sources from Cython files"
544
545    user_options = [
546        ('force', 'f',
547         "forcibly build everything (ignore file timestamps)"),
548        ]
549
550    boolean_options = ['force']
551
552    def initialize_options(self):
553        self.force = False
554
555    def finalize_options(self):
556        self.set_undefined_options('build',
557                                   ('force', 'force'),
558                                   )
559
560    def run(self):
561        sources = getattr(self, 'sources', [])
562        for source in sources:
563            cython_run(
564                force=self.force,
565                VERSION=cython_req(),
566                **source
567            )
568
569
570class build_ext(_build_ext):
571
572    user_options = _build_ext.user_options + cmd_petsc_opts
573
574    def initialize_options(self):
575        _build_ext.initialize_options(self)
576        self.petsc_dir  = None
577        self.petsc_arch = None
578        self._outputs = []
579
580    def finalize_options(self):
581        _build_ext.finalize_options(self)
582        self.set_undefined_options('build',
583                                   ('petsc_dir',  'petsc_dir'),
584                                   ('petsc_arch', 'petsc_arch'))
585        if ((sys.platform.startswith('linux') or
586             sys.platform.startswith('gnu') or
587             sys.platform.startswith('sunos')) and
588            sysconfig.get_config_var('Py_ENABLE_SHARED')):
589            py_version = sysconfig.get_python_version()
590            bad_pylib_dir = os.path.join(sys.prefix, "lib",
591                                         "python" + py_version,
592                                         "config")
593            try:
594                self.library_dirs.remove(bad_pylib_dir)
595            except ValueError:
596                pass
597            pylib_dir = sysconfig.get_config_var("LIBDIR")
598            if pylib_dir not in self.library_dirs:
599                self.library_dirs.append(pylib_dir)
600            if pylib_dir not in self.rpath:
601                self.rpath.append(pylib_dir)
602            if sys.exec_prefix == '/usr':
603                self.library_dirs.remove(pylib_dir)
604                self.rpath.remove(pylib_dir)
605
606    def _copy_ext(self, ext):
607        extclass = ext.__class__
608        fullname = self.get_ext_fullname(ext.name)
609        modpath = str.split(fullname, '.')
610        pkgpath = os.path.join('', *modpath[0:-1])
611        name = modpath[-1]
612        sources = list(ext.sources)
613        newext = extclass(name, sources)
614        newext.__dict__.update(copy.deepcopy(ext.__dict__))
615        newext.name = name
616        return pkgpath, newext
617
618    def _build_ext_arch(self, ext, pkgpath, arch):
619        build_temp = self.build_temp
620        build_lib  = self.build_lib
621        try:
622            self.build_temp = os.path.join(build_temp, arch)
623            self.build_lib  = os.path.join(build_lib, pkgpath, arch)
624            _build_ext.build_extension(self, ext)
625        finally:
626            self.build_temp = build_temp
627            self.build_lib  = build_lib
628
629    def get_config_arch(self, arch):
630        return config.Configure(self.petsc_dir, arch)
631
632    def build_extension(self, ext):
633        if not isinstance(ext, Extension):
634            return _build_ext.build_extension(self, ext)
635        petsc_arch = self.petsc_arch
636        if not petsc_arch:
637            petsc_arch = [ None ]
638        for arch in petsc_arch:
639            config = self.get_config_arch(arch)
640            ARCH = arch or config['PETSC_ARCH']
641            if ARCH not in self.PETSC_ARCH_LIST:
642                self.PETSC_ARCH_LIST.append(ARCH)
643            self.DESTDIR = config.DESTDIR
644            ext.language = config.language
645            config.log_info()
646            pkgpath, newext = self._copy_ext(ext)
647            config.configure(newext, self.compiler)
648            self._build_ext_arch(newext, pkgpath, ARCH)
649
650    def run(self):
651        self.build_sources()
652        _build_ext.run(self)
653
654    def build_sources(self):
655        if 'build_src' in self.distribution.cmdclass:
656            self.run_command('build_src')
657
658    def build_extensions(self, *args, **kargs):
659        self.PETSC_ARCH_LIST = []
660        _build_ext.build_extensions(self, *args,**kargs)
661        if not self.PETSC_ARCH_LIST: return
662        self.build_configuration(self.PETSC_ARCH_LIST)
663
664    def build_configuration(self, arch_list):
665        #
666        template, variables = self.get_config_data(arch_list)
667        config_data = template % variables
668        #
669        build_lib   = self.build_lib
670        dist_name   = self.distribution.get_name()
671        config_file = os.path.join(build_lib, dist_name, 'lib',
672                                   dist_name.replace('4py', '') + '.cfg')
673        #
674        def write_file(filename, data):
675            with open(filename, 'w') as fh:
676                fh.write(config_data)
677        execute(write_file, (config_file, config_data),
678                msg='writing %s' % config_file,
679                verbose=self.verbose, dry_run=self.dry_run)
680
681    def get_config_data(self, arch_list):
682        DESTDIR = self.DESTDIR
683        template = "\n".join([
684            "PETSC_DIR  = %(PETSC_DIR)s",
685            "PETSC_ARCH = %(PETSC_ARCH)s",
686        ]) + "\n"
687        variables = {
688            'PETSC_DIR'  : strip_prefix(DESTDIR, self.petsc_dir),
689            'PETSC_ARCH' : os.path.pathsep.join(arch_list),
690        }
691        return template, variables
692
693    def copy_extensions_to_source(self):
694        build_py = self.get_finalized_command('build_py')
695        for ext in self.extensions:
696            inp_file, reg_file = self._get_inplace_equivalent(build_py, ext)
697
698            arch_list = ['']
699            if isinstance(ext, Extension) and self.petsc_arch:
700                arch_list = self.petsc_arch[:]
701
702            file_pairs = []
703            inp_head, inp_tail = os.path.split(inp_file)
704            reg_head, reg_tail = os.path.split(reg_file)
705            for arch in arch_list:
706                inp_file = os.path.join(inp_head, arch, inp_tail)
707                reg_file = os.path.join(reg_head, arch, reg_tail)
708                file_pairs.append((inp_file, reg_file))
709
710            for inp_file, reg_file in file_pairs:
711                if os.path.exists(reg_file) or not ext.optional:
712                    dest_dir, _ = os.path.split(inp_file)
713                    self.mkpath(dest_dir)
714                    self.copy_file(reg_file, inp_file, level=self.verbose)
715
716    def get_outputs(self):
717        self.check_extensions_list(self.extensions)
718        outputs = []
719        for ext in self.extensions:
720            fullname = self.get_ext_fullname(ext.name)
721            filename = self.get_ext_filename(fullname)
722            if isinstance(ext, Extension) and self.petsc_arch:
723                head, tail = os.path.split(filename)
724                for arch in self.petsc_arch:
725                    outfile = os.path.join(self.build_lib, head, arch, tail)
726                    outputs.append(outfile)
727            else:
728                outfile = os.path.join(self.build_lib, filename)
729                outputs.append(outfile)
730        outputs = list(set(outputs))
731        return outputs
732
733
734class install(_install):
735
736    def initialize_options(self):
737        with warnings.catch_warnings():
738            if setuptools:
739                if hasattr(setuptools, 'SetuptoolsDeprecationWarning'):
740                    category = setuptools.SetuptoolsDeprecationWarning
741                    warnings.simplefilter('ignore', category)
742            _install.initialize_options(self)
743        self.old_and_unmanageable = True
744
745
746cmdclass_list = [
747    config,
748    build,
749    build_src,
750    build_ext,
751    install,
752]
753
754# --------------------------------------------------------------------
755
756def setup(**attrs):
757    cmdclass = attrs.setdefault('cmdclass', {})
758    for cmd in cmdclass_list:
759        cmdclass.setdefault(cmd.__name__, cmd)
760    build_src.sources = attrs.pop('cython_sources', None)
761    use_setup_requires = False  # handle Cython requirement ourselves
762    if setuptools and build_src.sources and use_setup_requires:
763        version = cython_req()
764        if not cython_chk(version, verbose=False):
765            reqs = attrs.setdefault('setup_requires', [])
766            reqs += ['Cython>='+version]
767    return _setup(**attrs)
768
769# --------------------------------------------------------------------
770
771if setuptools:
772    try:
773        from setuptools.command import egg_info as mod_egg_info
774        _FileList = mod_egg_info.FileList
775        class FileList(_FileList):
776            def process_template_line(self, line):
777                level = log.set_threshold(log.ERROR)
778                try:
779                    _FileList.process_template_line(self, line)
780                finally:
781                    log.set_threshold(level)
782        mod_egg_info.FileList = FileList
783    except (ImportError, AttributeError):
784        pass
785
786# --------------------------------------------------------------------
787
788def append(seq, item):
789    if item not in seq:
790        seq.append(item)
791
792def append_dict(conf, dct):
793    for key, values in dct.items():
794        if key in conf:
795            for value in values:
796                if value not in conf[key]:
797                    conf[key].append(value)
798def unique(seq):
799    res = []
800    for item in seq:
801        if item not in res:
802            res.append(item)
803    return res
804
805def flaglist(flags):
806
807    conf = {
808        'define_macros'       : [],
809        'undef_macros'        : [],
810        'include_dirs'        : [],
811
812        'libraries'           : [],
813        'library_dirs'        : [],
814        'runtime_library_dirs': [],
815
816        'extra_compile_args'  : [],
817        'extra_link_args'     : [],
818        }
819
820    if type(flags) is str:
821        flags = flags.split()
822
823    switch = '-Wl,'
824    newflags = []
825    linkopts = []
826    for f in flags:
827        if f.startswith(switch):
828            if len(f) > 4:
829                append(linkopts, f[4:])
830        else:
831            append(newflags, f)
832    if linkopts:
833        newflags.append(switch + ','.join(linkopts))
834    flags = newflags
835
836    append_next_word = None
837
838    for word in flags:
839
840        if append_next_word is not None:
841            append(append_next_word, word)
842            append_next_word = None
843            continue
844
845        switch, value = word[0:2], word[2:]
846
847        if switch == "-I":
848            append(conf['include_dirs'], value)
849        elif switch == "-D":
850            try:
851                idx = value.index("=")
852                macro = (value[:idx], value[idx+1:])
853            except ValueError:
854                macro = (value, None)
855            append(conf['define_macros'], macro)
856        elif switch == "-U":
857            append(conf['undef_macros'], value)
858        elif switch == "-l":
859            append(conf['libraries'], value)
860        elif switch == "-L":
861            append(conf['library_dirs'], value)
862        elif switch == "-R":
863            append(conf['runtime_library_dirs'], value)
864        elif word.startswith("-Wl"):
865            linkopts = word.split(',')
866            append_dict(conf, flaglist(linkopts[1:]))
867        elif word == "-rpath":
868            append_next_word = conf['runtime_library_dirs']
869        elif word == "-Xlinker":
870            append_next_word = conf['extra_link_args']
871        else:
872            #log.warn("unrecognized flag '%s'" % word)
873            pass
874    return conf
875
876def prepend_to_flags(path, flags):
877    """Prepend a path to compiler flags with absolute paths"""
878    if not path:
879        return flags
880    def append_path(m):
881        switch = m.group(1)
882        open_quote = m.group(4)
883        old_path = m.group(5)
884        close_quote = m.group(6)
885        if os.path.isabs(old_path):
886            moded_path = os.path.normpath(path + os.path.sep + old_path)
887            return switch + open_quote + moded_path + close_quote
888        return m.group(0)
889    return re.sub(r'((^|\s+)(-I|-L))(\s*["\']?)(\S+)(["\']?)',
890            append_path, flags)
891
892def strip_prefix(prefix, string):
893    if not prefix:
894        return string
895    return re.sub(r'^' + prefix, '', string)
896
897# --------------------------------------------------------------------
898
899from distutils.text_file import TextFile
900
901# Regexes needed for parsing Makefile-like syntaxes
902import re as _re
903_variable_rx = _re.compile("([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)")
904_findvar1_rx = _re.compile(r"\$\(([A-Za-z][A-Za-z0-9_]*)\)")
905_findvar2_rx = _re.compile(r"\${([A-Za-z][A-Za-z0-9_]*)}")
906
907def makefile(fileobj, dct=None):
908    """Parse a Makefile-style file.
909
910    A dictionary containing name/value pairs is returned.  If an
911    optional dictionary is passed in as the second argument, it is
912    used instead of a new dictionary.
913    """
914    fp = TextFile(file=fileobj,
915                  strip_comments=1,
916                  skip_blanks=1,
917                  join_lines=1)
918
919    if dct is None:
920        dct = {}
921    done = {}
922    notdone = {}
923
924    while 1:
925        line = fp.readline()
926        if line is None: # eof
927            break
928        m = _variable_rx.match(line)
929        if m:
930            n, v = m.group(1, 2)
931            v = str.strip(v)
932            if "$" in v:
933                notdone[n] = v
934            else:
935                try: v = int(v)
936                except ValueError: pass
937                done[n] = v
938                try: del notdone[n]
939                except KeyError: pass
940    fp.close()
941
942    # do variable interpolation here
943    while notdone:
944        for name in list(notdone.keys()):
945            value = notdone[name]
946            m = _findvar1_rx.search(value) or _findvar2_rx.search(value)
947            if m:
948                n = m.group(1)
949                found = True
950                if n in done:
951                    item = str(done[n])
952                elif n in notdone:
953                    # get it on a subsequent round
954                    found = False
955                else:
956                    done[n] = item = ""
957                if found:
958                    after = value[m.end():]
959                    value = value[:m.start()] + item + after
960                    if "$" in after:
961                        notdone[name] = value
962                    else:
963                        try: value = int(value)
964                        except ValueError:
965                            done[name] = str.strip(value)
966                        else:
967                            done[name] = value
968                        del notdone[name]
969            else:
970                # bogus variable reference;
971                # just drop it since we can't deal
972                del notdone[name]
973    # save the results in the global dictionary
974    dct.update(done)
975    return dct
976
977# --------------------------------------------------------------------
978