setup.py 10 KB

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