PageRenderTime 28ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/third_party/protobuf/python/protobuf_distutils/protobuf_distutils/generate_py_protobufs.py

https://github.com/chromium/chromium
Python | 147 lines | 61 code | 17 blank | 69 comment | 13 complexity | d6b6e3022bc30b9fd9fc3897df10f3d0 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, Apache-2.0, BSD-3-Clause
  1. # Protocol Buffers - Google's data interchange format
  2. # Copyright 2008 Google Inc. All rights reserved.
  3. # https://developers.google.com/protocol-buffers/
  4. #
  5. # Redistribution and use in source and binary forms, with or without
  6. # modification, are permitted provided that the following conditions are
  7. # met:
  8. #
  9. # * Redistributions of source code must retain the above copyright
  10. # notice, this list of conditions and the following disclaimer.
  11. # * Redistributions in binary form must reproduce the above
  12. # copyright notice, this list of conditions and the following disclaimer
  13. # in the documentation and/or other materials provided with the
  14. # distribution.
  15. # * Neither the name of Google Inc. nor the names of its
  16. # contributors may be used to endorse or promote products derived from
  17. # this software without specific prior written permission.
  18. #
  19. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. """Implements the generate_py_protobufs command."""
  31. __author__ = 'dlj@google.com (David L. Jones)'
  32. import glob
  33. import sys
  34. import os
  35. import distutils.spawn as spawn
  36. from distutils.cmd import Command
  37. from distutils.errors import DistutilsOptionError, DistutilsExecError
  38. class generate_py_protobufs(Command):
  39. """Generates Python sources for .proto files."""
  40. description = 'Generate Python sources for .proto files'
  41. user_options = [
  42. ('extra-proto-paths=', None,
  43. 'Additional paths to resolve imports in .proto files.'),
  44. ('protoc=', None,
  45. 'Path to a specific `protoc` command to use.'),
  46. ]
  47. boolean_options = ['recurse']
  48. def initialize_options(self):
  49. """Sets the defaults for the command options."""
  50. self.source_dir = None
  51. self.proto_root_path = None
  52. self.extra_proto_paths = []
  53. self.output_dir = '.'
  54. self.proto_files = None
  55. self.recurse = True
  56. self.protoc = None
  57. def finalize_options(self):
  58. """Sets the final values for the command options.
  59. Defaults were set in `initialize_options`, but could have been changed
  60. by command-line options or by other commands.
  61. """
  62. self.ensure_dirname('source_dir')
  63. self.ensure_string_list('extra_proto_paths')
  64. if self.output_dir is None:
  65. self.output_dir = '.'
  66. self.ensure_dirname('output_dir')
  67. # SUBTLE: if 'source_dir' is a subdirectory of any entry in
  68. # 'extra_proto_paths', then in general, the shortest --proto_path prefix
  69. # (and the longest relative .proto filenames) must be used for
  70. # correctness. For example, consider:
  71. #
  72. # source_dir = 'a/b/c'
  73. # extra_proto_paths = ['a/b', 'x/y']
  74. #
  75. # In this case, we must ensure that a/b/c/d/foo.proto resolves
  76. # canonically as c/d/foo.proto, not just d/foo.proto. Otherwise, this
  77. # import:
  78. #
  79. # import "c/d/foo.proto";
  80. #
  81. # would result in different FileDescriptor.name keys from "d/foo.proto".
  82. # That will cause all the definitions in the file to be flagged as
  83. # duplicates, with an error similar to:
  84. #
  85. # c/d/foo.proto: "packagename.MessageName" is already defined in file "d/foo.proto"
  86. #
  87. # For paths in self.proto_files, we transform them to be relative to
  88. # self.proto_root_path, which may be different from self.source_dir.
  89. #
  90. # Although the order of --proto_paths is significant, shadowed filenames
  91. # are errors: if 'a/b/c.proto' resolves to different files under two
  92. # different --proto_path arguments, then the path is rejected as an
  93. # error. (Implementation note: this is enforced in protoc's
  94. # DiskSourceTree class.)
  95. if self.proto_root_path is None:
  96. self.proto_root_path = os.path.normpath(self.source_dir)
  97. for root_candidate in self.extra_proto_paths:
  98. root_candidate = os.path.normpath(root_candidate)
  99. if self.proto_root_path.startswith(root_candidate):
  100. self.proto_root_path = root_candidate
  101. if self.proto_root_path != self.source_dir:
  102. self.announce('using computed proto_root_path: ' + self.proto_root_path, level=2)
  103. if not self.source_dir.startswith(self.proto_root_path):
  104. raise DistutilsOptionError('source_dir ' + self.source_dir +
  105. ' is not under proto_root_path ' + self.proto_root_path)
  106. if self.proto_files is None:
  107. files = glob.glob(os.path.join(self.source_dir, '*.proto'))
  108. if self.recurse:
  109. files.extend(glob.glob(os.path.join(self.source_dir, '**', '*.proto')))
  110. self.proto_files = [f.partition(self.proto_root_path + os.path.sep)[-1] for f in files]
  111. if not self.proto_files:
  112. raise DistutilsOptionError('no .proto files were found under ' + self.source_dir)
  113. self.ensure_string_list('proto_files')
  114. if self.protoc is None:
  115. self.protoc = os.getenv('PROTOC')
  116. if self.protoc is None:
  117. self.protoc = spawn.find_executable('protoc')
  118. def run(self):
  119. # All proto file paths were adjusted in finalize_options to be relative
  120. # to self.proto_root_path.
  121. proto_paths = ['--proto_path=' + self.proto_root_path]
  122. proto_paths.extend(['--proto_path=' + x for x in self.extra_proto_paths])
  123. # Run protoc. It was already resolved, so don't try to resolve
  124. # through PATH.
  125. spawn.spawn(
  126. [self.protoc,
  127. '--python_out=' + self.output_dir,
  128. ] + proto_paths + self.proto_files,
  129. search_path=0)