setup.py 14 KB

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