setup.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. #! /usr/bin/env python
  2. #
  3. # See README for usage instructions.
  4. import sys
  5. import os
  6. import subprocess
  7. # We must use setuptools, not distutils, because we need to use the
  8. # namespace_packages option for the "google" package.
  9. try:
  10. from setuptools import setup, Extension, find_packages
  11. except ImportError:
  12. try:
  13. from ez_setup import use_setuptools
  14. use_setuptools()
  15. from setuptools import setup, Extension, find_packages
  16. except ImportError:
  17. sys.stderr.write(
  18. "Could not import setuptools; make sure you have setuptools or "
  19. "ez_setup installed.\n"
  20. )
  21. raise
  22. from distutils.command.clean import clean as _clean
  23. if sys.version_info[0] == 3:
  24. # Python 3
  25. from distutils.command.build_py import build_py_2to3 as _build_py
  26. else:
  27. # Python 2
  28. from distutils.command.build_py import build_py as _build_py
  29. from distutils.spawn import find_executable
  30. # Find the Protocol Compiler.
  31. if 'PROTOC' in os.environ and os.path.exists(os.environ['PROTOC']):
  32. protoc = os.environ['PROTOC']
  33. elif os.path.exists("../src/protoc"):
  34. protoc = "../src/protoc"
  35. elif os.path.exists("../src/protoc.exe"):
  36. protoc = "../src/protoc.exe"
  37. elif os.path.exists("../vsprojects/Debug/protoc.exe"):
  38. protoc = "../vsprojects/Debug/protoc.exe"
  39. elif os.path.exists("../vsprojects/Release/protoc.exe"):
  40. protoc = "../vsprojects/Release/protoc.exe"
  41. else:
  42. protoc = find_executable("protoc")
  43. def GetVersion():
  44. """Gets the version from google/protobuf/__init__.py
  45. Do not import google.protobuf.__init__ directly, because an installed
  46. protobuf library may be loaded instead."""
  47. with open(os.path.join('google', 'protobuf', '__init__.py')) as version_file:
  48. exec(version_file.read())
  49. return __version__
  50. def generate_proto(source):
  51. """Invokes the Protocol Compiler to generate a _pb2.py from the given
  52. .proto file. Does nothing if the output already exists and is newer than
  53. the input."""
  54. output = source.replace(".proto", "_pb2.py").replace("../src/", "")
  55. if (not os.path.exists(output) or
  56. (os.path.exists(source) and
  57. os.path.getmtime(source) > os.path.getmtime(output))):
  58. print("Generating %s..." % output)
  59. if not os.path.exists(source):
  60. sys.stderr.write("Can't find required file: %s\n" % source)
  61. sys.exit(-1)
  62. if protoc is None:
  63. sys.stderr.write(
  64. "protoc is not installed nor found in ../src. "
  65. "Please compile it or install the binary package.\n"
  66. )
  67. sys.exit(-1)
  68. protoc_command = [protoc, "-I../src", "-I.", "--python_out=.", source]
  69. if subprocess.call(protoc_command) != 0:
  70. sys.exit(-1)
  71. def GenerateUnittestProtos():
  72. generate_proto("../src/google/protobuf/unittest.proto")
  73. generate_proto("../src/google/protobuf/unittest_custom_options.proto")
  74. generate_proto("../src/google/protobuf/unittest_import.proto")
  75. generate_proto("../src/google/protobuf/unittest_import_public.proto")
  76. generate_proto("../src/google/protobuf/unittest_mset.proto")
  77. generate_proto("../src/google/protobuf/unittest_no_generic_services.proto")
  78. generate_proto("../src/google/protobuf/unittest_proto3_arena.proto")
  79. generate_proto("google/protobuf/internal/descriptor_pool_test1.proto")
  80. generate_proto("google/protobuf/internal/descriptor_pool_test2.proto")
  81. generate_proto("google/protobuf/internal/factory_test1.proto")
  82. generate_proto("google/protobuf/internal/factory_test2.proto")
  83. generate_proto("google/protobuf/internal/import_test_package/inner.proto")
  84. generate_proto("google/protobuf/internal/import_test_package/outer.proto")
  85. generate_proto("google/protobuf/internal/missing_enum_values.proto")
  86. generate_proto("google/protobuf/internal/more_extensions.proto")
  87. generate_proto("google/protobuf/internal/more_extensions_dynamic.proto")
  88. generate_proto("google/protobuf/internal/more_messages.proto")
  89. generate_proto("google/protobuf/internal/test_bad_identifiers.proto")
  90. generate_proto("google/protobuf/pyext/python.proto")
  91. class clean(_clean):
  92. def run(self):
  93. # Delete generated files in the code tree.
  94. for (dirpath, dirnames, filenames) in os.walk("."):
  95. for filename in filenames:
  96. filepath = os.path.join(dirpath, filename)
  97. if filepath.endswith("_pb2.py") or filepath.endswith(".pyc") or \
  98. filepath.endswith(".so") or filepath.endswith(".o") or \
  99. filepath.endswith('google/protobuf/compiler/__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. GenerateUnittestProtos()
  109. # Make sure google.protobuf/** are valid packages.
  110. for path in ['', 'internal/', 'compiler/', 'pyext/']:
  111. try:
  112. open('google/protobuf/%s__init__.py' % path, 'a').close()
  113. except EnvironmentError:
  114. pass
  115. # _build_py is an old-style class, so super() doesn't work.
  116. _build_py.run(self)
  117. # TODO(mrovner): Subclass to run 2to3 on some files only.
  118. # Tracing what https://wiki.python.org/moin/PortingPythonToPy3k's
  119. # "Approach 2" section on how to get 2to3 to run on source files during
  120. # install under Python 3. This class seems like a good place to put logic
  121. # that calls python3's distutils.util.run_2to3 on the subset of the files we
  122. # have in our release that are subject to conversion.
  123. # See code reference in previous code review.
  124. if __name__ == '__main__':
  125. ext_module_list = []
  126. cpp_impl = '--cpp_implementation'
  127. if cpp_impl in sys.argv:
  128. sys.argv.remove(cpp_impl)
  129. # C++ implementation extension
  130. ext_module_list.append(
  131. Extension(
  132. "google.protobuf.pyext._message",
  133. [
  134. "google/protobuf/pyext/descriptor.cc",
  135. "google/protobuf/pyext/descriptor_containers.cc",
  136. "google/protobuf/pyext/descriptor_pool.cc",
  137. "google/protobuf/pyext/extension_dict.cc",
  138. "google/protobuf/pyext/message.cc",
  139. "google/protobuf/pyext/repeated_composite_container.cc",
  140. "google/protobuf/pyext/repeated_scalar_container.cc",
  141. ],
  142. define_macros=[('GOOGLE_PROTOBUF_HAS_ONEOF', '1')],
  143. include_dirs=[".", "../src"],
  144. libraries=['protobuf'],
  145. library_dirs=['../src/.libs'],
  146. )
  147. )
  148. os.environ['PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION'] = 'cpp'
  149. setup(
  150. name='protobuf',
  151. version=GetVersion(),
  152. description='Protocol Buffers',
  153. long_description="Protocol Buffers are Google's data interchange format",
  154. url='https://developers.google.com/protocol-buffers/',
  155. maintainer='protobuf@googlegroups.com',
  156. maintainer_email='protobuf@googlegroups.com',
  157. license='New BSD License',
  158. classifiers=[
  159. 'Programming Language :: Python :: 2.7',
  160. ],
  161. namespace_packages=['google'],
  162. packages=find_packages(
  163. exclude=[
  164. 'import_test_package',
  165. ],
  166. ),
  167. test_suite='google.protobuf.internal',
  168. cmdclass={
  169. 'clean': clean,
  170. 'build_py': build_py,
  171. },
  172. install_requires=['setuptools'],
  173. ext_modules=ext_module_list,
  174. )