1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3
4import io
5import os
6import pprint
7import shutil
8import sys
9import warnings
10
11from setuptools import setup
12from setuptools.extension import Extension
13
14pkg_name = 'levmar'
15url = 'https://github.com/bjodah/' + pkg_name
16license = 'GNU General Public Licence v2'  # Takeshi Kanmae's wrapper code has the MIT license
17
18levmar_sources = [
19    'levmar/levmar-2.6/lm.c',
20    'levmar/levmar-2.6/Axb.c',
21    'levmar/levmar-2.6/misc.c',
22    'levmar/levmar-2.6/lmlec.c',
23    'levmar/levmar-2.6/lmbc.c',
24    'levmar/levmar-2.6/lmblec.c',
25    'levmar/levmar-2.6/lmbleic.c'
26]
27
28
29def _path_under_setup(*args):
30    return os.path.join(os.path.dirname(__file__), *args)
31
32release_py_path = _path_under_setup(pkg_name, '_release.py')
33config_py_path = _path_under_setup(pkg_name, '_config.py')
34env = None  # silence pyflakes, 'env' is actually set on the next line
35exec(open(config_py_path).read())
36for k, v in list(env.items()):
37    env[k] = os.environ.get('%s_%s' % (pkg_name.upper(), k), v)
38
39
40USE_CYTHON = os.path.exists(_path_under_setup(pkg_name, '_levmar.pyx'))
41# Cythonize .pyx file if it exists (not in source distribution)
42ext_modules = []
43
44if len(sys.argv) > 1 and '--help' not in sys.argv[1:] and sys.argv[1] not in (
45        '--help-commands', 'egg_info', 'clean', '--version'):
46    import numpy as np
47    ext = '.pyx' if USE_CYTHON else '.c'
48    ext_modules = [Extension('%s._levmar' % pkg_name,
49                             [os.path.join('levmar', '_levmar' + ext)] + levmar_sources)]
50    if USE_CYTHON:
51        from Cython.Build import cythonize
52        ext_modules = cythonize(ext_modules)
53    ext_modules[0].include_dirs = ['levmar/levmar-2.6', np.get_include()]
54    if env['LAPACK']:
55        ext_modules[0].libraries += [env['LAPACK']]
56    if env['BLAS']:
57        ext_modules[0].libraries += [env['BLAS']]
58
59_version_env_var = '%s_RELEASE_VERSION' % pkg_name.upper()
60RELEASE_VERSION = os.environ.get(_version_env_var, '')
61
62# http://conda.pydata.org/docs/build.html#environment-variables-set-during-the-build-process
63if os.environ.get('CONDA_BUILD', '0') == '1':
64    try:
65        RELEASE_VERSION = 'v' + open(
66            '__conda_version__.txt', 'rt').readline().rstrip()
67    except IOError:
68        pass
69
70
71if len(RELEASE_VERSION) > 1:
72    if RELEASE_VERSION[0] != 'v':
73        raise ValueError("$%s does not start with 'v'" % _version_env_var)
74    TAGGED_RELEASE = True
75    __version__ = RELEASE_VERSION[1:]
76else:  # set `__version__` from _release.py:
77    TAGGED_RELEASE = False
78    exec(open(release_py_path).read())
79
80classifiers = [
81    'Intended Audience :: Science/Research',
82    'Topic :: Scientific/Engineering',
83    'Topic :: Scientific/Engineering :: Mathematics',
84    'Programming Language :: Python',
85    'Programming Language :: Python :: 2',
86    'Programming Language :: Python :: 2.7',
87    'Programming Language :: Python :: 3',
88    'Programming Language :: Python :: 3.4',
89    'Programming Language :: Python :: 3.5',
90    'License :: OSI Approved :: MIT License',
91]
92
93tests = [
94    '%s.tests' % pkg_name,
95]
96
97with io.open(_path_under_setup(pkg_name, '__init__.py'), 'rt', encoding='utf-8') as f:
98    short_description = f.read().split('"""')[1].split('\n')[1]
99if not 10 < len(short_description) < 255:
100    warnings.warn("Short description from __init__.py proably not read correctly")
101long_descr = io.open(_path_under_setup('README.rst'), encoding='utf-8').read()
102if not len(long_descr) > 100:
103    warnings.warn("Long description from README.rst probably not read correctly.")
104_author, _author_email = io.open(_path_under_setup('AUTHORS'), 'rt', encoding='utf-8').readline().split('<')
105_author_email = _author_email.split('>')[0].strip() if '@' in _author_email else None
106
107setup_kwargs = dict(
108    name=pkg_name,
109    version=__version__,
110    description=short_description,
111    long_description=long_descr,
112    classifiers=classifiers,
113    author=_author.strip(),
114    author_email=_author_email,
115    maintainer='Björn Dahlgren',
116    maintainer_email='bjodah@gmail.com',
117    url=url,
118    license=license,
119    packages=[pkg_name] + tests,
120    install_requires=['numpy'] + (['cython'] if USE_CYTHON else []),
121    setup_requires=['numpy'] + (['cython'] if USE_CYTHON else []),
122    extras_require={'docs': ['Sphinx', 'sphinx_rtd_theme', 'numpydoc']},
123    ext_modules=ext_modules,
124    zip_safe=False,
125)
126
127if __name__ == '__main__':
128    try:
129        if TAGGED_RELEASE:
130            # Same commit should generate different sdist
131            # depending on tagged version (set PYGSLODEIV2_RELEASE_VERSION)
132            # this will ensure source distributions contain the correct version
133            shutil.move(release_py_path, release_py_path+'__temp__')
134            open(release_py_path, 'wt').write(
135                "__version__ = '{}'\n".format(__version__))
136        shutil.move(config_py_path, config_py_path+'__temp__')
137        open(config_py_path, 'wt').write("env = {}\n".format(pprint.pformat(env)))
138        setup(**setup_kwargs)
139    finally:
140        if TAGGED_RELEASE:
141            shutil.move(release_py_path+'__temp__', release_py_path)
142        shutil.move(config_py_path+'__temp__', config_py_path)
143