setup.py 11.2 KB
Newer Older
1
#! /usr/bin/env python
temporal's avatar
temporal committed
2 3
#
# See README for usage instructions.
4
from distutils import util
5
import glob
6
import os
7 8
import pkg_resources
import re
9
import subprocess
10
import sys
11
import sysconfig
12
import platform
temporal's avatar
temporal committed
13 14 15

# We must use setuptools, not distutils, because we need to use the
# namespace_packages option for the "google" package.
16
from setuptools import setup, Extension, find_packages
17

18
from distutils.command.build_py import build_py as _build_py
19
from distutils.command.clean import clean as _clean
temporal's avatar
temporal committed
20 21 22
from distutils.spawn import find_executable

# Find the Protocol Compiler.
23 24 25
if 'PROTOC' in os.environ and os.path.exists(os.environ['PROTOC']):
  protoc = os.environ['PROTOC']
elif os.path.exists("../src/protoc"):
temporal's avatar
temporal committed
26
  protoc = "../src/protoc"
27 28
elif os.path.exists("../src/protoc.exe"):
  protoc = "../src/protoc.exe"
29 30 31 32
elif os.path.exists("../vsprojects/Debug/protoc.exe"):
  protoc = "../vsprojects/Debug/protoc.exe"
elif os.path.exists("../vsprojects/Release/protoc.exe"):
  protoc = "../vsprojects/Release/protoc.exe"
temporal's avatar
temporal committed
33 34 35
else:
  protoc = find_executable("protoc")

36

37 38 39
def GetVersion():
  """Gets the version from google/protobuf/__init__.py

40 41
  Do not import google.protobuf.__init__ directly, because an installed
  protobuf library may be loaded instead."""
42 43

  with open(os.path.join('google', 'protobuf', '__init__.py')) as version_file:
Behzad Tabibian's avatar
Behzad Tabibian committed
44
    exec(version_file.read(), globals())
45
    global __version__
46 47 48
    return __version__


49
def generate_proto(source, require = True):
temporal's avatar
temporal committed
50 51 52 53
  """Invokes the Protocol Compiler to generate a _pb2.py from the given
  .proto file.  Does nothing if the output already exists and is newer than
  the input."""

54 55 56
  if not require and not os.path.exists(source):
    return

temporal's avatar
temporal committed
57 58 59 60 61
  output = source.replace(".proto", "_pb2.py").replace("../src/", "")

  if (not os.path.exists(output) or
      (os.path.exists(source) and
       os.path.getmtime(source) > os.path.getmtime(output))):
62
    print("Generating %s..." % output)
temporal's avatar
temporal committed
63

64 65 66 67
    if not os.path.exists(source):
      sys.stderr.write("Can't find required file: %s\n" % source)
      sys.exit(-1)

68
    if protoc is None:
temporal's avatar
temporal committed
69 70 71 72 73
      sys.stderr.write(
          "protoc is not installed nor found in ../src.  Please compile it "
          "or install the binary package.\n")
      sys.exit(-1)

74 75
    protoc_command = [ protoc, "-I../src", "-I.", "--python_out=.", source ]
    if subprocess.call(protoc_command) != 0:
temporal's avatar
temporal committed
76 77
      sys.exit(-1)

78
def GenerateUnittestProtos():
79
  generate_proto("../src/google/protobuf/any_test.proto", False)
80
  generate_proto("../src/google/protobuf/map_proto2_unittest.proto", False)
81
  generate_proto("../src/google/protobuf/map_unittest.proto", False)
82
  generate_proto("../src/google/protobuf/test_messages_proto3.proto", False)
83
  generate_proto("../src/google/protobuf/test_messages_proto2.proto", False)
84 85 86
  generate_proto("../src/google/protobuf/unittest_arena.proto", False)
  generate_proto("../src/google/protobuf/unittest_no_arena.proto", False)
  generate_proto("../src/google/protobuf/unittest_no_arena_import.proto", False)
87 88 89 90 91
  generate_proto("../src/google/protobuf/unittest.proto", False)
  generate_proto("../src/google/protobuf/unittest_custom_options.proto", False)
  generate_proto("../src/google/protobuf/unittest_import.proto", False)
  generate_proto("../src/google/protobuf/unittest_import_public.proto", False)
  generate_proto("../src/google/protobuf/unittest_mset.proto", False)
92
  generate_proto("../src/google/protobuf/unittest_mset_wire_format.proto", False)
93 94
  generate_proto("../src/google/protobuf/unittest_no_generic_services.proto", False)
  generate_proto("../src/google/protobuf/unittest_proto3_arena.proto", False)
95
  generate_proto("../src/google/protobuf/util/json_format_proto3.proto", False)
96
  generate_proto("google/protobuf/internal/any_test.proto", False)
97 98 99 100
  generate_proto("google/protobuf/internal/descriptor_pool_test1.proto", False)
  generate_proto("google/protobuf/internal/descriptor_pool_test2.proto", False)
  generate_proto("google/protobuf/internal/factory_test1.proto", False)
  generate_proto("google/protobuf/internal/factory_test2.proto", False)
101
  generate_proto("google/protobuf/internal/file_options_test.proto", False)
102 103 104
  generate_proto("google/protobuf/internal/import_test_package/inner.proto", False)
  generate_proto("google/protobuf/internal/import_test_package/outer.proto", False)
  generate_proto("google/protobuf/internal/missing_enum_values.proto", False)
105
  generate_proto("google/protobuf/internal/message_set_extensions.proto", False)
106 107 108
  generate_proto("google/protobuf/internal/more_extensions.proto", False)
  generate_proto("google/protobuf/internal/more_extensions_dynamic.proto", False)
  generate_proto("google/protobuf/internal/more_messages.proto", False)
109
  generate_proto("google/protobuf/internal/no_package.proto", False)
110
  generate_proto("google/protobuf/internal/packed_field_test.proto", False)
111 112
  generate_proto("google/protobuf/internal/test_bad_identifiers.proto", False)
  generate_proto("google/protobuf/pyext/python.proto", False)
113

114

115 116 117
class clean(_clean):
  def run(self):
    # Delete generated files in the code tree.
temporal's avatar
temporal committed
118 119 120
    for (dirpath, dirnames, filenames) in os.walk("."):
      for filename in filenames:
        filepath = os.path.join(dirpath, filename)
121
        if filepath.endswith("_pb2.py") or filepath.endswith(".pyc") or \
122
          filepath.endswith(".so") or filepath.endswith(".o"):
temporal's avatar
temporal committed
123
          os.remove(filepath)
124 125 126 127 128
    # _clean is an old-style class, so super() doesn't work.
    _clean.run(self)

class build_py(_build_py):
  def run(self):
temporal's avatar
temporal committed
129 130
    # Generate necessary .proto file if it doesn't exist.
    generate_proto("../src/google/protobuf/descriptor.proto")
131
    generate_proto("../src/google/protobuf/compiler/plugin.proto")
132
    generate_proto("../src/google/protobuf/any.proto")
133 134 135
    generate_proto("../src/google/protobuf/api.proto")
    generate_proto("../src/google/protobuf/duration.proto")
    generate_proto("../src/google/protobuf/empty.proto")
136
    generate_proto("../src/google/protobuf/field_mask.proto")
137 138 139 140 141
    generate_proto("../src/google/protobuf/source_context.proto")
    generate_proto("../src/google/protobuf/struct.proto")
    generate_proto("../src/google/protobuf/timestamp.proto")
    generate_proto("../src/google/protobuf/type.proto")
    generate_proto("../src/google/protobuf/wrappers.proto")
142 143
    GenerateUnittestProtos()

144 145
    # _build_py is an old-style class, so super() doesn't work.
    _build_py.run(self)
146

147 148 149
class test_conformance(_build_py):
  target = 'test_python'
  def run(self):
150 151 152
    # Python 2.6 dodges these extra failures.
    os.environ["CONFORMANCE_PYTHON_EXTRA_FAILURES"] = (
        "--failure_list failure_list_python-post26.txt")
153 154
    cmd = 'cd ../conformance && make %s' % (test_conformance.target)
    status = subprocess.check_call(cmd, shell=True)
155

156

157 158 159 160 161 162 163
def get_option_from_sys_argv(option_str):
  if option_str in sys.argv:
    sys.argv.remove(option_str)
    return True
  return False


164
if __name__ == '__main__':
165
  ext_module_list = []
166
  warnings_as_errors = '--warnings_as_errors'
167 168 169 170 171 172 173 174 175 176 177
  if get_option_from_sys_argv('--cpp_implementation'):
    # Link libprotobuf.a and libprotobuf-lite.a statically with the
    # extension. Note that those libraries have to be compiled with
    # -fPIC for this to work.
    compile_static_ext = get_option_from_sys_argv('--compile_static_extension')
    libraries = ['protobuf']
    extra_objects = None
    if compile_static_ext:
      libraries = None
      extra_objects = ['../src/.libs/libprotobuf.a',
                       '../src/.libs/libprotobuf-lite.a']
178
    test_conformance.target = 'test_python_cpp'
179

Paul Yang's avatar
Paul Yang committed
180 181 182 183 184 185
    extra_compile_args = []

    if sys.platform != 'win32':
        extra_compile_args.append('-Wno-write-strings')
        extra_compile_args.append('-Wno-invalid-offsetof')
        extra_compile_args.append('-Wno-sign-compare')
Feng Xiao's avatar
Feng Xiao committed
186
        extra_compile_args.append('-Wno-unused-variable')
187
        extra_compile_args.append('-std=c++11')
Paul Yang's avatar
Paul Yang committed
188

Feng Xiao's avatar
Feng Xiao committed
189 190 191
    if sys.platform == 'darwin':
      extra_compile_args.append("-Wno-shorten-64-to-32");

192 193 194 195 196 197 198 199 200 201 202 203
    # https://developer.apple.com/documentation/xcode_release_notes/xcode_10_release_notes
    # C++ projects must now migrate to libc++ and are recommended to set a
    # deployment target of macOS 10.9 or later, or iOS 7 or later.
    if sys.platform == 'darwin':
      mac_target = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET')
      if mac_target and (pkg_resources.parse_version(mac_target) <
                       pkg_resources.parse_version('10.9.0')):
        os.environ['MACOSX_DEPLOYMENT_TARGET'] = '10.9'
        os.environ['_PYTHON_HOST_PLATFORM'] = re.sub(
            r'macosx-[0-9]+\.[0-9]+-(.+)', r'macosx-10.9-\1',
            util.get_platform())

Paul Yang's avatar
Paul Yang committed
204 205 206 207 208 209 210 211 212
    # https://github.com/Theano/Theano/issues/4926
    if sys.platform == 'win32':
      extra_compile_args.append('-D_hypot=hypot')

    # https://github.com/tpaviot/pythonocc-core/issues/48
    if sys.platform == 'win32' and  '64 bit' in sys.version:
      extra_compile_args.append('-DMS_WIN64')

    # MSVS default is dymanic
213
    if (sys.platform == 'win32'):
Paul Yang's avatar
Paul Yang committed
214 215
      extra_compile_args.append('/MT')

216
    if "clang" in os.popen('$CC --version 2> /dev/null').read():
217
      extra_compile_args.append('-Wno-shorten-64-to-32')
218 219 220 221 222

    if warnings_as_errors in sys.argv:
      extra_compile_args.append('-Werror')
      sys.argv.remove(warnings_as_errors)

223
    # C++ implementation extension
224
    ext_module_list.extend([
225 226
        Extension(
            "google.protobuf.pyext._message",
227
            glob.glob('google/protobuf/pyext/*.cc'),
228
            include_dirs=[".", "../src"],
229 230
            libraries=libraries,
            extra_objects=extra_objects,
231
            library_dirs=['../src/.libs'],
232
            extra_compile_args=extra_compile_args,
233 234 235 236
        ),
        Extension(
            "google.protobuf.internal._api_implementation",
            glob.glob('google/protobuf/internal/api_implementation.cc'),
Paul Yang's avatar
Paul Yang committed
237
            extra_compile_args=extra_compile_args + ['-DPYTHON_PROTO2_CPP_IMPL_V2'],
238 239
        ),
    ])
240
    os.environ['PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION'] = 'cpp'
241

Dan O'Reilly's avatar
Dan O'Reilly committed
242
  # Keep this list of dependencies in sync with tox.ini.
243
  install_requires = ['six>=1.9', 'setuptools']
Dan O'Reilly's avatar
Dan O'Reilly committed
244 245 246 247
  if sys.version_info <= (2,7):
    install_requires.append('ordereddict')
    install_requires.append('unittest2')

248 249 250 251
  setup(
      name='protobuf',
      version=GetVersion(),
      description='Protocol Buffers',
Feng Xiao's avatar
Feng Xiao committed
252
      download_url='https://github.com/protocolbuffers/protobuf/releases',
253 254 255 256
      long_description="Protocol Buffers are Google's data interchange format",
      url='https://developers.google.com/protocol-buffers/',
      maintainer='protobuf@googlegroups.com',
      maintainer_email='protobuf@googlegroups.com',
257
      license='3-Clause BSD License',
258
      classifiers=[
259 260 261 262 263 264 265
        "Programming Language :: Python",
        "Programming Language :: Python :: 2",
        "Programming Language :: Python :: 2.7",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.3",
        "Programming Language :: Python :: 3.4",
        ],
266
      namespace_packages=['google'],
267 268 269 270 271 272 273 274 275
      packages=find_packages(
          exclude=[
              'import_test_package',
          ],
      ),
      test_suite='google.protobuf.internal',
      cmdclass={
          'clean': clean,
          'build_py': build_py,
276
          'test_conformance': test_conformance,
277
      },
Dan O'Reilly's avatar
Dan O'Reilly committed
278
      install_requires=install_requires,
279 280
      ext_modules=ext_module_list,
  )