summaryrefslogtreecommitdiff
path: root/distutils2/create.py
diff options
context:
space:
mode:
Diffstat (limited to 'distutils2/create.py')
-rw-r--r--distutils2/create.py120
1 files changed, 49 insertions, 71 deletions
diff --git a/distutils2/create.py b/distutils2/create.py
index 78c291c..139cf6a 100644
--- a/distutils2/create.py
+++ b/distutils2/create.py
@@ -23,25 +23,17 @@ import re
import imp
import sys
import glob
-import codecs
import shutil
+from hashlib import md5
from textwrap import dedent
-from ConfigParser import RawConfigParser
+from tokenize import detect_encoding
+from configparser import RawConfigParser
# 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.compat import detect_encoding
from distutils2.version import is_valid_version
from distutils2._backport import sysconfig
-try:
- any
-except NameError:
- from distutils2.compat import any
-try:
- from hashlib import md5
-except ImportError:
- from distutils2._backport.hashlib import md5
_FILENAME = 'setup.cfg'
@@ -120,26 +112,20 @@ def load_setup():
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:
+ with open("setup.py", "rb") as f:
encoding, lines = detect_encoding(f.readline)
- finally:
- f.close()
- f = open("setup.py")
- try:
+ with open("setup.py", encoding=encoding) as f:
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 'yn':
+ if answer and answer[0].lower() in ('y', 'n'):
return answer[0].lower()
- print '\nERROR: You must select "Y" or "N".\n'
+ print('\nERROR: You must select "Y" or "N".\n')
# XXX use util.ask
@@ -148,11 +134,11 @@ def ask_yn(question, default=None, helptext=None):
def ask(question, default=None, helptext=None, required=True,
lengthy=False, multiline=False):
- prompt = u'%s: ' % (question,)
+ prompt = '%s: ' % (question,)
if default:
- prompt = u'%s [%s]: ' % (question, default)
+ prompt = '%s [%s]: ' % (question, default)
if default and len(question) + len(default) > 70:
- prompt = u'%s\n [%s]: ' % (question, default)
+ prompt = '%s\n [%s]: ' % (question, default)
if lengthy or multiline:
prompt += '\n > '
@@ -167,19 +153,19 @@ def ask(question, default=None, helptext=None, required=True,
line = sys.stdin.readline().strip()
if line == '?':
- print '=' * 70
- print helptext
- print '=' * 70
+ 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 '==========================='
+ print('*' * 70)
+ print('This value cannot be empty.')
+ print('===========================')
if helptext:
- print helptext
- print '*' * 70
+ print(helptext)
+ print('*' * 70)
continue
return line
@@ -216,7 +202,7 @@ def _build_licences(classifiers):
LICENCES = _build_licences(_CLASSIFIERS_LIST)
-class MainProgram(object):
+class MainProgram:
"""Make a project setup configuration file (setup.cfg)."""
def __init__(self):
@@ -286,34 +272,32 @@ class MainProgram(object):
def _write_cfg(self):
if os.path.exists(_FILENAME):
if os.path.exists('%s.old' % _FILENAME):
- print ('ERROR: %(name)s.old backup exists, please check that '
- 'current %(name)s is correct and remove %(name)s.old' %
- {'name': _FILENAME})
+ print("ERROR: %(name)s.old backup exists, please check that "
+ "current %(name)s is correct and remove %(name)s.old" %
+ {'name': _FILENAME})
return
shutil.move(_FILENAME, '%s.old' % _FILENAME)
- fp = codecs.open(_FILENAME, 'w', encoding='utf-8')
- try:
- fp.write(u'[metadata]\n')
+ with open(_FILENAME, 'w', encoding='utf-8') as fp:
+ fp.write('[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')))
+ fp.write('%s = %s\n' % (name, self.data.get(name, 'UNKNOWN')))
# optional string entries
if 'keywords' in self.data and self.data['keywords']:
- fp.write(u'keywords = %s\n' % ' '.join(self.data['keywords']))
+ fp.write('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')))
+ fp.write('%s = %s\n' % (name, self.data[name]))
if 'description' in self.data:
fp.write(
- u'description = %s\n'
- % u'\n |'.join(self.data['description'].split('\n')))
+ 'description = %s\n'
+ % '\n |'.join(self.data['description'].split('\n')))
# multiple use string entries
for name in ('platform', 'supported-platform', 'classifier',
@@ -321,25 +305,23 @@ class MainProgram(object):
'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
+ fp.write('%s = ' % name)
+ fp.write(''.join(' %s\n' % val
for val in self.data[name]).lstrip())
- fp.write(u'\n[files]\n')
+ fp.write('\n[files]\n')
for name in ('packages', 'modules', 'scripts',
'package_data', '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()))
- fp.write(u'\nresources =\n')
+ fp.write('%s = %s\n'
+ % (name, '\n '.join(self.data[name]).strip()))
+ fp.write('\nresources =\n')
for src, dest in self.data['resources']:
- fp.write(u' %s = %s\n' % (src, dest))
- fp.write(u'\n')
- finally:
- fp.close()
+ fp.write(' %s = %s\n' % (src, dest))
+ fp.write('\n')
- os.chmod(_FILENAME, 0644)
- print 'Wrote %r.' % _FILENAME
+ os.chmod(_FILENAME, 0o644)
+ print('Wrote "%s".' % _FILENAME)
def convert_py_to_cfg(self):
"""Generate a setup.cfg from an existing setup.py.
@@ -368,9 +350,8 @@ class MainProgram(object):
('description', 'summary'),
('long_description', 'description'),
('url', 'home_page'),
- ('platforms', 'platform'))
- if sys.version >= '2.5':
- labels += (
+ ('platforms', 'platform'),
+ # backport only for 2.5+
('provides', 'provides-dist'),
('obsoletes', 'obsoletes-dist'),
('requires', 'requires-dist'))
@@ -386,7 +367,7 @@ class MainProgram(object):
# 2.1 data_files -> resources
if dist.data_files:
if (len(dist.data_files) < 2 or
- isinstance(dist.data_files[1], basestring)):
+ isinstance(dist.data_files[1], str)):
dist.data_files = [('', dist.data_files)]
# add tokens in the destination paths
vars = {'distribution.name': data['name']}
@@ -421,11 +402,8 @@ class MainProgram(object):
self.data['description']).lower().encode())
ref = ref.digest()
for readme in glob.glob('README*'):
- fp = codecs.open(readme, encoding='utf-8')
- try:
+ with open(readme, encoding='utf-8') as fp:
contents = fp.read()
- finally:
- fp.close()
contents = re.sub('\s', '', contents.lower()).encode()
val = md5(contents).digest()
if val == ref:
@@ -637,8 +615,8 @@ class MainProgram(object):
break
if len(found_list) == 0:
- print ('ERROR: Could not find a matching license for "%s"' %
- license)
+ print('ERROR: Could not find a matching license for "%s"' %
+ license)
continue
question = 'Matching licenses:\n\n'
@@ -659,8 +637,8 @@ class MainProgram(object):
try:
index = found_list[int(choice) - 1]
except ValueError:
- print ('ERROR: Invalid selection, type a number from the list '
- 'above.')
+ print("ERROR: Invalid selection, type a number from the list "
+ "above.")
classifiers.add(_CLASSIFIERS_LIST[index])
@@ -683,8 +661,8 @@ class MainProgram(object):
classifiers.add(key)
return
except (IndexError, ValueError):
- print ('ERROR: Invalid selection, type a single digit '
- 'number.')
+ print("ERROR: Invalid selection, type a single digit "
+ "number.")
def main():