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