Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save JohannesBuchner/c1fc8274ae4d0e7dd519876447856e81 to your computer and use it in GitHub Desktop.
Save JohannesBuchner/c1fc8274ae4d0e7dd519876447856e81 to your computer and use it in GitHub Desktop.
Convert setup.py to pyproject.toml (WIP)
# Help create a pyproject.toml from a setup.py file
#
# USAGE:
# 1)
# replace "from [a-z.]* import setup" in your setup.py
# with "from convert_setup_py_to_pyproject_toml import setup"
# 2)
# run the resulting script with python, with this script in the PYTHONPATH
#
# The above can be achieved on Linux, for example, with:
# sed 's/from [a-z.]* import setup/from convert_setup_py_to_pyproject_toml import setup/g' setup.py | PYTHONPATH=. python3
#
def toml_list(f, k, l):
f.write('%s = [\n' % k)
for e in l:
f.write(' "%s",\n' % e)
f.write(']\n')
def remove_keys(kwargs, keys):
for k in keys:
if k in kwargs:
print("you can remove %s from setup.py" % k)
del kwargs[k]
def setup(**kwargs):
with open('pyproject.toml.proposed', 'w') as f:
f.write('[project]\n')
copy_keys = 'name', 'version', 'description', 'license'
for k in copy_keys:
f.write('%s = "%s"\n' % (k, kwargs.get(k, '???????')))
remove_keys(kwargs, copy_keys)
if 'author' not in kwargs:
kwargs['author'] = '??????'
if 'author_email' in kwargs:
f.write('authors = ["%(author)s"]\n' % kwargs)
else:
f.write('authors = ["%(author)s <%(author_email)s>"]\n' % kwargs)
remove_keys(kwargs, ['author', 'author_email'])
keywords = kwargs.get('keywords', [])
if hasattr(keywords, 'split'):
keywords = keywords.split()
toml_list(f, 'keywords', keywords)
if 'classifiers' in kwargs:
toml_list(f, 'classifiers', kwargs['classifiers'])
remove_keys(kwargs, ['classifiers'])
if 'python_requires' in kwargs:
f.write('requires-python = "%(python_requires)s"\n' % kwargs)
toml_list(f, 'dependencies', kwargs.get('install_requires', []))
# urls
f.write('\n\n[project.urls]\n')
if 'project_urls' in kwargs:
for k, v in project_urls.items():
f.write('%s = "%s"\n' % (k, v))
else:
f.write('Documentation = "%s"\n' % (kwargs.get('url', '')))
f.write('Source = "%s"\n' % (kwargs.get('url', '')))
f.write('\n\n[project.optional-dependencies]\n')
for k, v in kwargs.get('extras_require', {}).items():
toml_list(f, k, v)
if 'test_require' in kwargs:
toml_list(f, 'test', kwargs['test_require'])
remove_keys(kwargs, ['python_requires', 'extras_require', 'test_require', 'install_requires', 'setup_requires'])
# build dependencies
f.write('\n\n[build-system]\n')
build_requires = kwargs.get('install_requires', [])
for r in kwargs.get('setup_requires', []):
if r not in build_requires:
build_requires.append(r)
toml_list(f, 'requires', build_requires)
# test that result is valid:
import toml
parsed_toml = toml.load(open('pyproject.toml.proposed'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment