source: pyyaml/trunk/setup.py @ 298

Revision 298, 9.1 KB checked in by xi, 6 years ago (diff)

Fixed the distutils script to run when installed using easy_install and Pyrex is available.

RevLine 
[39]1
[150]2NAME = 'PyYAML'
[275]3VERSION = '3.06'
[150]4DESCRIPTION = "YAML parser and emitter for Python"
5LONG_DESCRIPTION = """\
6YAML is a data serialization format designed for human readability and
[156]7interaction with scripting languages.  PyYAML is a YAML parser and
8emitter for Python.
[150]9
[156]10PyYAML features a complete YAML 1.1 parser, Unicode support, pickle
11support, capable extension API, and sensible error messages.  PyYAML
12supports standard YAML tags and provides Python-specific tags that allow
13to represent an arbitrary Python object.
[150]14
[156]15PyYAML is applicable for a broad range of tasks from complex
16configuration files to object serialization and persistance."""
[39]17AUTHOR = "Kirill Simonov"
18AUTHOR_EMAIL = 'xi@resolvent.net'
[59]19LICENSE = "MIT"
[150]20PLATFORMS = "Any"
21URL = "http://pyyaml.org/wiki/PyYAML"
22DOWNLOAD_URL = "http://pyyaml.org/download/pyyaml/%s-%s.tar.gz" % (NAME, VERSION)
23CLASSIFIERS = [
[275]24    "Development Status :: 5 - Production/Stable",
[150]25    "Intended Audience :: Developers",
26    "License :: OSI Approved :: MIT License",
27    "Operating System :: OS Independent",
28    "Programming Language :: Python",
29    "Topic :: Software Development :: Libraries :: Python Modules",
30    "Topic :: Text Processing :: Markup",
31]
[39]32
[281]33
[292]34LIBYAML_CHECK = """
35#include <yaml.h>
36
37int main(void) {
38    yaml_parser_t parser;
39    yaml_emitter_t emitter;
40
41    yaml_parser_initialize(&parser);
42    yaml_parser_delete(&parser);
43
44    yaml_emitter_initialize(&emitter);
45    yaml_emitter_delete(&emitter);
46
47    return 0;
48}
49"""
50
51
[298]52import sys, os.path
53
[292]54from distutils import log
[290]55from distutils.core import setup, Command
56from distutils.core import Distribution as _Distribution
57from distutils.core import Extension as _Extension
[292]58from distutils.dir_util import mkpath
[290]59from distutils.command.build_ext import build_ext as _build_ext
[294]60from distutils.errors import CompileError, LinkError, DistutilsPlatformError
[39]61
[298]62if 'setuptools.extension' in sys.modules:
63    _Extension = sys.modules['setuptools.extension']._Extension
64    sys.modules['distutils.core'].Extension = _Extension
65    sys.modules['distutils.extension'].Extension = _Extension
66    sys.modules['distutils.command.build_ext'].Extension = _Extension
67
[290]68try:
69    from Pyrex.Distutils import Extension as _Extension
70    from Pyrex.Distutils import build_ext as _build_ext
71    with_pyrex = True
72except ImportError:
73    with_pyrex = False
74
75
76
77class Distribution(_Distribution):
78
79    def __init__(self, attrs=None):
80        _Distribution.__init__(self, attrs)
81        if not self.ext_modules:
82            return
[294]83        for idx in range(len(self.ext_modules)-1, -1, -1):
84            ext = self.ext_modules[idx]
[290]85            if not isinstance(ext, Extension):
86                continue
87            setattr(self, ext.attr_name, None)
88            self.global_options = [
89                    (ext.option_name, None,
[292]90                        "include %s (default if %s is available)"
91                        % (ext.feature_description, ext.feature_name)),
[290]92                    (ext.neg_option_name, None,
[292]93                        "exclude %s" % ext.feature_description),
[290]94            ] + self.global_options
95            self.negative_opt = self.negative_opt.copy()
96            self.negative_opt[ext.neg_option_name] = ext.option_name
97
98
99class Extension(_Extension):
100
[292]101    def __init__(self, name, sources, feature_name, feature_description,
102            feature_check, **kwds):
[290]103        if not with_pyrex:
104            for filename in sources[:]:
105                base, ext = os.path.splitext(filename)
[294]106                if ext == '.pyx':
107                    sources.remove(filename)
108                    sources.append('%s.c' % base)
[290]109        _Extension.__init__(self, name, sources, **kwds)
110        self.feature_name = feature_name
111        self.feature_description = feature_description
[292]112        self.feature_check = feature_check
[290]113        self.attr_name = 'with_' + feature_name.replace('-', '_')
114        self.option_name = 'with-' + feature_name
115        self.neg_option_name = 'without-' + feature_name
116
117
118class build_ext(_build_ext):
119
[294]120    def run(self):
121        optional = True
122        disabled = True
123        for ext in self.extensions:
124            if isinstance(ext, Extension):
125                with_ext = getattr(self.distribution, ext.attr_name)
126                if with_ext is None:
127                    disabled = False
128                elif with_ext:
129                    optional = False
130                    disabled = False
131            else:
132                optional = False
133                disabled = False
134                break
135        if disabled:
136            return
137        try:
138            _build_ext.run(self)
139        except DistutilsPlatformError, exc:
140            if optional:
141                log.warn(str(exc))
142                log.warn("skipping build_ext")
143            else:
144                raise
145
[290]146    def get_source_files(self):
147        self.check_extensions_list(self.extensions)
148        filenames = []
149        for ext in self.extensions:
150            if with_pyrex:
151                self.pyrex_sources(ext.sources, ext)
152            for filename in ext.sources:
153                filenames.append(filename)
154                base = os.path.splitext(filename)[0]
155                for ext in ['c', 'h', 'pyx', 'pxd']:
156                    filename = '%s.%s' % (base, ext)
157                    if filename not in filenames and os.path.isfile(filename):
158                        filenames.append(filename)
159        return filenames
160
161    def build_extensions(self):
162        self.check_extensions_list(self.extensions)
163        for ext in self.extensions:
164            if isinstance(ext, Extension):
[292]165                with_ext = getattr(self.distribution, ext.attr_name)
166                if with_ext is None:
167                    with_ext = self.check_extension_availability(ext)
168                if not with_ext:
[290]169                    continue
170            if with_pyrex:
171                ext.sources = self.pyrex_sources(ext.sources, ext)
172            self.build_extension(ext)
173
[292]174    def check_extension_availability(self, ext):
175        cache = os.path.join(self.build_temp, 'check_%s.out' % ext.feature_name)
176        if not self.force and os.path.isfile(cache):
177            data = open(cache).read().strip()
178            if data == '1':
179                return True
180            elif data == '0':
181                return False
182        mkpath(self.build_temp)
183        src = os.path.join(self.build_temp, 'check_%s.c' % ext.feature_name)
184        open(src, 'w').write(ext.feature_check)
185        log.info("checking if %s compiles" % ext.feature_name)
186        try:
187            [obj] = self.compiler.compile([src],
188                    macros=ext.define_macros+[(undef,) for undef in ext.undef_macros],
189                    include_dirs=ext.include_dirs,
190                    extra_postargs=(ext.extra_compile_args or []),
191                    depends=ext.depends)
192        except CompileError:
193            log.warn("%s appears not to be installed" % ext.feature_name)
194            log.warn("(if %s is installed, you may need to specify"
195                    % ext.feature_name)
196            log.warn(" the option --include-dirs or uncomment and modify")
197            log.warn(" the parameter include_dirs in setup.cfg)")
198            open(cache, 'w').write('0\n')
199            return False
200        prog = 'check_%s' % ext.feature_name
201        log.info("checking if %s links" % ext.feature_name)
202        try:
203            self.compiler.link_executable([obj], prog,
204                    output_dir=self.build_temp,
205                    libraries=ext.libraries,
206                    library_dirs=ext.library_dirs,
207                    runtime_library_dirs=ext.runtime_library_dirs,
208                    extra_postargs=(ext.extra_link_args or []))
209        except LinkError:
210            log.warn("unable to link against %s" % ext.feature_name)
211            log.warn("(if %s is installed correctly, you may need to specify"
212                    % ext.feature_name)
213            log.warn(" the option --library-dirs or uncomment and modify")
214            log.warn(" the parameter library_dirs in setup.cfg)")
215            open(cache, 'w').write('0\n')
216            return False
217        open(cache, 'w').write('1\n')
218        return True
[290]219
[292]220
[290]221class test(Command):
222
223    user_options = []
224
225    def initialize_options(self):
226        pass
227
228    def finalize_options(self):
229        pass
230
231    def run(self):
232        build_cmd = self.get_finalized_command('build')
233        build_cmd.run()
234        sys.path.insert(0, build_cmd.build_lib)
235        sys.path.insert(0, 'tests')
236        import test_all
237        test_all.main()
238
239
[227]240if __name__ == '__main__':
[39]241
[227]242    setup(
243        name=NAME,
244        version=VERSION,
245        description=DESCRIPTION,
246        long_description=LONG_DESCRIPTION,
247        author=AUTHOR,
248        author_email=AUTHOR_EMAIL,
249        license=LICENSE,
250        platforms=PLATFORMS,
251        url=URL,
252        download_url=DOWNLOAD_URL,
253        classifiers=CLASSIFIERS,
[39]254
[227]255        package_dir={'': 'lib'},
256        packages=['yaml'],
[290]257        ext_modules=[
[294]258            Extension('_yaml', ['ext/_yaml.pyx'],
[292]259                'libyaml', "LibYAML bindings", LIBYAML_CHECK,
[290]260                libraries=['yaml']),
261        ],
[275]262
[290]263        distclass=Distribution,
264        cmdclass={
265            'build_ext': build_ext,
[295]266#            'test': test,
[275]267        },
[227]268    )
269
Note: See TracBrowser for help on using the repository browser.