source: pyyaml/trunk/setup.py @ 292

Revision 292, 7.9 KB checked in by xi, 6 years ago (diff)

Check if libyaml is installed before attempting to compile the libyaml bindings.

Line 
1
2NAME = 'PyYAML'
3VERSION = '3.06'
4DESCRIPTION = "YAML parser and emitter for Python"
5LONG_DESCRIPTION = """\
6YAML is a data serialization format designed for human readability and
7interaction with scripting languages.  PyYAML is a YAML parser and
8emitter for Python.
9
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.
14
15PyYAML is applicable for a broad range of tasks from complex
16configuration files to object serialization and persistance."""
17AUTHOR = "Kirill Simonov"
18AUTHOR_EMAIL = 'xi@resolvent.net'
19LICENSE = "MIT"
20PLATFORMS = "Any"
21URL = "http://pyyaml.org/wiki/PyYAML"
22DOWNLOAD_URL = "http://pyyaml.org/download/pyyaml/%s-%s.tar.gz" % (NAME, VERSION)
23CLASSIFIERS = [
24    "Development Status :: 5 - Production/Stable",
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]
32
33
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
52from distutils import log
53from distutils.core import setup, Command
54from distutils.core import Distribution as _Distribution
55from distutils.core import Extension as _Extension
56from distutils.dir_util import mkpath
57from distutils.command.build_ext import build_ext as _build_ext
58from distutils.errors import CompileError, LinkError
59
60try:
61    from Pyrex.Distutils import Extension as _Extension
62    from Pyrex.Distutils import build_ext as _build_ext
63    with_pyrex = True
64except ImportError:
65    with_pyrex = False
66
67import sys, os.path
68
69
70class Distribution(_Distribution):
71
72    def __init__(self, attrs=None):
73        _Distribution.__init__(self, attrs)
74        if not self.ext_modules:
75            return
76        for ext in reversed(self.ext_modules):
77            if not isinstance(ext, Extension):
78                continue
79            setattr(self, ext.attr_name, None)
80            self.global_options = [
81                    (ext.option_name, None,
82                        "include %s (default if %s is available)"
83                        % (ext.feature_description, ext.feature_name)),
84                    (ext.neg_option_name, None,
85                        "exclude %s" % ext.feature_description),
86            ] + self.global_options
87            self.negative_opt = self.negative_opt.copy()
88            self.negative_opt[ext.neg_option_name] = ext.option_name
89
90
91class Extension(_Extension):
92
93    def __init__(self, name, sources, feature_name, feature_description,
94            feature_check, **kwds):
95        if not with_pyrex:
96            for filename in sources[:]:
97                base, ext = os.path.splitext(filename)
98                if ext == 'pyx':
99                    sources.replace(filename, '%s.c' % base)
100        _Extension.__init__(self, name, sources, **kwds)
101        self.feature_name = feature_name
102        self.feature_description = feature_description
103        self.feature_check = feature_check
104        self.attr_name = 'with_' + feature_name.replace('-', '_')
105        self.option_name = 'with-' + feature_name
106        self.neg_option_name = 'without-' + feature_name
107
108
109class build_ext(_build_ext):
110
111    def get_source_files(self):
112        self.check_extensions_list(self.extensions)
113        filenames = []
114        for ext in self.extensions:
115            if with_pyrex:
116                self.pyrex_sources(ext.sources, ext)
117            for filename in ext.sources:
118                filenames.append(filename)
119                base = os.path.splitext(filename)[0]
120                for ext in ['c', 'h', 'pyx', 'pxd']:
121                    filename = '%s.%s' % (base, ext)
122                    if filename not in filenames and os.path.isfile(filename):
123                        filenames.append(filename)
124        return filenames
125
126    def build_extensions(self):
127        self.check_extensions_list(self.extensions)
128        for ext in self.extensions:
129            if isinstance(ext, Extension):
130                with_ext = getattr(self.distribution, ext.attr_name)
131                if with_ext is None:
132                    with_ext = self.check_extension_availability(ext)
133                if not with_ext:
134                    continue
135            if with_pyrex:
136                ext.sources = self.pyrex_sources(ext.sources, ext)
137            self.build_extension(ext)
138
139    def check_extension_availability(self, ext):
140        cache = os.path.join(self.build_temp, 'check_%s.out' % ext.feature_name)
141        if not self.force and os.path.isfile(cache):
142            data = open(cache).read().strip()
143            if data == '1':
144                return True
145            elif data == '0':
146                return False
147        mkpath(self.build_temp)
148        src = os.path.join(self.build_temp, 'check_%s.c' % ext.feature_name)
149        open(src, 'w').write(ext.feature_check)
150        log.info("checking if %s compiles" % ext.feature_name)
151        try:
152            [obj] = self.compiler.compile([src],
153                    macros=ext.define_macros+[(undef,) for undef in ext.undef_macros],
154                    include_dirs=ext.include_dirs,
155                    extra_postargs=(ext.extra_compile_args or []),
156                    depends=ext.depends)
157        except CompileError:
158            log.warn("%s appears not to be installed" % ext.feature_name)
159            log.warn("(if %s is installed, you may need to specify"
160                    % ext.feature_name)
161            log.warn(" the option --include-dirs or uncomment and modify")
162            log.warn(" the parameter include_dirs in setup.cfg)")
163            open(cache, 'w').write('0\n')
164            return False
165        prog = 'check_%s' % ext.feature_name
166        log.info("checking if %s links" % ext.feature_name)
167        try:
168            self.compiler.link_executable([obj], prog,
169                    output_dir=self.build_temp,
170                    libraries=ext.libraries,
171                    library_dirs=ext.library_dirs,
172                    runtime_library_dirs=ext.runtime_library_dirs,
173                    extra_postargs=(ext.extra_link_args or []))
174        except LinkError:
175            log.warn("unable to link against %s" % ext.feature_name)
176            log.warn("(if %s is installed correctly, you may need to specify"
177                    % ext.feature_name)
178            log.warn(" the option --library-dirs or uncomment and modify")
179            log.warn(" the parameter library_dirs in setup.cfg)")
180            open(cache, 'w').write('0\n')
181            return False
182        open(cache, 'w').write('1\n')
183        return True
184
185
186class test(Command):
187
188    user_options = []
189
190    def initialize_options(self):
191        pass
192
193    def finalize_options(self):
194        pass
195
196    def run(self):
197        build_cmd = self.get_finalized_command('build')
198        build_cmd.run()
199        sys.path.insert(0, build_cmd.build_lib)
200        sys.path.insert(0, 'tests')
201        import test_all
202        test_all.main()
203
204
205if __name__ == '__main__':
206
207    setup(
208        name=NAME,
209        version=VERSION,
210        description=DESCRIPTION,
211        long_description=LONG_DESCRIPTION,
212        author=AUTHOR,
213        author_email=AUTHOR_EMAIL,
214        license=LICENSE,
215        platforms=PLATFORMS,
216        url=URL,
217        download_url=DOWNLOAD_URL,
218        classifiers=CLASSIFIERS,
219
220        package_dir={'': 'lib'},
221        packages=['yaml'],
222        ext_modules=[
223            Extension('yaml/_yaml', ['ext/_yaml.pyx'],
224                'libyaml', "LibYAML bindings", LIBYAML_CHECK,
225                libraries=['yaml']),
226        ],
227
228        distclass=Distribution,
229        cmdclass={
230            'build_ext': build_ext,
231            'test': test,
232        },
233    )
234
Note: See TracBrowser for help on using the repository browser.