codekingpro/portable-devtools
114k
1# Copyright 2019 Google LLC2#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 at6#7# https://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# 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 and13# limitations under the License.14 15import enum16 17from google.protobuf import descriptor_pb218 19from proto import _file_info20from proto import _package_info21from proto.marshal.rules.enums import EnumRule22 23 24class ProtoEnumMeta(enum.EnumMeta):25 """A metaclass for building and registering protobuf enums."""26 27 def __new__(mcls, name, bases, attrs):28 # Do not do any special behavior for `proto.Enum` itself.29 if bases[0] == enum.IntEnum:30 return super().__new__(mcls, name, bases, attrs)31 32 # Get the essential information about the proto package, and where33 # this component belongs within the file.34 package, marshal = _package_info.compile(name, attrs)35 36 # Determine the local path of this proto component within the file.37 local_path = tuple(attrs.get("__qualname__", name).split("."))38 39 # Sanity check: We get the wrong full name if a class is declared40 # inside a function local scope; correct this.41 if "<locals>" in local_path:42 ix = local_path.index("<locals>")43 local_path = local_path[: ix - 1] + local_path[ix + 1 :]44 45 # Determine the full name in protocol buffers.46 full_name = ".".join((package,) + local_path).lstrip(".")47 filename = _file_info._FileInfo.proto_file_name(48 attrs.get("__module__", name.lower())49 )50 51 # Retrieve any enum options.52 # We expect something that looks like an EnumOptions message,53 # either an actual instance or a dict-like representation.54 pb_options = "_pb_options"55 opts = attrs.pop(pb_options, {})56 # This is the only portable way to remove the _pb_options name57 # from the enum attrs.58 # In 3.7 onwards, we can define an _ignore_ attribute and do some59 # mucking around with that.60 if pb_options in attrs._member_names:61 if isinstance(attrs._member_names, list):62 idx = attrs._member_names.index(pb_options)63 attrs._member_names.pop(idx)64 else: # Python 3.11.0b365 del attrs._member_names[pb_options]66 67 # Make the descriptor.68 enum_desc = descriptor_pb2.EnumDescriptorProto(69 name=name,70 # Note: the superclass ctor removes the variants, so get them now.71 # Note: proto3 requires that the first variant value be zero.72 value=sorted(73 (74 descriptor_pb2.EnumValueDescriptorProto(name=name, number=number)75 # Minor hack to get all the enum variants out.76 for name, number in attrs.items()77 if isinstance(number, int)78 ),79 key=lambda v: v.number,80 ),81 options=opts,82 )83 84 file_info = _file_info._FileInfo.maybe_add_descriptor(filename, package)85 if len(local_path) == 1:86 file_info.descriptor.enum_type.add().MergeFrom(enum_desc)87 else:88 file_info.nested_enum[local_path] = enum_desc89 90 # Run the superclass constructor.91 cls = super().__new__(mcls, name, bases, attrs)92 93 # We can't just add a "_meta" element to attrs because the Enum94 # machinery doesn't know what to do with a non-int value.95 # The pb is set later, in generate_file_pb96 cls._meta = _EnumInfo(full_name=full_name, pb=None)97 98 file_info.enums[full_name] = cls99 100 # Register the enum with the marshal.101 marshal.register(cls, EnumRule(cls))102 103 # Generate the descriptor for the file if it is ready.104 if file_info.ready(new_class=cls):105 file_info.generate_file_pb(new_class=cls, fallback_salt=full_name)106 107 # Done; return the class.108 return cls109 110 111class Enum(enum.IntEnum, metaclass=ProtoEnumMeta):112 """A enum object that also builds a protobuf enum descriptor."""113 114 def _comparable(self, other):115 # Avoid 'isinstance' to prevent other IntEnums from matching116 return type(other) in (type(self), int)117 118 def __hash__(self):119 return hash(self.value)120 121 def __eq__(self, other):122 if not self._comparable(other):123 return NotImplemented124 125 return self.value == int(other)126 127 def __ne__(self, other):128 if not self._comparable(other):129 return NotImplemented130 131 return self.value != int(other)132 133 def __lt__(self, other):134 if not self._comparable(other):135 return NotImplemented136 137 return self.value < int(other)138 139 def __le__(self, other):140 if not self._comparable(other):141 return NotImplemented142 143 return self.value <= int(other)144 145 def __ge__(self, other):146 if not self._comparable(other):147 return NotImplemented148 149 return self.value >= int(other)150 151 def __gt__(self, other):152 if not self._comparable(other):153 return NotImplemented154 155 return self.value > int(other)156 157 158class _EnumInfo:159 def __init__(self, *, full_name: str, pb):160 self.full_name = full_name161 self.pb = pb162 