setup.py 7.5 KB

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