setup.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. #! /usr/bin/env python
  2. #
  3. # See README for usage instructions.
  4. import glob
  5. import os
  6. import subprocess
  7. import sys
  8. # We must use setuptools, not distutils, because we need to use the
  9. # namespace_packages option for the "google" package.
  10. from setuptools import setup, Extension, find_packages
  11. from distutils.command.clean import clean as _clean
  12. if sys.version_info[0] == 3:
  13. # Python 3
  14. from distutils.command.build_py import build_py_2to3 as _build_py
  15. else:
  16. # Python 2
  17. from distutils.command.build_py import build_py as _build_py
  18. from distutils.spawn import find_executable
  19. # Find the Protocol Compiler.
  20. if 'PROTOC' in os.environ and os.path.exists(os.environ['PROTOC']):
  21. protoc = os.environ['PROTOC']
  22. elif os.path.exists("../src/protoc"):
  23. protoc = "../src/protoc"
  24. elif os.path.exists("../src/protoc.exe"):
  25. protoc = "../src/protoc.exe"
  26. elif os.path.exists("../vsprojects/Debug/protoc.exe"):
  27. protoc = "../vsprojects/Debug/protoc.exe"
  28. elif os.path.exists("../vsprojects/Release/protoc.exe"):
  29. protoc = "../vsprojects/Release/protoc.exe"
  30. else:
  31. protoc = find_executable("protoc")
  32. def GetVersion():
  33. """Gets the version from google/protobuf/__init__.py
  34. Do not import google.protobuf.__init__ directly, because an installed
  35. protobuf library may be loaded instead."""
  36. with open(os.path.join('google', 'protobuf', '__init__.py')) as version_file:
  37. exec(version_file.read(), globals())
  38. return __version__
  39. def generate_proto(source, require = True):
  40. """Invokes the Protocol Compiler to generate a _pb2.py from the given
  41. .proto file. Does nothing if the output already exists and is newer than
  42. the input."""
  43. if not require and not os.path.exists(source):
  44. return
  45. output = source.replace(".proto", "_pb2.py").replace("../src/", "")
  46. if (not os.path.exists(output) or
  47. (os.path.exists(source) and
  48. os.path.getmtime(source) > os.path.getmtime(output))):
  49. print("Generating %s..." % output)
  50. if not os.path.exists(source):
  51. sys.stderr.write("Can't find required file: %s\n" % source)
  52. sys.exit(-1)
  53. if protoc is None:
  54. sys.stderr.write(
  55. "protoc is not installed nor found in ../src. Please compile it "
  56. "or install the binary package.\n")
  57. sys.exit(-1)
  58. protoc_command = [ protoc, "-I../src", "-I.", "--python_out=.", source ]
  59. if subprocess.call(protoc_command) != 0:
  60. sys.exit(-1)
  61. def GenerateUnittestProtos():
  62. generate_proto("../src/google/protobuf/map_unittest.proto", False)
  63. generate_proto("../src/google/protobuf/unittest_arena.proto", False)
  64. generate_proto("../src/google/protobuf/unittest_no_arena.proto", False)
  65. generate_proto("../src/google/protobuf/unittest_no_arena_import.proto", False)
  66. generate_proto("../src/google/protobuf/unittest.proto", False)
  67. generate_proto("../src/google/protobuf/unittest_custom_options.proto", False)
  68. generate_proto("../src/google/protobuf/unittest_import.proto", False)
  69. generate_proto("../src/google/protobuf/unittest_import_public.proto", False)
  70. generate_proto("../src/google/protobuf/unittest_mset.proto", False)
  71. generate_proto("../src/google/protobuf/unittest_mset_wire_format.proto", False)
  72. generate_proto("../src/google/protobuf/unittest_no_generic_services.proto", False)
  73. generate_proto("../src/google/protobuf/unittest_proto3_arena.proto", False)
  74. generate_proto("../src/google/protobuf/util/json_format_proto3.proto", False)
  75. generate_proto("google/protobuf/internal/any_test.proto", False)
  76. generate_proto("google/protobuf/internal/descriptor_pool_test1.proto", False)
  77. generate_proto("google/protobuf/internal/descriptor_pool_test2.proto", False)
  78. generate_proto("google/protobuf/internal/factory_test1.proto", False)
  79. generate_proto("google/protobuf/internal/factory_test2.proto", False)
  80. generate_proto("google/protobuf/internal/import_test_package/inner.proto", False)
  81. generate_proto("google/protobuf/internal/import_test_package/outer.proto", False)
  82. generate_proto("google/protobuf/internal/missing_enum_values.proto", False)
  83. generate_proto("google/protobuf/internal/message_set_extensions.proto", False)
  84. generate_proto("google/protobuf/internal/more_extensions.proto", False)
  85. generate_proto("google/protobuf/internal/more_extensions_dynamic.proto", False)
  86. generate_proto("google/protobuf/internal/more_messages.proto", False)
  87. generate_proto("google/protobuf/internal/packed_field_test.proto", False)
  88. generate_proto("google/protobuf/internal/test_bad_identifiers.proto", False)
  89. generate_proto("google/protobuf/pyext/python.proto", False)
  90. class clean(_clean):
  91. def run(self):
  92. # Delete generated files in the code tree.
  93. for (dirpath, dirnames, filenames) in os.walk("."):
  94. for filename in filenames:
  95. filepath = os.path.join(dirpath, filename)
  96. if filepath.endswith("_pb2.py") or filepath.endswith(".pyc") or \
  97. filepath.endswith(".so") or filepath.endswith(".o") or \
  98. filepath.endswith('google/protobuf/compiler/__init__.py') or \
  99. filepath.endswith('google/protobuf/util/__init__.py'):
  100. os.remove(filepath)
  101. # _clean is an old-style class, so super() doesn't work.
  102. _clean.run(self)
  103. class build_py(_build_py):
  104. def run(self):
  105. # Generate necessary .proto file if it doesn't exist.
  106. generate_proto("../src/google/protobuf/descriptor.proto")
  107. generate_proto("../src/google/protobuf/compiler/plugin.proto")
  108. generate_proto("../src/google/protobuf/any.proto")
  109. generate_proto("../src/google/protobuf/api.proto")
  110. generate_proto("../src/google/protobuf/duration.proto")
  111. generate_proto("../src/google/protobuf/empty.proto")
  112. generate_proto("../src/google/protobuf/field_mask.proto")
  113. generate_proto("../src/google/protobuf/source_context.proto")
  114. generate_proto("../src/google/protobuf/struct.proto")
  115. generate_proto("../src/google/protobuf/timestamp.proto")
  116. generate_proto("../src/google/protobuf/type.proto")
  117. generate_proto("../src/google/protobuf/wrappers.proto")
  118. GenerateUnittestProtos()
  119. # Make sure google.protobuf/** are valid packages.
  120. for path in ['', 'internal/', 'compiler/', 'pyext/', 'util/']:
  121. try:
  122. open('google/protobuf/%s__init__.py' % path, 'a').close()
  123. except EnvironmentError:
  124. pass
  125. # _build_py is an old-style class, so super() doesn't work.
  126. _build_py.run(self)
  127. class test_conformance(_build_py):
  128. target = 'test_python'
  129. def run(self):
  130. if sys.version_info >= (2, 7):
  131. # Python 2.6 dodges these extra failures.
  132. os.environ["CONFORMANCE_PYTHON_EXTRA_FAILURES"] = (
  133. "--failure_list failure_list_python-post26.txt")
  134. cmd = 'cd ../conformance && make %s' % (test_conformance.target)
  135. status = subprocess.check_call(cmd, shell=True)
  136. def get_option_from_sys_argv(option_str):
  137. if option_str in sys.argv:
  138. sys.argv.remove(option_str)
  139. return True
  140. return False
  141. if __name__ == '__main__':
  142. ext_module_list = []
  143. warnings_as_errors = '--warnings_as_errors'
  144. if get_option_from_sys_argv('--cpp_implementation'):
  145. # Link libprotobuf.a and libprotobuf-lite.a statically with the
  146. # extension. Note that those libraries have to be compiled with
  147. # -fPIC for this to work.
  148. compile_static_ext = get_option_from_sys_argv('--compile_static_extension')
  149. extra_compile_args = ['-Wno-write-strings', '-Wno-invalid-offsetof']
  150. libraries = ['protobuf']
  151. extra_objects = None
  152. if compile_static_ext:
  153. libraries = None
  154. extra_objects = ['../src/.libs/libprotobuf.a',
  155. '../src/.libs/libprotobuf-lite.a']
  156. test_conformance.target = 'test_python_cpp'
  157. if "clang" in os.popen('$CC --version 2> /dev/null').read():
  158. extra_compile_args.append('-Wno-shorten-64-to-32')
  159. if warnings_as_errors in sys.argv:
  160. extra_compile_args.append('-Werror')
  161. sys.argv.remove(warnings_as_errors)
  162. # C++ implementation extension
  163. ext_module_list.extend([
  164. Extension(
  165. "google.protobuf.pyext._message",
  166. glob.glob('google/protobuf/pyext/*.cc'),
  167. include_dirs=[".", "../src"],
  168. libraries=libraries,
  169. extra_objects=extra_objects,
  170. library_dirs=['../src/.libs'],
  171. extra_compile_args=extra_compile_args,
  172. ),
  173. Extension(
  174. "google.protobuf.internal._api_implementation",
  175. glob.glob('google/protobuf/internal/api_implementation.cc'),
  176. extra_compile_args=['-DPYTHON_PROTO2_CPP_IMPL_V2'],
  177. ),
  178. ])
  179. os.environ['PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION'] = 'cpp'
  180. # Keep this list of dependencies in sync with tox.ini.
  181. install_requires = ['six>=1.9', 'setuptools']
  182. if sys.version_info <= (2,7):
  183. install_requires.append('ordereddict')
  184. install_requires.append('unittest2')
  185. setup(
  186. name='protobuf',
  187. version=GetVersion(),
  188. description='Protocol Buffers',
  189. long_description="Protocol Buffers are Google's data interchange format",
  190. url='https://developers.google.com/protocol-buffers/',
  191. maintainer='protobuf@googlegroups.com',
  192. maintainer_email='protobuf@googlegroups.com',
  193. license='New BSD License',
  194. classifiers=[
  195. "Programming Language :: Python",
  196. "Programming Language :: Python :: 2",
  197. "Programming Language :: Python :: 2.6",
  198. "Programming Language :: Python :: 2.7",
  199. "Programming Language :: Python :: 3",
  200. "Programming Language :: Python :: 3.3",
  201. "Programming Language :: Python :: 3.4",
  202. ],
  203. namespace_packages=['google'],
  204. packages=find_packages(
  205. exclude=[
  206. 'import_test_package',
  207. ],
  208. ),
  209. test_suite='google.protobuf.internal',
  210. cmdclass={
  211. 'clean': clean,
  212. 'build_py': build_py,
  213. 'test_conformance': test_conformance,
  214. },
  215. install_requires=install_requires,
  216. ext_modules=ext_module_list,
  217. )