setup.py 11.9 KB
Newer Older
1 2

NAME = 'PyYAML'
3
VERSION = '3.10'
4 5
DESCRIPTION = "YAML parser and emitter for Python"
LONG_DESCRIPTION = """\
6 7 8
YAML is a data serialization format designed for human readability
and interaction with scripting languages.  PyYAML is a YAML parser
and emitter for Python.
9 10 11

PyYAML features a complete YAML 1.1 parser, Unicode support, pickle
support, capable extension API, and sensible error messages.  PyYAML
12 13
supports standard YAML tags and provides Python-specific tags that
allow to represent an arbitrary Python object.
14 15 16 17 18 19 20 21 22 23

PyYAML is applicable for a broad range of tasks from complex
configuration files to object serialization and persistance."""
AUTHOR = "Kirill Simonov"
AUTHOR_EMAIL = 'xi@resolvent.net'
LICENSE = "MIT"
PLATFORMS = "Any"
URL = "http://pyyaml.org/wiki/PyYAML"
DOWNLOAD_URL = "http://pyyaml.org/download/pyyaml/%s-%s.tar.gz" % (NAME, VERSION)
CLASSIFIERS = [
24
    "Development Status :: 5 - Production/Stable",
25 26 27 28
    "Intended Audience :: Developers",
    "License :: OSI Approved :: MIT License",
    "Operating System :: OS Independent",
    "Programming Language :: Python",
29 30 31 32 33
    "Programming Language :: Python :: 2",
    "Programming Language :: Python :: 2.3",
    "Programming Language :: Python :: 2.4",
    "Programming Language :: Python :: 2.5",
    "Programming Language :: Python :: 2.6",
34
    "Programming Language :: Python :: 2.7",
35 36
    "Programming Language :: Python :: 3",
    "Programming Language :: Python :: 3.0",
37
    "Programming Language :: Python :: 3.1",
38
    "Programming Language :: Python :: 3.2",
39 40 41 42
    "Topic :: Software Development :: Libraries :: Python Modules",
    "Topic :: Text Processing :: Markup",
]

43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61

LIBYAML_CHECK = """
#include <yaml.h>

int main(void) {
    yaml_parser_t parser;
    yaml_emitter_t emitter;

    yaml_parser_initialize(&parser);
    yaml_parser_delete(&parser);

    yaml_emitter_initialize(&emitter);
    yaml_emitter_delete(&emitter);

    return 0;
}
"""


62 63
import sys, os.path

64 65 66 67 68 69
from distutils import log
from distutils.core import setup, Command
from distutils.core import Distribution as _Distribution
from distutils.core import Extension as _Extension
from distutils.dir_util import mkpath
from distutils.command.build_ext import build_ext as _build_ext
70
from distutils.command.bdist_rpm import bdist_rpm as _bdist_rpm
71 72
from distutils.errors import CompileError, LinkError, DistutilsPlatformError

73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
if 'setuptools.extension' in sys.modules:
    _Extension = sys.modules['setuptools.extension']._Extension
    sys.modules['distutils.core'].Extension = _Extension
    sys.modules['distutils.extension'].Extension = _Extension
    sys.modules['distutils.command.build_ext'].Extension = _Extension

with_pyrex = None
if sys.version_info[0] < 3:
    try:
        from Cython.Distutils.extension import Extension as _Extension
        from Cython.Distutils import build_ext as _build_ext
        with_pyrex = 'cython'
    except ImportError:
        try:
            # Pyrex cannot build _yaml.c at the moment,
            # but it may get fixed eventually.
            from Pyrex.Distutils import Extension as _Extension
            from Pyrex.Distutils import build_ext as _build_ext
            with_pyrex = 'pyrex'
        except ImportError:
            pass
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116


class Distribution(_Distribution):

    def __init__(self, attrs=None):
        _Distribution.__init__(self, attrs)
        if not self.ext_modules:
            return
        for idx in range(len(self.ext_modules)-1, -1, -1):
            ext = self.ext_modules[idx]
            if not isinstance(ext, Extension):
                continue
            setattr(self, ext.attr_name, None)
            self.global_options = [
                    (ext.option_name, None,
                        "include %s (default if %s is available)"
                        % (ext.feature_description, ext.feature_name)),
                    (ext.neg_option_name, None,
                        "exclude %s" % ext.feature_description),
            ] + self.global_options
            self.negative_opt = self.negative_opt.copy()
            self.negative_opt[ext.neg_option_name] = ext.option_name

117 118 119 120 121 122 123 124 125 126
    def has_ext_modules(self):
        if not self.ext_modules:
            return False
        for ext in self.ext_modules:
            with_ext = self.ext_status(ext)
            if with_ext is None or with_ext:
                return True
        return False

    def ext_status(self, ext):
127 128
        if 'Java' in sys.version or 'IronPython' in sys.version or 'PyPy' in sys.version:
            return False
129 130 131 132 133 134
        if isinstance(ext, Extension):
            with_ext = getattr(self, ext.attr_name)
            return with_ext
        else:
            return True

135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160

class Extension(_Extension):

    def __init__(self, name, sources, feature_name, feature_description,
            feature_check, **kwds):
        if not with_pyrex:
            for filename in sources[:]:
                base, ext = os.path.splitext(filename)
                if ext == '.pyx':
                    sources.remove(filename)
                    sources.append('%s.c' % base)
        _Extension.__init__(self, name, sources, **kwds)
        self.feature_name = feature_name
        self.feature_description = feature_description
        self.feature_check = feature_check
        self.attr_name = 'with_' + feature_name.replace('-', '_')
        self.option_name = 'with-' + feature_name
        self.neg_option_name = 'without-' + feature_name


class build_ext(_build_ext):

    def run(self):
        optional = True
        disabled = True
        for ext in self.extensions:
161 162 163 164
            with_ext = self.distribution.ext_status(ext)
            if with_ext is None:
                disabled = False
            elif with_ext:
165 166 167 168 169 170 171
                optional = False
                disabled = False
                break
        if disabled:
            return
        try:
            _build_ext.run(self)
172 173
        except DistutilsPlatformError:
            exc = sys.exc_info()[1]
174 175 176 177 178 179 180 181 182 183
            if optional:
                log.warn(str(exc))
                log.warn("skipping build_ext")
            else:
                raise

    def get_source_files(self):
        self.check_extensions_list(self.extensions)
        filenames = []
        for ext in self.extensions:
184
            if with_pyrex == 'pyrex':
185
                self.pyrex_sources(ext.sources, ext)
186 187
            elif with_pyrex == 'cython':
                self.cython_sources(ext.sources, ext)
188 189 190 191 192 193 194 195 196
            for filename in ext.sources:
                filenames.append(filename)
                base = os.path.splitext(filename)[0]
                for ext in ['c', 'h', 'pyx', 'pxd']:
                    filename = '%s.%s' % (base, ext)
                    if filename not in filenames and os.path.isfile(filename):
                        filenames.append(filename)
        return filenames

197 198 199 200 201 202 203 204 205 206 207
    def get_outputs(self):
        self.check_extensions_list(self.extensions)
        outputs = []
        for ext in self.extensions:
            fullname = self.get_ext_fullname(ext.name)
            filename = os.path.join(self.build_lib,
                                    self.get_ext_filename(fullname))
            if os.path.isfile(filename):
                outputs.append(filename)
        return outputs

208 209 210
    def build_extensions(self):
        self.check_extensions_list(self.extensions)
        for ext in self.extensions:
211 212 213 214 215 216
            with_ext = self.distribution.ext_status(ext)
            if with_ext is None:
                with_ext = self.check_extension_availability(ext)
            if not with_ext:
                continue
            if with_pyrex == 'pyrex':
217
                ext.sources = self.pyrex_sources(ext.sources, ext)
218 219
            elif with_pyrex == 'cython':
                ext.sources = self.cython_sources(ext.sources, ext)
220 221 222 223 224 225 226 227 228 229 230 231 232
            self.build_extension(ext)

    def check_extension_availability(self, ext):
        cache = os.path.join(self.build_temp, 'check_%s.out' % ext.feature_name)
        if not self.force and os.path.isfile(cache):
            data = open(cache).read().strip()
            if data == '1':
                return True
            elif data == '0':
                return False
        mkpath(self.build_temp)
        src = os.path.join(self.build_temp, 'check_%s.c' % ext.feature_name)
        open(src, 'w').write(ext.feature_check)
233
        log.info("checking if %s is compilable" % ext.feature_name)
234 235 236 237 238 239 240
        try:
            [obj] = self.compiler.compile([src],
                    macros=ext.define_macros+[(undef,) for undef in ext.undef_macros],
                    include_dirs=ext.include_dirs,
                    extra_postargs=(ext.extra_compile_args or []),
                    depends=ext.depends)
        except CompileError:
241 242 243 244
            log.warn("")
            log.warn("%s is not found or a compiler error: forcing --%s"
                     % (ext.feature_name, ext.neg_option_name))
            log.warn("(if %s is installed correctly, you may need to"
245
                    % ext.feature_name)
246 247
            log.warn(" specify the option --include-dirs or uncomment and")
            log.warn(" modify the parameter include_dirs in setup.cfg)")
248 249 250
            open(cache, 'w').write('0\n')
            return False
        prog = 'check_%s' % ext.feature_name
251
        log.info("checking if %s is linkable" % ext.feature_name)
252 253 254 255 256 257 258 259
        try:
            self.compiler.link_executable([obj], prog,
                    output_dir=self.build_temp,
                    libraries=ext.libraries,
                    library_dirs=ext.library_dirs,
                    runtime_library_dirs=ext.runtime_library_dirs,
                    extra_postargs=(ext.extra_link_args or []))
        except LinkError:
260 261 262 263
            log.warn("")
            log.warn("%s is not found or a linker error: forcing --%s"
                     % (ext.feature_name, ext.neg_option_name))
            log.warn("(if %s is installed correctly, you may need to"
264
                    % ext.feature_name)
265 266
            log.warn(" specify the option --library-dirs or uncomment and")
            log.warn(" modify the parameter library_dirs in setup.cfg)")
267 268 269 270 271 272
            open(cache, 'w').write('0\n')
            return False
        open(cache, 'w').write('1\n')
        return True


273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
class bdist_rpm(_bdist_rpm):

    def _make_spec_file(self):
        argv0 = sys.argv[0]
        features = []
        for ext in self.distribution.ext_modules:
            if not isinstance(ext, Extension):
                continue
            with_ext = getattr(self.distribution, ext.attr_name)
            if with_ext is None:
                continue
            if with_ext:
                features.append('--'+ext.option_name)
            else:
                features.append('--'+ext.neg_option_name)
        sys.argv[0] = ' '.join([argv0]+features)
        spec_file = _bdist_rpm._make_spec_file(self)
        sys.argv[0] = argv0
        return spec_file


294 295 296 297 298 299 300 301 302 303 304 305 306 307
class test(Command):

    user_options = []

    def initialize_options(self):
        pass

    def finalize_options(self):
        pass

    def run(self):
        build_cmd = self.get_finalized_command('build')
        build_cmd.run()
        sys.path.insert(0, build_cmd.build_lib)
308 309 310 311
        if sys.version_info[0] < 3:
            sys.path.insert(0, 'tests/lib')
        else:
            sys.path.insert(0, 'tests/lib3')
312
        import test_all
313
        test_all.main([])
314

315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330

if __name__ == '__main__':

    setup(
        name=NAME,
        version=VERSION,
        description=DESCRIPTION,
        long_description=LONG_DESCRIPTION,
        author=AUTHOR,
        author_email=AUTHOR_EMAIL,
        license=LICENSE,
        platforms=PLATFORMS,
        url=URL,
        download_url=DOWNLOAD_URL,
        classifiers=CLASSIFIERS,

331
        package_dir={'': {2: 'lib', 3: 'lib3'}[sys.version_info[0]]},
332
        packages=['yaml'],
333 334 335 336 337 338 339
        ext_modules=[
            Extension('_yaml', ['ext/_yaml.pyx'],
                'libyaml', "LibYAML bindings", LIBYAML_CHECK,
                libraries=['yaml']),
        ],

        distclass=Distribution,
340

341 342
        cmdclass={
            'build_ext': build_ext,
343 344
            'bdist_rpm': bdist_rpm,
            'test': test,
345
        },
346 347
    )