setup.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. #!/usr/bin/env python
  2. # This file is dual licensed under the terms of the Apache License, Version
  3. # 2.0, and the BSD License. See the LICENSE file in the root of this repository
  4. # for complete details.
  5. from __future__ import absolute_import, division, print_function
  6. import os
  7. import platform
  8. import subprocess
  9. import sys
  10. from distutils.command.build import build
  11. import pkg_resources
  12. from setuptools import find_packages, setup
  13. from setuptools.command.install import install
  14. from setuptools.command.test import test
  15. base_dir = os.path.dirname(__file__)
  16. src_dir = os.path.join(base_dir, "src")
  17. # When executing the setup.py, we need to be able to import ourselves, this
  18. # means that we need to add the src/ directory to the sys.path.
  19. sys.path.insert(0, src_dir)
  20. about = {}
  21. with open(os.path.join(src_dir, "cryptography", "__about__.py")) as f:
  22. exec(f.read(), about)
  23. VECTORS_DEPENDENCY = "cryptography_vectors=={0}".format(about['__version__'])
  24. setup_requirements = []
  25. if platform.python_implementation() == "PyPy":
  26. if sys.pypy_version_info < (5, 3):
  27. raise RuntimeError(
  28. "cryptography 1.9 is not compatible with PyPy < 5.3. Please "
  29. "upgrade PyPy to use this library."
  30. )
  31. else:
  32. setup_requirements.append("cffi>=1.7")
  33. test_requirements = [
  34. "pytest>=3.2.1,!=3.3.0",
  35. "pretend",
  36. "iso8601",
  37. "pytz",
  38. ]
  39. if sys.version_info[:2] > (2, 6):
  40. test_requirements.append("hypothesis>=1.11.4")
  41. # If there's no vectors locally that probably means we are in a tarball and
  42. # need to go and get the matching vectors package from PyPi
  43. if not os.path.exists(os.path.join(base_dir, "vectors/setup.py")):
  44. test_requirements.append(VECTORS_DEPENDENCY)
  45. class PyTest(test):
  46. def finalize_options(self):
  47. test.finalize_options(self)
  48. self.test_args = []
  49. self.test_suite = True
  50. # This means there's a vectors/ folder with the package in here.
  51. # cd into it, install the vectors package and then refresh sys.path
  52. if VECTORS_DEPENDENCY not in test_requirements:
  53. subprocess.check_call(
  54. [sys.executable, "setup.py", "install"], cwd="vectors"
  55. )
  56. pkg_resources.get_distribution("cryptography_vectors").activate()
  57. def run_tests(self):
  58. # Import here because in module scope the eggs are not loaded.
  59. import pytest
  60. test_args = [os.path.join(base_dir, "tests")]
  61. errno = pytest.main(test_args)
  62. sys.exit(errno)
  63. def keywords_with_side_effects(argv):
  64. """
  65. Get a dictionary with setup keywords that (can) have side effects.
  66. :param argv: A list of strings with command line arguments.
  67. :returns: A dictionary with keyword arguments for the ``setup()`` function.
  68. This setup.py script uses the setuptools 'setup_requires' feature because
  69. this is required by the cffi package to compile extension modules. The
  70. purpose of ``keywords_with_side_effects()`` is to avoid triggering the cffi
  71. build process as a result of setup.py invocations that don't need the cffi
  72. module to be built (setup.py serves the dual purpose of exposing package
  73. metadata).
  74. All of the options listed by ``python setup.py --help`` that print
  75. information should be recognized here. The commands ``clean``,
  76. ``egg_info``, ``register``, ``sdist`` and ``upload`` are also recognized.
  77. Any combination of these options and commands is also supported.
  78. This function was originally based on the `setup.py script`_ of SciPy (see
  79. also the discussion in `pip issue #25`_).
  80. .. _pip issue #25: https://github.com/pypa/pip/issues/25
  81. .. _setup.py script: https://github.com/scipy/scipy/blob/master/setup.py
  82. """
  83. no_setup_requires_arguments = (
  84. '-h', '--help',
  85. '-n', '--dry-run',
  86. '-q', '--quiet',
  87. '-v', '--verbose',
  88. '-V', '--version',
  89. '--author',
  90. '--author-email',
  91. '--classifiers',
  92. '--contact',
  93. '--contact-email',
  94. '--description',
  95. '--egg-base',
  96. '--fullname',
  97. '--help-commands',
  98. '--keywords',
  99. '--licence',
  100. '--license',
  101. '--long-description',
  102. '--maintainer',
  103. '--maintainer-email',
  104. '--name',
  105. '--no-user-cfg',
  106. '--obsoletes',
  107. '--platforms',
  108. '--provides',
  109. '--requires',
  110. '--url',
  111. 'clean',
  112. 'egg_info',
  113. 'register',
  114. 'sdist',
  115. 'upload',
  116. )
  117. def is_short_option(argument):
  118. """Check whether a command line argument is a short option."""
  119. return len(argument) >= 2 and argument[0] == '-' and argument[1] != '-'
  120. def expand_short_options(argument):
  121. """Expand combined short options into canonical short options."""
  122. return ('-' + char for char in argument[1:])
  123. def argument_without_setup_requirements(argv, i):
  124. """Check whether a command line argument needs setup requirements."""
  125. if argv[i] in no_setup_requires_arguments:
  126. # Simple case: An argument which is either an option or a command
  127. # which doesn't need setup requirements.
  128. return True
  129. elif (is_short_option(argv[i]) and
  130. all(option in no_setup_requires_arguments
  131. for option in expand_short_options(argv[i]))):
  132. # Not so simple case: Combined short options none of which need
  133. # setup requirements.
  134. return True
  135. elif argv[i - 1:i] == ['--egg-base']:
  136. # Tricky case: --egg-info takes an argument which should not make
  137. # us use setup_requires (defeating the purpose of this code).
  138. return True
  139. else:
  140. return False
  141. if all(argument_without_setup_requirements(argv, i)
  142. for i in range(1, len(argv))):
  143. return {
  144. "cmdclass": {
  145. "build": DummyBuild,
  146. "install": DummyInstall,
  147. "test": DummyPyTest,
  148. }
  149. }
  150. else:
  151. cffi_modules = [
  152. "src/_cffi_src/build_openssl.py:ffi",
  153. "src/_cffi_src/build_constant_time.py:ffi",
  154. "src/_cffi_src/build_padding.py:ffi",
  155. ]
  156. return {
  157. "setup_requires": setup_requirements,
  158. "cmdclass": {
  159. "test": PyTest,
  160. },
  161. "cffi_modules": cffi_modules
  162. }
  163. setup_requires_error = ("Requested setup command that needs 'setup_requires' "
  164. "while command line arguments implied a side effect "
  165. "free command or option.")
  166. class DummyBuild(build):
  167. """
  168. This class makes it very obvious when ``keywords_with_side_effects()`` has
  169. incorrectly interpreted the command line arguments to ``setup.py build`` as
  170. one of the 'side effect free' commands or options.
  171. """
  172. def run(self):
  173. raise RuntimeError(setup_requires_error)
  174. class DummyInstall(install):
  175. """
  176. This class makes it very obvious when ``keywords_with_side_effects()`` has
  177. incorrectly interpreted the command line arguments to ``setup.py install``
  178. as one of the 'side effect free' commands or options.
  179. """
  180. def run(self):
  181. raise RuntimeError(setup_requires_error)
  182. class DummyPyTest(test):
  183. """
  184. This class makes it very obvious when ``keywords_with_side_effects()`` has
  185. incorrectly interpreted the command line arguments to ``setup.py test`` as
  186. one of the 'side effect free' commands or options.
  187. """
  188. def run_tests(self):
  189. raise RuntimeError(setup_requires_error)
  190. with open(os.path.join(base_dir, "README.rst")) as f:
  191. long_description = f.read()
  192. setup(
  193. name=about["__title__"],
  194. version=about["__version__"],
  195. description=about["__summary__"],
  196. long_description=long_description,
  197. license=about["__license__"],
  198. url=about["__uri__"],
  199. author=about["__author__"],
  200. author_email=about["__email__"],
  201. classifiers=[
  202. "Intended Audience :: Developers",
  203. "License :: OSI Approved :: Apache Software License",
  204. "License :: OSI Approved :: BSD License",
  205. "Natural Language :: English",
  206. "Operating System :: MacOS :: MacOS X",
  207. "Operating System :: POSIX",
  208. "Operating System :: POSIX :: BSD",
  209. "Operating System :: POSIX :: Linux",
  210. "Operating System :: Microsoft :: Windows",
  211. "Programming Language :: Python",
  212. "Programming Language :: Python :: 2",
  213. "Programming Language :: Python :: 2.6",
  214. "Programming Language :: Python :: 2.7",
  215. "Programming Language :: Python :: 3",
  216. "Programming Language :: Python :: 3.4",
  217. "Programming Language :: Python :: 3.5",
  218. "Programming Language :: Python :: 3.6",
  219. "Programming Language :: Python :: Implementation :: CPython",
  220. "Programming Language :: Python :: Implementation :: PyPy",
  221. "Topic :: Security :: Cryptography",
  222. ],
  223. package_dir={"": "src"},
  224. packages=find_packages(where="src", exclude=["_cffi_src", "_cffi_src.*"]),
  225. include_package_data=True,
  226. install_requires=[
  227. "idna >= 2.1",
  228. "asn1crypto >= 0.21.0",
  229. "six >= 1.4.1",
  230. ],
  231. tests_require=test_requirements,
  232. extras_require={
  233. ":python_version < '3'": ["enum34", "ipaddress"],
  234. ":platform_python_implementation != 'PyPy'": ["cffi >= 1.7"],
  235. "test": test_requirements,
  236. "docstest": [
  237. "doc8",
  238. "pyenchant >= 1.6.11",
  239. "readme_renderer >= 16.0",
  240. "sphinx",
  241. "sphinx_rtd_theme",
  242. "sphinxcontrib-spelling",
  243. ],
  244. "pep8test": [
  245. "flake8",
  246. "flake8-import-order",
  247. "pep8-naming",
  248. ],
  249. },
  250. # for cffi
  251. zip_safe=False,
  252. ext_package="cryptography.hazmat.bindings",
  253. **keywords_with_side_effects(sys.argv)
  254. )