summaryrefslogtreecommitdiff
path: root/distutils2/create.py
blob: 0a60ac81ef1f196ca89c381b705f39cbe2cfbc9c (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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
"""Interactive helper used to create a setup.cfg file.

This script will generate a distutils2 configuration file by looking at
the current directory and asking the user questions.  It is intended to
be called as *pysetup create*.
"""

#  Original code by Sean Reifschneider <jafo@tummy.com>

#  Original TODO list:
#  Look for a license file and automatically add the category.
#  When a .c file is found during the walk, can we add it as an extension?
#  Ask if there is a maintainer different that the author
#  Ask for the platform (can we detect this via "import win32" or something?)
#  Ask for the dependencies.
#  Ask for the Requires-Dist
#  Ask for the Provides-Dist
#  Ask for a description
#  Detect scripts (not sure how.  #! outside of package?)

import os
import re
import imp
import sys
import glob
import codecs
from textwrap import dedent
from ConfigParser import RawConfigParser

from distutils2 import logger
# importing this with an underscore as it should be replaced by the
# dict form or another structures for all purposes
from distutils2._trove import all_classifiers as _CLASSIFIERS_LIST
from distutils2.version import is_valid_version
from distutils2._backport import shutil, sysconfig
from distutils2._backport.misc import any, detect_encoding
try:
    from hashlib import md5
except ImportError:
    from distutils2._backport.hashlib import md5


_FILENAME = 'setup.cfg'
_DEFAULT_CFG = '.pypkgcreate'  # FIXME use a section in user .pydistutils.cfg

_helptext = {
    'name': '''
The name of the project to be packaged, usually a single word composed
of lower-case characters such as "zope.interface", "sqlalchemy" or
"CherryPy".
''',
    'version': '''
Version number of the software, typically 2 or 3 numbers separated by
dots such as "1.0", "0.6b3", or "3.2.1".  "0.1.0" is recommended for
initial development.
''',
    'summary': '''
A one-line summary of what this project is or does, typically a sentence
80 characters or less in length.
''',
    'author': '''
The full name of the author (typically you).
''',
    'author_email': '''
Email address of the project author.
''',
    'do_classifier': '''
Trove classifiers are optional identifiers that allow you to specify the
intended audience by saying things like "Beta software with a text UI
for Linux under the PSF license".  However, this can be a somewhat
involved process.
''',
    'packages': '''
Python packages included in the project.
''',
    'modules': '''
Pure Python modules included in the project.
''',
    'extra_files': '''
You can provide extra files/dirs contained in your project.
It has to follow the template syntax. XXX add help here.
''',

    'home_page': '''
The home page for the project, typically a public Web page.
''',
    'trove_license': '''
Optionally you can specify a license.  Type a string that identifies a
common license, and then you can select a list of license specifiers.
''',
    'trove_generic': '''
Optionally, you can set other trove identifiers for things such as the
human language, programming language, user interface, etc.
''',
    'setup.py found': '''
The setup.py script will be executed to retrieve the metadata.
An interactive helper will be run if you answer "n",
''',
}

PROJECT_MATURITY = ['Development Status :: 1 - Planning',
                    'Development Status :: 2 - Pre-Alpha',
                    'Development Status :: 3 - Alpha',
                    'Development Status :: 4 - Beta',
                    'Development Status :: 5 - Production/Stable',
                    'Development Status :: 6 - Mature',
                    'Development Status :: 7 - Inactive']

# XXX everything needs docstrings and tests (both low-level tests of various
# methods and functional tests of running the script)


def load_setup():
    """run the setup script (i.e the setup.py file)

    This function load the setup file in all cases (even if it have already
    been loaded before, because we are monkey patching its setup function with
    a particular one"""
    f = open("setup.py", "rb")
    try:
        encoding, lines = detect_encoding(f.readline)
    finally:
        f.close()
    f = open("setup.py")
    try:
        imp.load_module("setup", f, "setup.py", (".py", "r", imp.PY_SOURCE))
    finally:
        f.close()


def ask_yn(question, default=None, helptext=None):
    question += ' (y/n)'
    while True:
        answer = ask(question, default, helptext, required=True)
        if answer and answer[0].lower() in ('y', 'n'):
            return answer[0].lower()

        logger.error('You must select "Y" or "N".')


# XXX use util.ask
# FIXME: if prompt ends with '?', don't add ':'


def ask(question, default=None, helptext=None, required=True,
        lengthy=False, multiline=False):
    prompt = u'%s: ' % (question,)
    if default:
        prompt = u'%s [%s]: ' % (question, default)
        if default and len(question) + len(default) > 70:
            prompt = u'%s\n    [%s]: ' % (question, default)
    if lengthy or multiline:
        prompt += '\n   > '

    if not helptext:
        helptext = 'No additional help available.'

    helptext = helptext.strip("\n")

    while True:
        line = raw_input(prompt).strip()
        if line == '?':
            print '=' * 70
            print helptext
            print '=' * 70
            continue
        if default and not line:
            return default
        if not line and required:
            print '*' * 70
            print 'This value cannot be empty.'
            print '==========================='
            if helptext:
                print helptext
            print '*' * 70
            continue
        return line


def convert_yn_to_bool(yn, yes=True, no=False):
    """Convert a y/yes or n/no to a boolean value."""
    if yn.lower().startswith('y'):
        return yes
    else:
        return no


def _build_classifiers_dict(classifiers):
    d = {}
    for key in classifiers:
        subdict = d
        for subkey in key.split(' :: '):
            if subkey not in subdict:
                subdict[subkey] = {}
            subdict = subdict[subkey]
    return d

CLASSIFIERS = _build_classifiers_dict(_CLASSIFIERS_LIST)


def _build_licences(classifiers):
    res = []
    for index, item in enumerate(classifiers):
        if not item.startswith('License :: '):
            continue
        res.append((index, item.split(' :: ')[-1].lower()))
    return res

LICENCES = _build_licences(_CLASSIFIERS_LIST)


class MainProgram(object):
    """Make a project setup configuration file (setup.cfg)."""

    def __init__(self):
        self.configparser = None
        self.classifiers = set()
        self.data = {'name': '',
                     'version': '1.0.0',
                     'classifier': self.classifiers,
                     'packages': [],
                     'modules': [],
                     'platform': [],
                     'resources': [],
                     'extra_files': [],
                     'scripts': [],
                     }
        self._load_defaults()

    def __call__(self):
        setupcfg_defined = False
        if self.has_setup_py() and self._prompt_user_for_conversion():
            setupcfg_defined = self.convert_py_to_cfg()
        if not setupcfg_defined:
            self.define_cfg_values()
        self._write_cfg()

    def has_setup_py(self):
        """Test for the existence of a setup.py file."""
        return os.path.exists('setup.py')

    def define_cfg_values(self):
        self.inspect()
        self.query_user()

    def _lookup_option(self, key):
        if not self.configparser.has_option('DEFAULT', key):
            return None
        return self.configparser.get('DEFAULT', key)

    def _load_defaults(self):
        # Load default values from a user configuration file
        self.configparser = RawConfigParser()
        # TODO replace with section in distutils config file
        default_cfg = os.path.expanduser(os.path.join('~', _DEFAULT_CFG))
        self.configparser.read(default_cfg)
        self.data['author'] = self._lookup_option('author')
        self.data['author_email'] = self._lookup_option('author_email')

    def _prompt_user_for_conversion(self):
        # Prompt the user about whether they would like to use the setup.py
        # conversion utility to generate a setup.cfg or generate the setup.cfg
        # from scratch
        answer = ask_yn(('A legacy setup.py has been found.\n'
                         'Would you like to convert it to a setup.cfg?'),
                        default="y",
                        helptext=_helptext['setup.py found'])
        return convert_yn_to_bool(answer)

    def _dotted_packages(self, data):
        packages = sorted(data)
        modified_pkgs = []
        for pkg in packages:
            pkg = pkg.lstrip('./')
            pkg = pkg.replace('/', '.')
            modified_pkgs.append(pkg)
        return modified_pkgs

    def _write_cfg(self):
        if os.path.exists(_FILENAME):
            if os.path.exists('%s.old' % _FILENAME):
                message = ("ERROR: %(name)s.old backup exists, please check "
                           "that current %(name)s is correct and remove "
                           "%(name)s.old" % {'name': _FILENAME})
                logger.error(message)
                return
            shutil.move(_FILENAME, '%s.old' % _FILENAME)

        fp = codecs.open(_FILENAME, 'w', encoding='utf-8')
        try:
            fp.write(u'[metadata]\n')
            # TODO use metadata module instead of hard-coding field-specific
            # behavior here

            # simple string entries
            for name in ('name', 'version', 'summary', 'download_url'):
                fp.write(u'%s = %s\n' % (name, self.data.get(name, 'UNKNOWN')))

            # optional string entries
            if 'keywords' in self.data and self.data['keywords']:
                # XXX shoud use comma to separate, not space
                fp.write(u'keywords = %s\n' % ' '.join(self.data['keywords']))
            for name in ('home_page', 'author', 'author_email',
                         'maintainer', 'maintainer_email', 'description-file'):
                if name in self.data and self.data[name]:
                    fp.write(u'%s = %s\n' % (name.decode('utf-8'),
                                             self.data[name].decode('utf-8')))
            if 'description' in self.data:
                fp.write(
                    u'description = %s\n'
                    % u'\n       |'.join(self.data['description'].split('\n')))

            # multiple use string entries
            for name in ('platform', 'supported-platform', 'classifier',
                         'requires-dist', 'provides-dist', 'obsoletes-dist',
                         'requires-external'):
                if not(name in self.data and self.data[name]):
                    continue
                fp.write(u'%s = ' % name)
                fp.write(u''.join('    %s\n' % val
                                 for val in self.data[name]).lstrip())

            fp.write(u'\n[files]\n')

            for name in ('packages', 'modules', 'scripts', 'extra_files'):
                if not(name in self.data and self.data[name]):
                    continue
                fp.write(u'%s = %s\n'
                         % (name, u'\n    '.join(self.data[name]).strip()))

            if self.data.get('package_data'):
                fp.write(u'package_data =\n')
                for pkg, spec in sorted(self.data['package_data'].items()):
                    # put one spec per line, indented under the package name
                    indent = u' ' * (len(pkg) + 7)
                    spec = (u'\n' + indent).join(spec)
                    fp.write(u'    %s = %s\n' % (pkg, spec))
                fp.write(u'\n')

            if self.data.get('resources'):
                fp.write(u'resources =\n')
                for src, dest in self.data['resources']:
                    fp.write(u'    %s = %s\n' % (src, dest))
                fp.write(u'\n')

        finally:
            fp.close()

        os.chmod(_FILENAME, 0644)
        logger.info('Wrote "%s".' % _FILENAME)

    def convert_py_to_cfg(self):
        """Generate a setup.cfg from an existing setup.py.

        It only exports the distutils metadata (setuptools specific metadata
        is not currently supported).
        """
        data = self.data

        def setup_mock(**attrs):
            """Mock the setup(**attrs) in order to retrieve metadata."""

            # TODO use config and metadata instead of Distribution
            from distutils.dist import Distribution
            dist = Distribution(attrs)
            dist.parse_config_files()

            # 1. retrieve metadata fields that are quite similar in
            # PEP 314 and PEP 345
            labels = (('name',) * 2,
                      ('version',) * 2,
                      ('author',) * 2,
                      ('author_email',) * 2,
                      ('maintainer',) * 2,
                      ('maintainer_email',) * 2,
                      ('description', 'summary'),
                      ('long_description', 'description'),
                      ('url', 'home_page'),
                      ('platforms', 'platform'))
            if sys.version_info[:2] >= (2, 5):
                labels += (
                      ('provides', 'provides-dist'),
                      ('obsoletes', 'obsoletes-dist'),
                      ('requires', 'requires-dist'))

            get = lambda lab: getattr(dist.metadata, lab.replace('-', '_'))
            data.update((new, get(old)) for old, new in labels if get(old))

            # 2. retrieve data that requires special processing
            data['classifier'].update(dist.get_classifiers() or [])
            data['scripts'].extend(dist.scripts or [])
            data['packages'].extend(dist.packages or [])
            data['modules'].extend(dist.py_modules or [])
            # 2.1 data_files -> resources
            if dist.data_files:
                if (len(dist.data_files) < 2 or
                    isinstance(dist.data_files[1], basestring)):
                    dist.data_files = [('', dist.data_files)]
                # add tokens in the destination paths
                vars = {'distribution.name': data['name']}
                path_tokens = sysconfig.get_paths(vars=vars).items()
                # sort tokens to use the longest one first
                path_tokens = sorted(path_tokens, key=lambda x: len(x[1]))
                for dest, srcs in (dist.data_files or []):
                    dest = os.path.join(sys.prefix, dest)
                    dest = dest.replace(os.path.sep, '/')
                    for tok, path in path_tokens:
                        path = path.replace(os.path.sep, '/')
                        if not dest.startswith(path):
                            continue

                        dest = ('{%s}' % tok) + dest[len(path):]
                        files = [('/ '.join(src.rsplit('/', 1)), dest)
                                 for src in srcs]
                        data['resources'].extend(files)

            # 2.2 package_data
            data['package_data'] = dist.package_data.copy()

            # Use README file if its content is the desciption
            if "description" in data:
                ref = md5(re.sub('\s', '',
                                 self.data['description']).lower().encode())
                ref = ref.digest()
                for readme in glob.glob('README*'):
                    fp = codecs.open(readme, encoding='utf-8')
                    try:
                        contents = fp.read()
                    finally:
                        fp.close()
                    contents = re.sub('\s', '', contents.lower()).encode()
                    val = md5(contents).digest()
                    if val == ref:
                        del data['description']
                        data['description-file'] = readme
                        break

        # apply monkey patch to distutils (v1) and setuptools (if needed)
        # (abort the feature if distutils v1 has been killed)
        try:
            from distutils import core
            core.setup  # make sure it's not d2 maskerading as d1
        except (ImportError, AttributeError):
            return
        saved_setups = [(core, core.setup)]
        core.setup = setup_mock
        try:
            import setuptools
        except ImportError:
            pass
        else:
            saved_setups.append((setuptools, setuptools.setup))
            setuptools.setup = setup_mock
        # get metadata by executing the setup.py with the patched setup(...)
        success = False  # for python < 2.4
        try:
            load_setup()
            success = True
        finally:  # revert monkey patches
            for patched_module, original_setup in saved_setups:
                patched_module.setup = original_setup
        if not self.data:
            raise ValueError('Unable to load metadata from setup.py')
        return success

    def inspect(self):
        """Inspect the current working diretory for a name and version.

        This information is harvested in where the directory is named
        like [name]-[version].
        """
        dir_name = os.path.basename(os.getcwd())
        self.data['name'] = dir_name
        match = re.match(r'(.*)-(\d.+)', dir_name)
        if match:
            self.data['name'] = match.group(1)
            self.data['version'] = match.group(2)
            # TODO needs testing!
            if not is_valid_version(self.data['version']):
                msg = "Invalid version discovered: %s" % self.data['version']
                raise ValueError(msg)

    def query_user(self):
        self.data['name'] = ask('Project name', self.data['name'],
              _helptext['name'])

        self.data['version'] = ask('Current version number',
              self.data.get('version'), _helptext['version'])
        self.data['summary'] = ask('Project description summary',
              self.data.get('summary'), _helptext['summary'],
              lengthy=True)
        self.data['author'] = ask('Author name',
              self.data.get('author'), _helptext['author'])
        self.data['author_email'] = ask('Author email address',
              self.data.get('author_email'), _helptext['author_email'])
        self.data['home_page'] = ask('Project home page',
              self.data.get('home_page'), _helptext['home_page'],
              required=False)

        if ask_yn('Do you want me to automatically build the file list '
              'with everything I can find in the current directory? '
              'If you say no, you will have to define them manually.') == 'y':
            self._find_files()
        else:
            while ask_yn('Do you want to add a single module?'
                        ' (you will be able to add full packages next)',
                    helptext=_helptext['modules']) == 'y':
                self._set_multi('Module name', 'modules')

            while ask_yn('Do you want to add a package?',
                    helptext=_helptext['packages']) == 'y':
                self._set_multi('Package name', 'packages')

            while ask_yn('Do you want to add an extra file?',
                        helptext=_helptext['extra_files']) == 'y':
                self._set_multi('Extra file/dir name', 'extra_files')

        if ask_yn('Do you want to set Trove classifiers?',
                  helptext=_helptext['do_classifier']) == 'y':
            self.set_classifier()

    def _find_files(self):
        # we are looking for python modules and packages,
        # other stuff are added as regular files
        pkgs = self.data['packages']
        modules = self.data['modules']
        extra_files = self.data['extra_files']

        def is_package(path):
            return os.path.exists(os.path.join(path, '__init__.py'))

        curdir = os.getcwd()
        scanned = []
        _pref = ['lib', 'include', 'dist', 'build', '.', '~']
        _suf = ['.pyc']

        def to_skip(path):
            path = relative(path)

            for pref in _pref:
                if path.startswith(pref):
                    return True

            for suf in _suf:
                if path.endswith(suf):
                    return True

            return False

        def relative(path):
            return path[len(curdir) + 1:]

        def dotted(path):
            res = relative(path).replace(os.path.sep, '.')
            if res.endswith('.py'):
                res = res[:-len('.py')]
            return res

        # first pass: packages
        for root, dirs, files in os.walk(curdir):
            if to_skip(root):
                continue
            for dir_ in sorted(dirs):
                if to_skip(dir_):
                    continue
                fullpath = os.path.join(root, dir_)
                dotted_name = dotted(fullpath)
                if is_package(fullpath) and dotted_name not in pkgs:
                    pkgs.append(dotted_name)
                    scanned.append(fullpath)

        # modules and extra files
        for root, dirs, files in os.walk(curdir):
            if to_skip(root):
                continue

            if any(root.startswith(path) for path in scanned):
                continue

            for file in sorted(files):
                fullpath = os.path.join(root, file)
                if to_skip(fullpath):
                    continue
                # single module?
                if os.path.splitext(file)[-1] == '.py':
                    modules.append(dotted(fullpath))
                else:
                    extra_files.append(relative(fullpath))

    def _set_multi(self, question, name):
        existing_values = self.data[name]
        value = ask(question, helptext=_helptext[name]).strip()
        if value not in existing_values:
            existing_values.append(value)

    def set_classifier(self):
        self.set_maturity_status(self.classifiers)
        self.set_license(self.classifiers)
        self.set_other_classifier(self.classifiers)

    def set_other_classifier(self, classifiers):
        if ask_yn('Do you want to set other trove identifiers?', 'n',
                  _helptext['trove_generic']) != 'y':
            return
        self.walk_classifiers(classifiers, [CLASSIFIERS], '')

    def walk_classifiers(self, classifiers, trovepath, desc):
        trove = trovepath[-1]

        if not trove:
            return

        for key in sorted(trove):
            if len(trove[key]) == 0:
                if ask_yn('Add "%s"' % desc[4:] + ' :: ' + key, 'n') == 'y':
                    classifiers.add(desc[4:] + ' :: ' + key)
                continue

            if ask_yn('Do you want to set items under\n   "%s" (%d sub-items)?'
                      % (key, len(trove[key])), 'n',
                      _helptext['trove_generic']) == 'y':
                self.walk_classifiers(classifiers, trovepath + [trove[key]],
                                      desc + ' :: ' + key)

    def set_license(self, classifiers):
        while True:
            license = ask('What license do you use?',
                          helptext=_helptext['trove_license'], required=False)
            if not license:
                return

            license_words = license.lower().split(' ')
            found_list = []

            for index, licence in LICENCES:
                for word in license_words:
                    if word in licence:
                        found_list.append(index)
                        break

            if len(found_list) == 0:
                logger.error('Could not find a matching license for "%s"' %
                             license)
                continue

            question = 'Matching licenses:\n\n'

            for index, list_index in enumerate(found_list):
                question += '   %s) %s\n' % (index + 1,
                                             _CLASSIFIERS_LIST[list_index])

            question += ('\nType the number of the license you wish to use or '
                         '? to try again:')
            choice = ask(question, required=False)

            if choice == '?':
                continue
            if choice == '':
                return

            try:
                index = found_list[int(choice) - 1]
            except ValueError:
                logger.error(
                    "Invalid selection, type a number from the list above.")

            classifiers.add(_CLASSIFIERS_LIST[index])

    def set_maturity_status(self, classifiers):
        maturity_name = lambda mat: mat.split('- ')[-1]
        maturity_question = '''\
            Please select the project status:

            %s

            Status''' % '\n'.join('%s - %s' % (i, maturity_name(n))
                                  for i, n in enumerate(PROJECT_MATURITY))
        while True:
            choice = ask(dedent(maturity_question), required=False)

            if choice:
                try:
                    choice = int(choice) - 1
                    key = PROJECT_MATURITY[choice]
                    classifiers.add(key)
                    return
                except (IndexError, ValueError):
                    logger.error(
                        "Invalid selection, type a single digit number.")


def main():
    """Main entry point."""
    program = MainProgram()
    # # uncomment when implemented
    # if not program.load_existing_setup_script():
    #     program.inspect_directory()
    #     program.query_user()
    #     program.update_config_file()
    # program.write_setup_script()
    # distutils2.util.cfg_to_args()
    program()