setup.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. #! /usr/bin/env python
  2. #
  3. # See README for usage instructions.
  4. from distutils import util
  5. import glob
  6. import os
  7. import pkg_resources
  8. import re
  9. import subprocess
  10. import sys
  11. import sysconfig
  12. import platform
  13. # We must use setuptools, not distutils, because we need to use the
  14. # namespace_packages option for the "google" package.
  15. from setuptools import setup, Extension, find_packages
  16. from distutils.command.build_py import build_py as _build_py
  17. from distutils.command.clean import clean as _clean
  18. from distutils.spawn import find_executable
  19. current_dir = os.path.dirname(__file__)
  20. current_dir_relative = os.path.relpath(current_dir)
  21. src_dir = os.path.abspath(os.path.join(current_dir, "..", "src"))
  22. vsprojects_dir = os.path.abspath(os.path.join(current_dir, "..", "vsprojects"))
  23. # Find the Protocol Compiler.
  24. if 'PROTOC' in os.environ and os.path.exists(os.environ['PROTOC']):
  25. protoc = os.environ['PROTOC']
  26. elif os.path.exists(os.path.join(src_dir, "protoc")):
  27. protoc = os.path.join(src_dir, "protoc")
  28. elif os.path.exists(os.path.join(src_dir, "protoc.exe")):
  29. protoc = os.path.join(src_dir, "protoc.exe")
  30. elif os.path.exists(os.path.join(vsprojects_dir, "Debug", "protoc.exe")):
  31. protoc = os.path.join(vsprojects_dir, "Debug", "protoc.exe")
  32. elif os.path.exists(os.path.join(vsprojects_dir, "Release", "protoc.exe")):
  33. protoc = os.path.join(vsprojects_dir, "Release", "protoc.exe")
  34. else:
  35. protoc = find_executable("protoc")
  36. def GetVersion():
  37. """Gets the version from google/protobuf/__init__.py
  38. Do not import google.protobuf.__init__ directly, because an installed
  39. protobuf library may be loaded instead."""
  40. with open(os.path.join(current_dir, 'google', 'protobuf', '__init__.py')) as version_file:
  41. exec(version_file.read(), globals())
  42. global __version__
  43. return __version__
  44. def generate_proto(source, require = True):
  45. """Invokes the Protocol Compiler to generate a _pb2.py from the given
  46. .proto file. Does nothing if the output already exists and is newer than
  47. the input."""
  48. original_source = source
  49. source = source.replace("../src", src_dir)
  50. if not require and not os.path.exists(source):
  51. return
  52. output = os.path.join(
  53. current_dir,
  54. original_source.replace(".proto", "_pb2.py").replace("../src/", "")
  55. )
  56. if (not os.path.exists(output) or
  57. (os.path.exists(source) and
  58. os.path.getmtime(source) > os.path.getmtime(output))):
  59. print("Generating %s..." % os.path.relpath(output))
  60. if not os.path.exists(source):
  61. sys.stderr.write("Can't find required file: %s\n" % source)
  62. sys.exit(-1)
  63. if protoc is None:
  64. sys.stderr.write(
  65. "protoc is not installed nor found in ../src. Please compile it "
  66. "or install the binary package.\n")
  67. sys.exit(-1)
  68. protoc_command = [
  69. protoc,
  70. "-I{}".format(src_dir),
  71. "-I{}".format(current_dir),
  72. "--python_out={}".format(current_dir),
  73. source,
  74. ]
  75. if subprocess.call(protoc_command) != 0:
  76. sys.exit(-1)
  77. def GenerateUnittestProtos():
  78. generate_proto("../src/google/protobuf/any_test.proto", False)
  79. generate_proto("../src/google/protobuf/map_proto2_unittest.proto", False)
  80. generate_proto("../src/google/protobuf/map_unittest.proto", False)
  81. generate_proto("../src/google/protobuf/test_messages_proto3.proto", False)
  82. generate_proto("../src/google/protobuf/test_messages_proto2.proto", False)
  83. generate_proto("../src/google/protobuf/unittest_arena.proto", False)
  84. generate_proto("../src/google/protobuf/unittest_no_arena.proto", False)
  85. generate_proto("../src/google/protobuf/unittest_no_arena_import.proto", False)
  86. generate_proto("../src/google/protobuf/unittest.proto", False)
  87. generate_proto("../src/google/protobuf/unittest_custom_options.proto", False)
  88. generate_proto("../src/google/protobuf/unittest_import.proto", False)
  89. generate_proto("../src/google/protobuf/unittest_import_public.proto", False)
  90. generate_proto("../src/google/protobuf/unittest_mset.proto", False)
  91. generate_proto("../src/google/protobuf/unittest_mset_wire_format.proto", False)
  92. generate_proto("../src/google/protobuf/unittest_no_generic_services.proto", False)
  93. generate_proto("../src/google/protobuf/unittest_proto3_arena.proto", False)
  94. generate_proto("../src/google/protobuf/util/json_format.proto", False)
  95. generate_proto("../src/google/protobuf/util/json_format_proto3.proto", False)
  96. generate_proto("google/protobuf/internal/any_test.proto", False)
  97. generate_proto("google/protobuf/internal/descriptor_pool_test1.proto", False)
  98. generate_proto("google/protobuf/internal/descriptor_pool_test2.proto", False)
  99. generate_proto("google/protobuf/internal/factory_test1.proto", False)
  100. generate_proto("google/protobuf/internal/factory_test2.proto", False)
  101. generate_proto("google/protobuf/internal/file_options_test.proto", False)
  102. generate_proto("google/protobuf/internal/import_test_package/inner.proto", False)
  103. generate_proto("google/protobuf/internal/import_test_package/outer.proto", False)
  104. generate_proto("google/protobuf/internal/missing_enum_values.proto", False)
  105. generate_proto("google/protobuf/internal/message_set_extensions.proto", False)
  106. generate_proto("google/protobuf/internal/more_extensions.proto", False)
  107. generate_proto("google/protobuf/internal/more_extensions_dynamic.proto", False)
  108. generate_proto("google/protobuf/internal/more_messages.proto", False)
  109. generate_proto("google/protobuf/internal/no_package.proto", False)
  110. generate_proto("google/protobuf/internal/packed_field_test.proto", False)
  111. generate_proto("google/protobuf/internal/test_bad_identifiers.proto", False)
  112. generate_proto("google/protobuf/pyext/python.proto", False)
  113. class clean(_clean):
  114. def run(self):
  115. # Delete generated files in the code tree.
  116. for (dirpath, dirnames, filenames) in os.walk(current_dir):
  117. for filename in filenames:
  118. filepath = os.path.join(dirpath, filename)
  119. if filepath.endswith("_pb2.py") or filepath.endswith(".pyc") or \
  120. filepath.endswith(".so") or filepath.endswith(".o"):
  121. os.remove(filepath)
  122. # _clean is an old-style class, so super() doesn't work.
  123. _clean.run(self)
  124. class build_py(_build_py):
  125. def run(self):
  126. # Generate necessary .proto file if it doesn't exist.
  127. generate_proto("../src/google/protobuf/descriptor.proto")
  128. generate_proto("../src/google/protobuf/compiler/plugin.proto")
  129. generate_proto("../src/google/protobuf/any.proto")
  130. generate_proto("../src/google/protobuf/api.proto")
  131. generate_proto("../src/google/protobuf/duration.proto")
  132. generate_proto("../src/google/protobuf/empty.proto")
  133. generate_proto("../src/google/protobuf/field_mask.proto")
  134. generate_proto("../src/google/protobuf/source_context.proto")
  135. generate_proto("../src/google/protobuf/struct.proto")
  136. generate_proto("../src/google/protobuf/timestamp.proto")
  137. generate_proto("../src/google/protobuf/type.proto")
  138. generate_proto("../src/google/protobuf/wrappers.proto")
  139. GenerateUnittestProtos()
  140. # _build_py is an old-style class, so super() doesn't work.
  141. _build_py.run(self)
  142. class test_conformance(_build_py):
  143. target = 'test_python'
  144. def run(self):
  145. # Python 2.6 dodges these extra failures.
  146. os.environ["CONFORMANCE_PYTHON_EXTRA_FAILURES"] = (
  147. "--failure_list failure_list_python-post26.txt")
  148. cmd = 'cd ../conformance && make %s' % (test_conformance.target)
  149. status = subprocess.check_call(cmd, shell=True)
  150. def get_option_from_sys_argv(option_str):
  151. if option_str in sys.argv:
  152. sys.argv.remove(option_str)
  153. return True
  154. return False
  155. if __name__ == '__main__':
  156. ext_module_list = []
  157. warnings_as_errors = '--warnings_as_errors'
  158. if get_option_from_sys_argv('--cpp_implementation'):
  159. # Link libprotobuf.a and libprotobuf-lite.a statically with the
  160. # extension. Note that those libraries have to be compiled with
  161. # -fPIC for this to work.
  162. compile_static_ext = get_option_from_sys_argv('--compile_static_extension')
  163. libraries = ['protobuf']
  164. extra_objects = None
  165. if compile_static_ext:
  166. libraries = None
  167. extra_objects = ['../src/.libs/libprotobuf.a',
  168. '../src/.libs/libprotobuf-lite.a']
  169. test_conformance.target = 'test_python_cpp'
  170. extra_compile_args = []
  171. if sys.platform != 'win32':
  172. extra_compile_args.append('-Wno-write-strings')
  173. extra_compile_args.append('-Wno-invalid-offsetof')
  174. extra_compile_args.append('-Wno-sign-compare')
  175. extra_compile_args.append('-Wno-unused-variable')
  176. extra_compile_args.append('-std=c++11')
  177. if sys.platform == 'darwin':
  178. extra_compile_args.append("-Wno-shorten-64-to-32");
  179. extra_compile_args.append("-Wno-deprecated-register");
  180. # https://developer.apple.com/documentation/xcode_release_notes/xcode_10_release_notes
  181. # C++ projects must now migrate to libc++ and are recommended to set a
  182. # deployment target of macOS 10.9 or later, or iOS 7 or later.
  183. if sys.platform == 'darwin':
  184. mac_target = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET')
  185. if mac_target and (pkg_resources.parse_version(mac_target) <
  186. pkg_resources.parse_version('10.9.0')):
  187. os.environ['MACOSX_DEPLOYMENT_TARGET'] = '10.9'
  188. os.environ['_PYTHON_HOST_PLATFORM'] = re.sub(
  189. r'macosx-[0-9]+\.[0-9]+-(.+)', r'macosx-10.9-\1',
  190. util.get_platform())
  191. # https://github.com/Theano/Theano/issues/4926
  192. if sys.platform == 'win32':
  193. extra_compile_args.append('-D_hypot=hypot')
  194. # https://github.com/tpaviot/pythonocc-core/issues/48
  195. if sys.platform == 'win32' and '64 bit' in sys.version:
  196. extra_compile_args.append('-DMS_WIN64')
  197. # MSVS default is dymanic
  198. if (sys.platform == 'win32'):
  199. extra_compile_args.append('/MT')
  200. if "clang" in os.popen('$CC --version 2> /dev/null').read():
  201. extra_compile_args.append('-Wno-shorten-64-to-32')
  202. if warnings_as_errors in sys.argv:
  203. extra_compile_args.append('-Werror')
  204. sys.argv.remove(warnings_as_errors)
  205. # C++ implementation extension
  206. ext_module_list.extend([
  207. Extension(
  208. "google.protobuf.pyext._message",
  209. glob.glob('google/protobuf/pyext/*.cc'),
  210. include_dirs=[".", "../src"],
  211. libraries=libraries,
  212. extra_objects=extra_objects,
  213. library_dirs=['../src/.libs'],
  214. extra_compile_args=extra_compile_args,
  215. ),
  216. Extension(
  217. "google.protobuf.internal._api_implementation",
  218. glob.glob('google/protobuf/internal/api_implementation.cc'),
  219. extra_compile_args=extra_compile_args + ['-DPYTHON_PROTO2_CPP_IMPL_V2'],
  220. ),
  221. ])
  222. os.environ['PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION'] = 'cpp'
  223. # Keep this list of dependencies in sync with tox.ini.
  224. install_requires = ['six>=1.9', 'setuptools']
  225. if sys.version_info <= (2,7):
  226. install_requires.append('ordereddict')
  227. install_requires.append('unittest2')
  228. setup(
  229. name='protobuf',
  230. version=GetVersion(),
  231. description='Protocol Buffers',
  232. download_url='https://github.com/protocolbuffers/protobuf/releases',
  233. long_description="Protocol Buffers are Google's data interchange format",
  234. url='https://developers.google.com/protocol-buffers/',
  235. maintainer='protobuf@googlegroups.com',
  236. maintainer_email='protobuf@googlegroups.com',
  237. license='3-Clause BSD License',
  238. classifiers=[
  239. "Programming Language :: Python",
  240. "Programming Language :: Python :: 2",
  241. "Programming Language :: Python :: 2.7",
  242. "Programming Language :: Python :: 3",
  243. "Programming Language :: Python :: 3.3",
  244. "Programming Language :: Python :: 3.4",
  245. "Programming Language :: Python :: 3.5",
  246. "Programming Language :: Python :: 3.6",
  247. "Programming Language :: Python :: 3.7",
  248. ],
  249. namespace_packages=['google'],
  250. # package_dir is required when setup.py is not run from the python/
  251. # directory (such as from the ReadTheDocs build). See
  252. # https://setuptools.readthedocs.io/en/latest/setuptools.html#using-find-packages
  253. # package_dir must be a relative path. See:
  254. # https://stackoverflow.com/a/53547931/101923
  255. package_dir={"": current_dir_relative},
  256. packages=find_packages(
  257. where=current_dir,
  258. exclude=[
  259. 'import_test_package',
  260. ],
  261. ),
  262. test_suite='google.protobuf.internal',
  263. cmdclass={
  264. 'clean': clean,
  265. 'build_py': build_py,
  266. 'test_conformance': test_conformance,
  267. },
  268. install_requires=install_requires,
  269. ext_modules=ext_module_list,
  270. )