1
2NAME = 'PyYAML'
3VERSION = '5.4.1'
4DESCRIPTION = "YAML parser and emitter for Python"
5LONG_DESCRIPTION = """\
6YAML is a data serialization format designed for human readability
7and interaction with scripting languages.  PyYAML is a YAML parser
8and emitter 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
13allow to represent an arbitrary Python object.
14
15PyYAML is applicable for a broad range of tasks from complex
16configuration files to object serialization and persistence."""
17AUTHOR = "Kirill Simonov"
18AUTHOR_EMAIL = 'xi@resolvent.net'
19LICENSE = "MIT"
20PLATFORMS = "Any"
21URL = "https://pyyaml.org/"
22DOWNLOAD_URL = "https://pypi.org/project/PyYAML/"
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 :: Cython",
29    "Programming Language :: Python",
30    "Programming Language :: Python :: 2",
31    "Programming Language :: Python :: 2.7",
32    "Programming Language :: Python :: 3",
33    "Programming Language :: Python :: 3.6",
34    "Programming Language :: Python :: 3.7",
35    "Programming Language :: Python :: 3.8",
36    "Programming Language :: Python :: 3.9",
37    "Programming Language :: Python :: Implementation :: CPython",
38    "Programming Language :: Python :: Implementation :: PyPy",
39    "Topic :: Software Development :: Libraries :: Python Modules",
40    "Topic :: Text Processing :: Markup",
41]
42PROJECT_URLS = {
43   'Bug Tracker': 'https://github.com/yaml/pyyaml/issues',
44   'CI': 'https://github.com/yaml/pyyaml/actions',
45   'Documentation': 'https://pyyaml.org/wiki/PyYAMLDocumentation',
46   'Mailing lists': 'http://lists.sourceforge.net/lists/listinfo/yaml-core',
47   'Source Code': 'https://github.com/yaml/pyyaml',
48}
49
50LIBYAML_CHECK = """
51#include <yaml.h>
52
53int main(void) {
54    yaml_parser_t parser;
55    yaml_emitter_t emitter;
56
57    yaml_parser_initialize(&parser);
58    yaml_parser_delete(&parser);
59
60    yaml_emitter_initialize(&emitter);
61    yaml_emitter_delete(&emitter);
62
63    return 0;
64}
65"""
66
67
68import sys, os, os.path, platform, warnings
69
70from distutils import log
71from setuptools import setup, Command, Distribution as _Distribution, Extension as _Extension
72from setuptools.command.build_ext import build_ext as _build_ext
73from distutils.errors import DistutilsError, CompileError, LinkError, DistutilsPlatformError
74
75with_cython = False
76if 'sdist' in sys.argv or os.environ.get('PYYAML_FORCE_CYTHON') == '1':
77    # we need cython here
78    with_cython = True
79try:
80    from Cython.Distutils.extension import Extension as _Extension
81    from Cython.Distutils import build_ext as _build_ext
82    with_cython = True
83except ImportError:
84    if with_cython:
85        raise
86
87try:
88    from wheel.bdist_wheel import bdist_wheel
89except ImportError:
90    bdist_wheel = None
91
92
93# on Windows, disable wheel generation warning noise
94windows_ignore_warnings = [
95"Unknown distribution option: 'python_requires'",
96"Config variable 'Py_DEBUG' is unset",
97"Config variable 'WITH_PYMALLOC' is unset",
98"Config variable 'Py_UNICODE_SIZE' is unset",
99"Cython directive 'language_level' not set"
100]
101
102if platform.system() == 'Windows':
103    for w in windows_ignore_warnings:
104        warnings.filterwarnings('ignore', w)
105
106
107class Distribution(_Distribution):
108    def __init__(self, attrs=None):
109        _Distribution.__init__(self, attrs)
110        if not self.ext_modules:
111            return
112        for idx in range(len(self.ext_modules)-1, -1, -1):
113            ext = self.ext_modules[idx]
114            if not isinstance(ext, Extension):
115                continue
116            setattr(self, ext.attr_name, None)
117            self.global_options = [
118                    (ext.option_name, None,
119                        "include %s (default if %s is available)"
120                        % (ext.feature_description, ext.feature_name)),
121                    (ext.neg_option_name, None,
122                        "exclude %s" % ext.feature_description),
123            ] + self.global_options
124            self.negative_opt = self.negative_opt.copy()
125            self.negative_opt[ext.neg_option_name] = ext.option_name
126
127    def has_ext_modules(self):
128        if not self.ext_modules:
129            return False
130        for ext in self.ext_modules:
131            with_ext = self.ext_status(ext)
132            if with_ext is None or with_ext:
133                return True
134        return False
135
136    def ext_status(self, ext):
137        implementation = platform.python_implementation()
138        if implementation not in ['CPython', 'PyPy']:
139            return False
140        if isinstance(ext, Extension):
141            # the "build by default" behavior is implemented by this returning None
142            with_ext = getattr(self, ext.attr_name) or os.environ.get('PYYAML_FORCE_{0}'.format(ext.feature_name.upper()))
143            try:
144                with_ext = int(with_ext)  # attempt coerce envvar to int
145            except TypeError:
146                pass
147            return with_ext
148        else:
149            return True
150
151
152class Extension(_Extension):
153
154    def __init__(self, name, sources, feature_name, feature_description,
155            feature_check, **kwds):
156        if not with_cython:
157            for filename in sources[:]:
158                base, ext = os.path.splitext(filename)
159                if ext == '.pyx':
160                    sources.remove(filename)
161                    sources.append('%s.c' % base)
162        _Extension.__init__(self, name, sources, **kwds)
163        self.feature_name = feature_name
164        self.feature_description = feature_description
165        self.feature_check = feature_check
166        self.attr_name = 'with_' + feature_name.replace('-', '_')
167        self.option_name = 'with-' + feature_name
168        self.neg_option_name = 'without-' + feature_name
169
170
171class build_ext(_build_ext):
172
173    def run(self):
174        optional = True
175        disabled = True
176        for ext in self.extensions:
177            with_ext = self.distribution.ext_status(ext)
178            if with_ext is None:
179                disabled = False
180            elif with_ext:
181                optional = False
182                disabled = False
183                break
184        if disabled:
185            return
186        try:
187            _build_ext.run(self)
188        except DistutilsPlatformError:
189            exc = sys.exc_info()[1]
190            if optional:
191                log.warn(str(exc))
192                log.warn("skipping build_ext")
193            else:
194                raise
195
196    def get_source_files(self):
197        self.check_extensions_list(self.extensions)
198        filenames = []
199        for ext in self.extensions:
200            if with_cython:
201                self.cython_sources(ext.sources, ext)
202            for filename in ext.sources:
203                filenames.append(filename)
204                base = os.path.splitext(filename)[0]
205                for ext in ['c', 'h', 'pyx', 'pxd']:
206                    filename = '%s.%s' % (base, ext)
207                    if filename not in filenames and os.path.isfile(filename):
208                        filenames.append(filename)
209        return filenames
210
211    def get_outputs(self):
212        self.check_extensions_list(self.extensions)
213        outputs = []
214        for ext in self.extensions:
215            fullname = self.get_ext_fullname(ext.name)
216            filename = os.path.join(self.build_lib,
217                                    self.get_ext_filename(fullname))
218            if os.path.isfile(filename):
219                outputs.append(filename)
220        return outputs
221
222    def build_extensions(self):
223        self.check_extensions_list(self.extensions)
224        for ext in self.extensions:
225            with_ext = self.distribution.ext_status(ext)
226            if with_ext is not None and not with_ext:
227                continue
228            if with_cython:
229                ext.sources = self.cython_sources(ext.sources, ext)
230            try:
231                self.build_extension(ext)
232            except (CompileError, LinkError):
233                if with_ext is not None:
234                    raise
235                log.warn("Error compiling module, falling back to pure Python")
236
237
238class test(Command):
239
240    user_options = []
241
242    def initialize_options(self):
243        pass
244
245    def finalize_options(self):
246        pass
247
248    def run(self):
249        build_cmd = self.get_finalized_command('build')
250        build_cmd.run()
251        sys.path.insert(0, build_cmd.build_lib)
252        if sys.version_info[0] < 3:
253            sys.path.insert(0, 'tests/lib')
254        else:
255            sys.path.insert(0, 'tests/lib3')
256        import test_all
257        if not test_all.main([]):
258            raise DistutilsError("Tests failed")
259
260
261cmdclass = {
262    'build_ext': build_ext,
263    'test': test,
264}
265if bdist_wheel:
266    cmdclass['bdist_wheel'] = bdist_wheel
267
268
269if __name__ == '__main__':
270
271    setup(
272        name=NAME,
273        version=VERSION,
274        description=DESCRIPTION,
275        long_description=LONG_DESCRIPTION,
276        author=AUTHOR,
277        author_email=AUTHOR_EMAIL,
278        license=LICENSE,
279        platforms=PLATFORMS,
280        url=URL,
281        download_url=DOWNLOAD_URL,
282        classifiers=CLASSIFIERS,
283        project_urls=PROJECT_URLS,
284
285        package_dir={'': {2: 'lib', 3: 'lib3'}[sys.version_info[0]]},
286        packages=['yaml', '_yaml'],
287        ext_modules=[
288            Extension('yaml._yaml', ['yaml/_yaml.pyx'],
289                'libyaml', "LibYAML bindings", LIBYAML_CHECK,
290                libraries=['yaml']),
291        ],
292
293        distclass=Distribution,
294        cmdclass=cmdclass,
295        python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*',
296    )
297