aboutsummaryrefslogtreecommitdiff
path: root/catapult/common/py_vulcanize/third_party/rjsmin/_setup/py2/setup.py
blob: 8b15d497af24b938ac96c808b5eb99e7ff2ef277 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
# -*- coding: ascii -*-
#
# Copyright 2007 - 2013
# Andr\xe9 Malo or his licensors, as applicable
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
===================
 Main setup runner
===================

This module provides a wrapper around the distutils core setup.
"""
__author__ = u"Andr\xe9 Malo"
__docformat__ = "restructuredtext en"

import ConfigParser as _config_parser
from distutils import core as _core
import os as _os
import posixpath as _posixpath
import sys as _sys

from _setup import commands as _commands
from _setup import data as _data
from _setup import ext as _ext
from _setup import util as _util
from _setup import shell as _shell


def check_python_version(impl, version_min, version_max):
    """ Check python version """
    if impl == 'python':
        version_info = _sys.version_info
    elif impl == 'pypy':
        version_info = getattr(_sys, 'pypy_version_info', None)
        if not version_info:
            return
    elif impl == 'jython':
        if not 'java' in _sys.platform.lower():
            return
        version_info = _sys.version_info
    else:
        raise AssertionError("impl not in ('python', 'pypy', 'jython')")

    pyversion = map(int, version_info[:3])
    if version_min:
        min_required = \
            map(int, '.'.join((version_min, '0.0.0')).split('.')[:3])
        if pyversion < min_required:
            raise EnvironmentError("Need at least %s %s (vs. %s)" % (
                impl, version_min, '.'.join(map(str, pyversion))
            ))
    if version_max:
        max_required = map(int, version_max.split('.'))
        max_required[-1] += 1
        if pyversion >= max_required:
            raise EnvironmentError("Need at max %s %s (vs. %s)" % (
                impl,
                version_max,
                '.'.join(map(str, pyversion))
            ))


def find_description(docs):
    """
    Determine the package description from DESCRIPTION

    :Parameters:
      `docs` : ``dict``
        Docs config section

    :Return: Tuple of summary, description and license
             (``('summary', 'description', 'license')``)
             (all may be ``None``)
    :Rtype: ``tuple``
    """
    summary = None
    filename = docs.get('meta.summary', 'SUMMARY').strip()
    if filename and _os.path.isfile(filename):
        fp = open(filename)
        try:
            try:
                summary = fp.read().strip().splitlines()[0].rstrip()
            except IndexError:
                summary = ''
        finally:
            fp.close()

    description = None
    filename = docs.get('meta.description', 'DESCRIPTION').strip()
    if filename and _os.path.isfile(filename):
        fp = open(filename)
        try:
            description = fp.read().rstrip()
        finally:
            fp.close()

        if summary is None and description:
            from docutils import core
            summary = core.publish_parts(
                source=description,
                source_path=filename,
                writer_name='html',
            )['title'].encode('utf-8')

    return summary, description


def find_classifiers(docs):
    """
    Determine classifiers from CLASSIFIERS

    :return: List of classifiers (``['classifier', ...]``)
    :rtype: ``list``
    """
    filename = docs.get('meta.classifiers', 'CLASSIFIERS').strip()
    if filename and _os.path.isfile(filename):
        fp = open(filename)
        try:
            content = fp.read()
        finally:
            fp.close()
        content = [item.strip() for item in content.splitlines()]
        return [item for item in content if item and not item.startswith('#')]
    return []


def find_provides(docs):
    """
    Determine provides from PROVIDES

    :return: List of provides (``['provides', ...]``)
    :rtype: ``list``
    """
    filename = docs.get('meta.provides', 'PROVIDES').strip()
    if filename and _os.path.isfile(filename):
        fp = open(filename)
        try:
            content = fp.read()
        finally:
            fp.close()
        content = [item.strip() for item in content.splitlines()]
        return [item for item in content if item and not item.startswith('#')]
    return []


def find_license(docs):
    """
    Determine license from LICENSE

    :return: License text
    :rtype: ``str``
    """
    filename = docs.get('meta.license', 'LICENSE').strip()
    if filename and _os.path.isfile(filename):
        fp = open(filename)
        try:
            return fp.read().rstrip()
        finally:
            fp.close()
    return None


def find_packages(manifest):
    """ Determine packages and subpackages """
    packages = {}
    collect = manifest.get('packages.collect', '').split()
    lib = manifest.get('packages.lib', '.')
    try:
        sep = _os.path.sep
    except AttributeError:
        sep = _os.path.join('1', '2')[1:-1]
    for root in collect:
        for dirpath, _, filenames in _shell.walk(_os.path.join(lib, root)):
            if dirpath.find('.svn') >= 0 or dirpath.find('.git') >= 0:
                continue
            if '__init__.py' in filenames:
                packages[
                    _os.path.normpath(dirpath).replace(sep, '.')
                ] = None
    packages = packages.keys()
    packages.sort()
    return packages


def find_data(name, docs):
    """ Determine data files """
    result = []
    if docs.get('extra', '').strip():
        result.append(_data.Documentation(docs['extra'].split(),
            prefix='share/doc/%s' % name,
        ))
    if docs.get('examples.dir', '').strip():
        tpl = ['recursive-include %s *' % docs['examples.dir']]
        if docs.get('examples.ignore', '').strip():
            tpl.extend(["global-exclude %s" % item
                for item in docs['examples.ignore'].split()
            ])
        strip = int(docs.get('examples.strip', '') or 0)
        result.append(_data.Documentation.from_templates(*tpl, **{
            'strip': strip,
            'prefix': 'share/doc/%s' % name,
            'preserve': 1,
        }))
    if docs.get('userdoc.dir', '').strip():
        tpl = ['recursive-include %s *' % docs['userdoc.dir']]
        if docs.get('userdoc.ignore', '').strip():
            tpl.extend(["global-exclude %s" % item
                for item in docs['userdoc.ignore'].split()
            ])
        strip = int(docs.get('userdoc.strip', '') or 0)
        result.append(_data.Documentation.from_templates(*tpl, **{
            'strip': strip,
            'prefix': 'share/doc/%s' % name,
            'preserve': 1,
        }))
    if docs.get('apidoc.dir', '').strip():
        tpl = ['recursive-include %s *' % docs['apidoc.dir']]
        if docs.get('apidoc.ignore', '').strip():
            tpl.extend(["global-exclude %s" % item
                for item in docs['apidoc.ignore'].split()
            ])
        strip = int(docs.get('apidoc.strip', '') or 0)
        result.append(_data.Documentation.from_templates(*tpl, **{
            'strip': strip,
            'prefix': 'share/doc/%s' % name,
            'preserve': 1,
        }))
    if docs.get('man', '').strip():
        result.extend(_data.Manpages.dispatch(docs['man'].split()))
    return result


def make_manifest(manifest, config, docs, kwargs):
    """ Create file list to pack up """
    # pylint: disable = R0912
    kwargs = kwargs.copy()
    kwargs['script_args'] = ['install']
    kwargs['packages'] = list(kwargs.get('packages') or ()) + [
        '_setup', '_setup.py2', '_setup.py3',
    ] + list(manifest.get('packages.extra', '').split() or ())
    _core._setup_stop_after = "commandline"
    try:
        dist = _core.setup(**kwargs)
    finally:
        _core._setup_stop_after = None

    result = ['MANIFEST', 'PKG-INFO', 'setup.py'] + list(config)
    # TODO: work with default values:
    for key in ('classifiers', 'description', 'summary', 'provides',
                'license'):
        filename = docs.get('meta.' + key, '').strip()
        if filename and _os.path.isfile(filename):
            result.append(filename)

    cmd = dist.get_command_obj("build_py")
    cmd.ensure_finalized()
    #from pprint import pprint; pprint(("build_py", cmd.get_source_files()))
    for item in cmd.get_source_files():
        result.append(_posixpath.sep.join(
            _os.path.normpath(item).split(_os.path.sep)
        ))

    cmd = dist.get_command_obj("build_ext")
    cmd.ensure_finalized()
    #from pprint import pprint; pprint(("build_ext", cmd.get_source_files()))
    for item in cmd.get_source_files():
        result.append(_posixpath.sep.join(
            _os.path.normpath(item).split(_os.path.sep)
        ))
    for ext in cmd.extensions:
        if ext.depends:
            result.extend([_posixpath.sep.join(
                _os.path.normpath(item).split(_os.path.sep)
            ) for item in ext.depends])

    cmd = dist.get_command_obj("build_clib")
    cmd.ensure_finalized()
    if cmd.libraries:
        #import pprint; pprint.pprint(("build_clib", cmd.get_source_files()))
        for item in cmd.get_source_files():
            result.append(_posixpath.sep.join(
                _os.path.normpath(item).split(_os.path.sep)
            ))
        for lib in cmd.libraries:
            if lib[1].get('depends'):
                result.extend([_posixpath.sep.join(
                    _os.path.normpath(item).split(_os.path.sep)
                ) for item in lib[1]['depends']])

    cmd = dist.get_command_obj("build_scripts")
    cmd.ensure_finalized()
    #import pprint; pprint.pprint(("build_scripts", cmd.get_source_files()))
    if cmd.get_source_files():
        for item in cmd.get_source_files():
            result.append(_posixpath.sep.join(
                _os.path.normpath(item).split(_os.path.sep)
            ))

    cmd = dist.get_command_obj("install_data")
    cmd.ensure_finalized()
    #from pprint import pprint; pprint(("install_data", cmd.get_inputs()))
    try:
        strings = basestring
    except NameError:
        strings = (str, unicode)

    for item in cmd.get_inputs():
        if isinstance(item, strings):
            result.append(item)
        else:
            result.extend(item[1])

    for item in manifest.get('dist', '').split():
        result.append(item)
        if _os.path.isdir(item):
            for filename in _shell.files(item):
                result.append(filename)

    result = dict([(item, None) for item in result]).keys()
    result.sort()
    return result


def run(config=('package.cfg',), ext=None, script_args=None, manifest_only=0):
    """ Main runner """
    if ext is None:
        ext = []

    cfg = _util.SafeConfigParser()
    cfg.read(config)
    pkg = dict(cfg.items('package'))
    python_min = pkg.get('python.min') or None
    python_max = pkg.get('python.max') or None
    check_python_version('python', python_min, python_max)
    pypy_min = pkg.get('pypy.min') or None
    pypy_max = pkg.get('pypy.max') or None
    check_python_version('pypy', pypy_min, pypy_max)
    jython_min = pkg.get('jython.min') or None
    jython_max = pkg.get('jython.max') or None
    check_python_version('jython', jython_min, jython_max)

    manifest = dict(cfg.items('manifest'))
    try:
        docs = dict(cfg.items('docs'))
    except _config_parser.NoSectionError:
        docs = {}

    summary, description = find_description(docs)
    scripts = manifest.get('scripts', '').strip() or None
    if scripts:
        scripts = scripts.split()
    modules = manifest.get('modules', '').strip() or None
    if modules:
        modules = modules.split()
    keywords = docs.get('meta.keywords', '').strip() or None
    if keywords:
        keywords = keywords.split()
    revision = pkg.get('version.revision', '').strip()
    if revision:
        revision = int(revision)
    else:
        revision = 0

    kwargs = {
        'name': pkg['name'],
        'version': "%s%s" % (
            pkg['version.number'],
            ["", ".dev%d" % (revision,)][_util.humanbool(
                'version.dev', pkg.get('version.dev', 'false')
            )],
        ),
        'provides': find_provides(docs),
        'description': summary,
        'long_description': description,
        'classifiers': find_classifiers(docs),
        'keywords': keywords,
        'author': pkg['author.name'],
        'author_email': pkg['author.email'],
        'maintainer': pkg.get('maintainer.name'),
        'maintainer_email': pkg.get('maintainer.email'),
        'url': pkg.get('url.homepage'),
        'download_url': pkg.get('url.download'),
        'license': find_license(docs),
        'package_dir': {'': manifest.get('packages.lib', '.')},
        'packages': find_packages(manifest),
        'py_modules': modules,
        'ext_modules': ext,
        'scripts': scripts,
        'script_args': script_args,
        'data_files': find_data(pkg['name'], docs),
        'cmdclass': {
            'build'       : _commands.Build,
            'build_ext'   : _commands.BuildExt,
            'install'     : _commands.Install,
            'install_data': _commands.InstallData,
            'install_lib' : _commands.InstallLib,
        }
    }
    for key in ('provides',):
        if key not in _core.setup_keywords:
            del kwargs[key]

    if manifest_only:
        return make_manifest(manifest, config, docs, kwargs)

    # monkey-patch crappy manifest writer away.
    from distutils.command import sdist
    sdist.sdist.get_file_list = sdist.sdist.read_manifest

    return _core.setup(**kwargs)