xref: /petsc/src/binding/petsc4py/conf/confpetsc.py (revision df4cd43f92eaa320656440c40edb1046daee8f75)
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, preppend=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 preppend:
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
319        self._configure_ext(extension, petsc_inc, preppend=True)
320        self._configure_ext(extension, petsc_lib)
321
322    def configure_compiler(self, compiler):
323        if compiler.compiler_type != 'unix': return
324        getenv = os.environ.get
325        # distutils C/C++ compiler
326        (cc, cflags, ccshared, cxx) = get_config_vars(
327            'CC', 'CFLAGS',  'CCSHARED', 'CXX')
328        ccshared = getenv('CCSHARED', ccshared or '')
329        cflags = getenv('CFLAGS', cflags or '')
330        cflags = cflags.replace('-Wstrict-prototypes', '')
331        # distutils linker
332        (ldflags, ldshared, so_ext) = get_config_vars(
333            'LDFLAGS', 'LDSHARED', 'SO')
334        ld = cc
335        ldshared = getenv('LDSHARED', ldshared)
336        ldflags = getenv('LDFLAGS', cflags + ' ' + (ldflags or ''))
337        ldcmd = split_quoted(ld) + split_quoted(ldflags)
338        ldshared = [flg for flg in split_quoted(ldshared) if flg not in ldcmd]
339        ldshared = str.join(' ', ldshared)
340        #
341        def get_flags(cmd):
342            if not cmd: return ''
343            cmd = split_quoted(cmd)
344            if os.path.basename(cmd[0]) == 'xcrun':
345                del cmd[0]
346                while True:
347                    if cmd[0] == '-sdk':
348                        del cmd[0:2]
349                        continue
350                    if cmd[0] == '-log':
351                        del cmd[0]
352                        continue
353                    break
354            return ' '.join(cmd[1:])
355        # PETSc C compiler
356        PCC = self['PCC']
357        PCC_FLAGS = get_flags(cc) + ' ' + self['PCC_FLAGS']
358        PCC_FLAGS = PCC_FLAGS.replace('-fvisibility=hidden', '')
359        PCC = getenv('PCC', PCC) + ' ' +  getenv('PCCFLAGS', PCC_FLAGS)
360        PCC_SHARED = str.join(' ', (PCC, ccshared, cflags))
361        # PETSc C++ compiler
362        PCXX = PCC if self.language == 'c++' else self.get('CXX', cxx)
363        # PETSc linker
364        PLD = self['PCC_LINKER']
365        PLD_FLAGS = get_flags(ld) + ' ' + self['PCC_LINKER_FLAGS']
366        PLD_FLAGS = PLD_FLAGS.replace('-fvisibility=hidden', '')
367        PLD = getenv('PLD', PLD) + ' ' + getenv('PLDFLAGS', PLD_FLAGS)
368        PLD_SHARED = str.join(' ', (PLD, ldshared, ldflags))
369        #
370        compiler.set_executables(
371            compiler     = PCC,
372            compiler_cxx = PCXX,
373            linker_exe   = PLD,
374            compiler_so  = PCC_SHARED,
375            linker_so    = PLD_SHARED,
376            )
377        compiler.shared_lib_extension = so_ext
378        #
379        if sys.platform == 'darwin':
380            for attr in ('preprocessor',
381                         'compiler', 'compiler_cxx', 'compiler_so',
382                         'linker_so', 'linker_exe'):
383                compiler_cmd = getattr(compiler, attr, [])
384                while '-mno-fused-madd' in compiler_cmd:
385                    compiler_cmd.remove('-mno-fused-madd')
386
387    def log_info(self):
388        PETSC_DIR  = self['PETSC_DIR']
389        PETSC_ARCH = self['PETSC_ARCH']
390        version = ".".join([str(i) for i in self.version[0]])
391        release = ("development", "release")[self.version[1]]
392        version_info = version + ' ' + release
393        integer_size = '%s-bit' % self['PETSC_INDEX_SIZE']
394        scalar_type  = self['PETSC_SCALAR']
395        precision    = self['PETSC_PRECISION']
396        language     = self['PETSC_LANGUAGE']
397        compiler     = self['PCC']
398        linker       = self['PCC_LINKER']
399        log.info('PETSC_DIR:    %s' % PETSC_DIR )
400        log.info('PETSC_ARCH:   %s' % PETSC_ARCH )
401        log.info('version:      %s' % version_info)
402        log.info('integer-size: %s' % integer_size)
403        log.info('scalar-type:  %s' % scalar_type)
404        log.info('precision:    %s' % precision)
405        log.info('language:     %s' % language)
406        log.info('compiler:     %s' % compiler)
407        log.info('linker:       %s' % linker)
408
409# --------------------------------------------------------------------
410
411class Extension(_Extension):
412    pass
413
414# --------------------------------------------------------------------
415
416cmd_petsc_opts = [
417    ('petsc-dir=', None,
418     "define PETSC_DIR, overriding environmental variables"),
419    ('petsc-arch=', None,
420     "define PETSC_ARCH, overriding environmental variables"),
421    ]
422
423
424class config(_config):
425
426    Configure = PetscConfig
427
428    user_options = _config.user_options + cmd_petsc_opts
429
430    def initialize_options(self):
431        _config.initialize_options(self)
432        self.petsc_dir  = None
433        self.petsc_arch = None
434
435    def get_config_arch(self, arch):
436        return config.Configure(self.petsc_dir, arch)
437
438    def run(self):
439        _config.run(self)
440        self.petsc_dir = config.get_petsc_dir(self.petsc_dir)
441        if self.petsc_dir is None: return
442        petsc_arch = config.get_petsc_arch(self.petsc_dir, self.petsc_arch)
443        log.info('-' * 70)
444        log.info('PETSC_DIR:   %s' % self.petsc_dir)
445        arch_list = petsc_arch
446        if not arch_list :
447            arch_list = [ None ]
448        for arch in arch_list:
449            conf = self.get_config_arch(arch)
450            archname    = conf.PETSC_ARCH or conf['PETSC_ARCH']
451            scalar_type = conf['PETSC_SCALAR']
452            precision   = conf['PETSC_PRECISION']
453            language    = conf['PETSC_LANGUAGE']
454            compiler    = conf['PCC']
455            linker      = conf['PCC_LINKER']
456            log.info('-'*70)
457            log.info('PETSC_ARCH:  %s' % archname)
458            log.info(' * scalar-type: %s' % scalar_type)
459            log.info(' * precision:   %s' % precision)
460            log.info(' * language:    %s' % language)
461            log.info(' * compiler:    %s' % compiler)
462            log.info(' * linker:      %s' % linker)
463        log.info('-' * 70)
464
465    #@staticmethod
466    def get_petsc_dir(petsc_dir):
467        if not petsc_dir: return None
468        petsc_dir = os.path.expandvars(petsc_dir)
469        if not petsc_dir or '$PETSC_DIR' in petsc_dir:
470            try:
471                import petsc
472                petsc_dir = petsc.get_petsc_dir()
473            except ImportError:
474                log.warn("PETSC_DIR not specified")
475                return None
476        petsc_dir = os.path.expanduser(petsc_dir)
477        petsc_dir = os.path.abspath(petsc_dir)
478        return config.chk_petsc_dir(petsc_dir)
479    get_petsc_dir = staticmethod(get_petsc_dir)
480
481    #@staticmethod
482    def chk_petsc_dir(petsc_dir):
483        if not os.path.isdir(petsc_dir):
484            log.error('invalid PETSC_DIR: %s (ignored)' % petsc_dir)
485            return None
486        return petsc_dir
487    chk_petsc_dir = staticmethod(chk_petsc_dir)
488
489    #@staticmethod
490    def get_petsc_arch(petsc_dir, petsc_arch):
491        if not petsc_dir: return None
492        petsc_arch = os.path.expandvars(petsc_arch)
493        if (not petsc_arch or '$PETSC_ARCH' in petsc_arch):
494            petsc_arch = ''
495            petsc_conf = os.path.join(petsc_dir, 'lib', 'petsc', 'conf')
496            if os.path.isdir(petsc_conf):
497                petscvariables = os.path.join(petsc_conf, 'petscvariables')
498                if os.path.exists(petscvariables):
499                    conf = makefile(open(petscvariables, 'rt'))
500                    petsc_arch = conf.get('PETSC_ARCH', '')
501        petsc_arch = petsc_arch.split(os.pathsep)
502        petsc_arch = unique(petsc_arch)
503        petsc_arch = [arch for arch in petsc_arch if arch]
504        return config.chk_petsc_arch(petsc_dir, petsc_arch)
505    get_petsc_arch = staticmethod(get_petsc_arch)
506
507    #@staticmethod
508    def chk_petsc_arch(petsc_dir, petsc_arch):
509        valid_archs = []
510        for arch in petsc_arch:
511            arch_path = os.path.join(petsc_dir, arch)
512            if os.path.isdir(arch_path):
513                valid_archs.append(arch)
514            else:
515                log.warn("invalid PETSC_ARCH: %s (ignored)" % arch)
516        return valid_archs
517    chk_petsc_arch = staticmethod(chk_petsc_arch)
518
519
520class build(_build):
521
522    user_options = _build.user_options + cmd_petsc_opts
523
524    def initialize_options(self):
525        _build.initialize_options(self)
526        self.petsc_dir  = None
527        self.petsc_arch = None
528
529    def finalize_options(self):
530        _build.finalize_options(self)
531        self.set_undefined_options('config',
532                                   ('petsc_dir',  'petsc_dir'),
533                                   ('petsc_arch', 'petsc_arch'))
534        self.petsc_dir  = config.get_petsc_dir(self.petsc_dir)
535        self.petsc_arch = config.get_petsc_arch(self.petsc_dir,
536                                                self.petsc_arch)
537
538    sub_commands = \
539        [('build_src', lambda *args: True)] + \
540        _build.sub_commands
541
542
543class build_src(Command):
544    description = "build C sources from Cython files"
545
546    user_options = [
547        ('force', 'f',
548         "forcibly build everything (ignore file timestamps)"),
549        ]
550
551    boolean_options = ['force']
552
553    def initialize_options(self):
554        self.force = False
555
556    def finalize_options(self):
557        self.set_undefined_options('build',
558                                   ('force', 'force'),
559                                   )
560
561    def run(self):
562        sources = getattr(self, 'sources', [])
563        for source in sources:
564            cython_run(
565                force=self.force,
566                VERSION=cython_req(),
567                **source
568            )
569
570
571class build_ext(_build_ext):
572
573    user_options = _build_ext.user_options + cmd_petsc_opts
574
575    def initialize_options(self):
576        _build_ext.initialize_options(self)
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',
584                                   ('petsc_dir',  'petsc_dir'),
585                                   ('petsc_arch', 'petsc_arch'))
586        if ((sys.platform.startswith('linux') or
587             sys.platform.startswith('gnu') or
588             sys.platform.startswith('sunos')) and
589            sysconfig.get_config_var('Py_ENABLE_SHARED')):
590            py_version = sysconfig.get_python_version()
591            bad_pylib_dir = os.path.join(sys.prefix, "lib",
592                                         "python" + py_version,
593                                         "config")
594            try:
595                self.library_dirs.remove(bad_pylib_dir)
596            except ValueError:
597                pass
598            pylib_dir = sysconfig.get_config_var("LIBDIR")
599            if pylib_dir not in self.library_dirs:
600                self.library_dirs.append(pylib_dir)
601            if pylib_dir not in self.rpath:
602                self.rpath.append(pylib_dir)
603            if sys.exec_prefix == '/usr':
604                self.library_dirs.remove(pylib_dir)
605                self.rpath.remove(pylib_dir)
606
607    def _copy_ext(self, ext):
608        extclass = ext.__class__
609        fullname = self.get_ext_fullname(ext.name)
610        modpath = str.split(fullname, '.')
611        pkgpath = os.path.join('', *modpath[0:-1])
612        name = modpath[-1]
613        sources = list(ext.sources)
614        newext = extclass(name, sources)
615        newext.__dict__.update(copy.deepcopy(ext.__dict__))
616        newext.name = name
617        return pkgpath, newext
618
619    def _build_ext_arch(self, ext, pkgpath, arch):
620        build_temp = self.build_temp
621        build_lib  = self.build_lib
622        try:
623            self.build_temp = os.path.join(build_temp, arch)
624            self.build_lib  = os.path.join(build_lib, pkgpath, arch)
625            _build_ext.build_extension(self, ext)
626        finally:
627            self.build_temp = build_temp
628            self.build_lib  = build_lib
629
630    def get_config_arch(self, arch):
631        return config.Configure(self.petsc_dir, arch)
632
633    def build_extension(self, ext):
634        if not isinstance(ext, Extension):
635            return _build_ext.build_extension(self, ext)
636        petsc_arch = self.petsc_arch
637        if not petsc_arch:
638            petsc_arch = [ None ]
639        for arch in petsc_arch:
640            config = self.get_config_arch(arch)
641            ARCH = arch or config['PETSC_ARCH']
642            if ARCH not in self.PETSC_ARCH_LIST:
643                self.PETSC_ARCH_LIST.append(ARCH)
644            self.DESTDIR = config.DESTDIR
645            ext.language = config.language
646            config.log_info()
647            pkgpath, newext = self._copy_ext(ext)
648            config.configure(newext, self.compiler)
649            self._build_ext_arch(newext, pkgpath, ARCH)
650
651    def run(self):
652        self.build_sources()
653        _build_ext.run(self)
654
655    def build_sources(self):
656        if 'build_src' in self.distribution.cmdclass:
657            self.run_command('build_src')
658
659    def build_extensions(self, *args, **kargs):
660        self.PETSC_ARCH_LIST = []
661        _build_ext.build_extensions(self, *args,**kargs)
662        if not self.PETSC_ARCH_LIST: return
663        self.build_configuration(self.PETSC_ARCH_LIST)
664
665    def build_configuration(self, arch_list):
666        #
667        template, variables = self.get_config_data(arch_list)
668        config_data = template % variables
669        #
670        build_lib   = self.build_lib
671        dist_name   = self.distribution.get_name()
672        config_file = os.path.join(build_lib, dist_name, 'lib',
673                                   dist_name.replace('4py', '') + '.cfg')
674        #
675        def write_file(filename, data):
676            with open(filename, 'w') as fh:
677                fh.write(config_data)
678        execute(write_file, (config_file, config_data),
679                msg='writing %s' % config_file,
680                verbose=self.verbose, dry_run=self.dry_run)
681
682    def get_config_data(self, arch_list):
683        DESTDIR = self.DESTDIR
684        template = "\n".join([
685            "PETSC_DIR  = %(PETSC_DIR)s",
686            "PETSC_ARCH = %(PETSC_ARCH)s",
687        ]) + "\n"
688        variables = {
689            'PETSC_DIR'  : strip_prefix(DESTDIR, self.petsc_dir),
690            'PETSC_ARCH' : os.path.pathsep.join(arch_list),
691        }
692        return template, variables
693
694    def copy_extensions_to_source(self):
695        build_py = self.get_finalized_command('build_py')
696        for ext in self.extensions:
697            inp_file, reg_file = self._get_inplace_equivalent(build_py, ext)
698
699            arch_list = ['']
700            if isinstance(ext, Extension) and self.petsc_arch:
701                arch_list = self.petsc_arch[:]
702
703            file_pairs = []
704            inp_head, inp_tail = os.path.split(inp_file)
705            reg_head, reg_tail = os.path.split(reg_file)
706            for arch in arch_list:
707                inp_file = os.path.join(inp_head, arch, inp_tail)
708                reg_file = os.path.join(reg_head, arch, reg_tail)
709                file_pairs.append((inp_file, reg_file))
710
711            for inp_file, reg_file in file_pairs:
712                if os.path.exists(reg_file) or not ext.optional:
713                    dest_dir, _ = os.path.split(inp_file)
714                    self.mkpath(dest_dir)
715                    self.copy_file(reg_file, inp_file, level=self.verbose)
716
717    def get_outputs(self):
718        self.check_extensions_list(self.extensions)
719        outputs = []
720        for ext in self.extensions:
721            fullname = self.get_ext_fullname(ext.name)
722            filename = self.get_ext_filename(fullname)
723            if isinstance(ext, Extension) and self.petsc_arch:
724                head, tail = os.path.split(filename)
725                for arch in self.petsc_arch:
726                    outfile = os.path.join(self.build_lib, head, arch, tail)
727                    outputs.append(outfile)
728            else:
729                outfile = os.path.join(self.build_lib, filename)
730                outputs.append(outfile)
731        outputs = list(set(outputs))
732        return outputs
733
734
735class install(_install):
736
737    def initialize_options(self):
738        with warnings.catch_warnings():
739            if setuptools:
740                if hasattr(setuptools, 'SetuptoolsDeprecationWarning'):
741                    category = setuptools.SetuptoolsDeprecationWarning
742                    warnings.simplefilter('ignore', category)
743            _install.initialize_options(self)
744        self.old_and_unmanageable = True
745
746
747cmdclass_list = [
748    config,
749    build,
750    build_src,
751    build_ext,
752    install,
753]
754
755# --------------------------------------------------------------------
756
757def setup(**attrs):
758    cmdclass = attrs.setdefault('cmdclass', {})
759    for cmd in cmdclass_list:
760        cmdclass.setdefault(cmd.__name__, cmd)
761    build_src.sources = attrs.pop('cython_sources', None)
762    use_setup_requires = False  # handle Cython requirement ourselves
763    if setuptools and build_src.sources and use_setup_requires:
764        version = cython_req()
765        if not cython_chk(version, verbose=False):
766            reqs = attrs.setdefault('setup_requires', [])
767            reqs += ['Cython>='+version]
768    return _setup(**attrs)
769
770# --------------------------------------------------------------------
771
772if setuptools:
773    try:
774        from setuptools.command import egg_info as mod_egg_info
775        _FileList = mod_egg_info.FileList
776        class FileList(_FileList):
777            def process_template_line(self, line):
778                level = log.set_threshold(log.ERROR)
779                try:
780                    _FileList.process_template_line(self, line)
781                finally:
782                    log.set_threshold(level)
783        mod_egg_info.FileList = FileList
784    except (ImportError, AttributeError):
785        pass
786
787# --------------------------------------------------------------------
788
789def append(seq, item):
790    if item not in seq:
791        seq.append(item)
792
793def append_dict(conf, dct):
794    for key, values in dct.items():
795        if key in conf:
796            for value in values:
797                if value not in conf[key]:
798                    conf[key].append(value)
799def unique(seq):
800    res = []
801    for item in seq:
802        if item not in res:
803            res.append(item)
804    return res
805
806def flaglist(flags):
807
808    conf = {
809        'define_macros'       : [],
810        'undef_macros'        : [],
811        'include_dirs'        : [],
812
813        'libraries'           : [],
814        'library_dirs'        : [],
815        'runtime_library_dirs': [],
816
817        'extra_compile_args'  : [],
818        'extra_link_args'     : [],
819        }
820
821    if type(flags) is str:
822        flags = flags.split()
823
824    switch = '-Wl,'
825    newflags = []
826    linkopts = []
827    for f in flags:
828        if f.startswith(switch):
829            if len(f) > 4:
830                append(linkopts, f[4:])
831        else:
832            append(newflags, f)
833    if linkopts:
834        newflags.append(switch + ','.join(linkopts))
835    flags = newflags
836
837    append_next_word = None
838
839    for word in flags:
840
841        if append_next_word is not None:
842            append(append_next_word, word)
843            append_next_word = None
844            continue
845
846        switch, value = word[0:2], word[2:]
847
848        if switch == "-I":
849            append(conf['include_dirs'], value)
850        elif switch == "-D":
851            try:
852                idx = value.index("=")
853                macro = (value[:idx], value[idx+1:])
854            except ValueError:
855                macro = (value, None)
856            append(conf['define_macros'], macro)
857        elif switch == "-U":
858            append(conf['undef_macros'], value)
859        elif switch == "-l":
860            append(conf['libraries'], value)
861        elif switch == "-L":
862            append(conf['library_dirs'], value)
863        elif switch == "-R":
864            append(conf['runtime_library_dirs'], value)
865        elif word.startswith("-Wl"):
866            linkopts = word.split(',')
867            append_dict(conf, flaglist(linkopts[1:]))
868        elif word == "-rpath":
869            append_next_word = conf['runtime_library_dirs']
870        elif word == "-Xlinker":
871            append_next_word = conf['extra_link_args']
872        else:
873            #log.warn("unrecognized flag '%s'" % word)
874            pass
875    return conf
876
877def prepend_to_flags(path, flags):
878    """Prepend a path to compiler flags with absolute paths"""
879    if not path:
880        return flags
881    def append_path(m):
882        switch = m.group(1)
883        open_quote = m.group(4)
884        old_path = m.group(5)
885        close_quote = m.group(6)
886        if os.path.isabs(old_path):
887            moded_path = os.path.normpath(path + os.path.sep + old_path)
888            return switch + open_quote + moded_path + close_quote
889        return m.group(0)
890    return re.sub(r'((^|\s+)(-I|-L))(\s*["\']?)(\S+)(["\']?)',
891            append_path, flags)
892
893def strip_prefix(prefix, string):
894    if not prefix:
895        return string
896    return re.sub(r'^' + prefix, '', string)
897
898# --------------------------------------------------------------------
899
900from distutils.text_file import TextFile
901
902# Regexes needed for parsing Makefile-like syntaxes
903import re as _re
904_variable_rx = _re.compile("([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)")
905_findvar1_rx = _re.compile(r"\$\(([A-Za-z][A-Za-z0-9_]*)\)")
906_findvar2_rx = _re.compile(r"\${([A-Za-z][A-Za-z0-9_]*)}")
907
908def makefile(fileobj, dct=None):
909    """Parse a Makefile-style file.
910
911    A dictionary containing name/value pairs is returned.  If an
912    optional dictionary is passed in as the second argument, it is
913    used instead of a new dictionary.
914    """
915    fp = TextFile(file=fileobj,
916                  strip_comments=1,
917                  skip_blanks=1,
918                  join_lines=1)
919
920    if dct is None:
921        dct = {}
922    done = {}
923    notdone = {}
924
925    while 1:
926        line = fp.readline()
927        if line is None: # eof
928            break
929        m = _variable_rx.match(line)
930        if m:
931            n, v = m.group(1, 2)
932            v = str.strip(v)
933            if "$" in v:
934                notdone[n] = v
935            else:
936                try: v = int(v)
937                except ValueError: pass
938                done[n] = v
939                try: del notdone[n]
940                except KeyError: pass
941    fp.close()
942
943    # do variable interpolation here
944    while notdone:
945        for name in list(notdone.keys()):
946            value = notdone[name]
947            m = _findvar1_rx.search(value) or _findvar2_rx.search(value)
948            if m:
949                n = m.group(1)
950                found = True
951                if n in done:
952                    item = str(done[n])
953                elif n in notdone:
954                    # get it on a subsequent round
955                    found = False
956                else:
957                    done[n] = item = ""
958                if found:
959                    after = value[m.end():]
960                    value = value[:m.start()] + item + after
961                    if "$" in after:
962                        notdone[name] = value
963                    else:
964                        try: value = int(value)
965                        except ValueError:
966                            done[name] = str.strip(value)
967                        else:
968                            done[name] = value
969                        del notdone[name]
970            else:
971                # bogus variable reference;
972                # just drop it since we can't deal
973                del notdone[name]
974    # save the results in the global dictionary
975    dct.update(done)
976    return dct
977
978# --------------------------------------------------------------------
979