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


grpc
Author(s):
autogenerated on Thu Mar 13 2025 03:01:18