1# Copyright 2016 gRPC authors. 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14 15import os 16import pkg_resources 17import sys 18 19import setuptools 20 21from grpc_tools import protoc 22 23 24def build_package_protos(package_root, strict_mode=False): 25 proto_files = [] 26 inclusion_root = os.path.abspath(package_root) 27 for root, _, files in os.walk(inclusion_root): 28 for filename in files: 29 if filename.endswith('.proto'): 30 proto_files.append(os.path.abspath(os.path.join(root, 31 filename))) 32 33 well_known_protos_include = pkg_resources.resource_filename( 34 'grpc_tools', '_proto') 35 36 for proto_file in proto_files: 37 command = [ 38 'grpc_tools.protoc', 39 '--proto_path={}'.format(inclusion_root), 40 '--proto_path={}'.format(well_known_protos_include), 41 '--python_out={}'.format(inclusion_root), 42 '--grpc_python_out={}'.format(inclusion_root), 43 ] + [proto_file] 44 if protoc.main(command) != 0: 45 if strict_mode: 46 raise Exception('error: {} failed'.format(command)) 47 else: 48 sys.stderr.write('warning: {} failed'.format(command)) 49 50 51class BuildPackageProtos(setuptools.Command): 52 """Command to generate project *_pb2.py modules from proto files.""" 53 54 description = 'build grpc protobuf modules' 55 user_options = [('strict-mode', 's', 56 'exit with non-zero value if the proto compiling fails.')] 57 58 def initialize_options(self): 59 self.strict_mode = False 60 61 def finalize_options(self): 62 pass 63 64 def run(self): 65 # due to limitations of the proto generator, we require that only *one* 66 # directory is provided as an 'include' directory. We assume it's the '' key 67 # to `self.distribution.package_dir` (and get a key error if it's not 68 # there). 69 build_package_protos(self.distribution.package_dir[''], 70 self.strict_mode) 71