1# Copyright 2018 Google LLC
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# https://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 sys
16
17from proto.marshal import Marshal
18
19
20def compile(name, attrs):
21 """Return the package and marshal to use.
22
23 Args:
24 name (str): The name of the new class, as sent to ``type.__new__``.
25 attrs (Mapping[str, Any]): The attrs for a new class, as sent
26 to ``type.__new__``
27
28 Returns:
29 Tuple[str, ~.Marshal]:
30 - The proto package, if any (empty string otherwise).
31 - The marshal object to use.
32 """
33 # Pull a reference to the module where this class is being
34 # declared.
35 module = sys.modules.get(attrs.get("__module__"))
36 module_name = module.__name__ if hasattr(module, __name__) else ""
37 proto_module = getattr(module, "__protobuf__", object())
38
39 # A package should be present; get the marshal from there.
40 # TODO: Revert to empty string as a package value after protobuf fix.
41 # When package is empty, upb based protobuf fails with an
42 # "TypeError: Couldn't build proto file into descriptor pool: invalid name: empty part ()' means"
43 # during an attempt to add to descriptor pool.
44 package = getattr(
45 proto_module, "package", module_name if module_name else "_default_package"
46 )
47 marshal = Marshal(name=getattr(proto_module, "marshal", package))
48
49 # Done; return the data.
50 return (package, marshal)