setup.py 10.4 KB
Newer Older
1
#! /usr/bin/env python
temporal's avatar
temporal committed
2 3
#
# See README for usage instructions.
4
import glob
5 6
import os
import subprocess
7
import sys
8
import platform
temporal's avatar
temporal committed
9 10 11

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

14
from distutils.command.clean import clean as _clean
15 16 17 18

if sys.version_info[0] == 3:
  # Python 3
  from distutils.command.build_py import build_py_2to3 as _build_py
19
else:
20 21
  # Python 2
  from distutils.command.build_py import build_py as _build_py
temporal's avatar
temporal committed
22 23 24
from distutils.spawn import find_executable

# Find the Protocol Compiler.
25 26 27
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
28
  protoc = "../src/protoc"
29 30
elif os.path.exists("../src/protoc.exe"):
  protoc = "../src/protoc.exe"
31 32 33 34
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
35 36 37
else:
  protoc = find_executable("protoc")

38

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

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

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


50
def generate_proto(source, require = True):
temporal's avatar
temporal committed
51 52 53 54
  """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."""

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

temporal's avatar
temporal committed
58 59 60 61 62
  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))):
63
    print("Generating %s..." % output)
temporal's avatar
temporal committed
64

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

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

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

79
def GenerateUnittestProtos():
80
  generate_proto("../src/google/protobuf/any_test.proto", False)
81
  generate_proto("../src/google/protobuf/map_proto2_unittest.proto", False)
82
  generate_proto("../src/google/protobuf/map_unittest.proto", False)
83
  generate_proto("../src/google/protobuf/test_messages_proto3.proto", False)
84
  generate_proto("../src/google/protobuf/test_messages_proto2.proto", False)
85 86 87
  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)
88 89 90 91 92
  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)
93
  generate_proto("../src/google/protobuf/unittest_mset_wire_format.proto", False)
94 95
  generate_proto("../src/google/protobuf/unittest_no_generic_services.proto", False)
  generate_proto("../src/google/protobuf/unittest_proto3_arena.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 99 100 101
  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)
102
  generate_proto("google/protobuf/internal/file_options_test.proto", False)
103 104 105
  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)
106
  generate_proto("google/protobuf/internal/message_set_extensions.proto", False)
107 108 109
  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)
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") or \
123 124
          filepath.endswith('google/protobuf/compiler/__init__.py') or \
          filepath.endswith('google/protobuf/util/__init__.py'):
temporal's avatar
temporal committed
125
          os.remove(filepath)
126 127 128 129 130
    # _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
131 132
    # Generate necessary .proto file if it doesn't exist.
    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 136 137
    generate_proto("../src/google/protobuf/api.proto")
    generate_proto("../src/google/protobuf/duration.proto")
    generate_proto("../src/google/protobuf/empty.proto")
138
    generate_proto("../src/google/protobuf/field_mask.proto")
139 140 141 142 143
    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")
144 145 146
    GenerateUnittestProtos()

    # Make sure google.protobuf/** are valid packages.
147
    for path in ['', 'internal/', 'compiler/', 'pyext/', 'util/']:
148 149 150 151
      try:
        open('google/protobuf/%s__init__.py' % path, 'a').close()
      except EnvironmentError:
        pass
152 153
    # _build_py is an old-style class, so super() doesn't work.
    _build_py.run(self)
154

155 156 157
class test_conformance(_build_py):
  target = 'test_python'
  def run(self):
158 159 160 161
    if sys.version_info >= (2, 7):
      # Python 2.6 dodges these extra failures.
      os.environ["CONFORMANCE_PYTHON_EXTRA_FAILURES"] = (
          "--failure_list failure_list_python-post26.txt")
162 163
    cmd = 'cd ../conformance && make %s' % (test_conformance.target)
    status = subprocess.check_call(cmd, shell=True)
164

165

166 167 168 169 170 171 172
def get_option_from_sys_argv(option_str):
  if option_str in sys.argv:
    sys.argv.remove(option_str)
    return True
  return False


173
if __name__ == '__main__':
174
  ext_module_list = []
175
  warnings_as_errors = '--warnings_as_errors'
176 177 178 179 180
  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')
181 182 183
    extra_compile_args = ['-Wno-write-strings',
                          '-Wno-invalid-offsetof',
                          '-Wno-sign-compare']
184 185 186 187 188 189
    libraries = ['protobuf']
    extra_objects = None
    if compile_static_ext:
      libraries = None
      extra_objects = ['../src/.libs/libprotobuf.a',
                       '../src/.libs/libprotobuf-lite.a']
190
    test_conformance.target = 'test_python_cpp'
191

192
    if "clang" in os.popen('$CC --version 2> /dev/null').read():
193
      extra_compile_args.append('-Wno-shorten-64-to-32')
194

195 196 197 198 199 200
    v, _, _ = platform.mac_ver()
    if v:
      v = float('.'.join(v.split('.')[:2]))
      if v >= 10.12:
        extra_compile_args.append('-std=c++11')

201 202 203 204
    if warnings_as_errors in sys.argv:
      extra_compile_args.append('-Werror')
      sys.argv.remove(warnings_as_errors)

205
    # C++ implementation extension
206
    ext_module_list.extend([
207 208
        Extension(
            "google.protobuf.pyext._message",
209
            glob.glob('google/protobuf/pyext/*.cc'),
210
            include_dirs=[".", "../src"],
211 212
            libraries=libraries,
            extra_objects=extra_objects,
213
            library_dirs=['../src/.libs'],
214
            extra_compile_args=extra_compile_args,
215 216 217 218 219 220 221
        ),
        Extension(
            "google.protobuf.internal._api_implementation",
            glob.glob('google/protobuf/internal/api_implementation.cc'),
            extra_compile_args=['-DPYTHON_PROTO2_CPP_IMPL_V2'],
        ),
    ])
222
    os.environ['PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION'] = 'cpp'
223

Dan O'Reilly's avatar
Dan O'Reilly committed
224
  # Keep this list of dependencies in sync with tox.ini.
225
  install_requires = ['six>=1.9', 'setuptools']
Dan O'Reilly's avatar
Dan O'Reilly committed
226 227 228 229
  if sys.version_info <= (2,7):
    install_requires.append('ordereddict')
    install_requires.append('unittest2')

230 231 232 233
  setup(
      name='protobuf',
      version=GetVersion(),
      description='Protocol Buffers',
234
      download_url='https://github.com/google/protobuf/releases',
235 236 237 238
      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',
239
      license='3-Clause BSD License',
240
      classifiers=[
241 242 243 244 245 246 247 248
        "Programming Language :: Python",
        "Programming Language :: Python :: 2",
        "Programming Language :: Python :: 2.6",
        "Programming Language :: Python :: 2.7",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.3",
        "Programming Language :: Python :: 3.4",
        ],
249
      namespace_packages=['google'],
250 251 252 253 254 255 256 257 258
      packages=find_packages(
          exclude=[
              'import_test_package',
          ],
      ),
      test_suite='google.protobuf.internal',
      cmdclass={
          'clean': clean,
          'build_py': build_py,
259
          'test_conformance': test_conformance,
260
      },
Dan O'Reilly's avatar
Dan O'Reilly committed
261
      install_requires=install_requires,
262 263
      ext_modules=ext_module_list,
  )