_file.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. # Copyright (c) 2025-2026 Buf Technologies, Inc.
  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. from __future__ import annotations
  15. from typing import TYPE_CHECKING
  16. from protobuf._file_registry import create_file_registry
  17. if TYPE_CHECKING:
  18. from collections.abc import Mapping, Sequence
  19. from protobuf._descriptors import DescFile
  20. from protobuf._enum import Enum
  21. from protobuf._extension import Extension
  22. from protobuf._message import Message
  23. def file_desc(
  24. proto_bytes: bytes,
  25. dependencies: Sequence[DescFile],
  26. stubs: Mapping[str, type[Message | Enum] | Extension],
  27. ) -> DescFile:
  28. """Create a DescFile from a serialized FileDescriptorProto."""
  29. from protobuf.wkt._gen.descriptor_pb import FileDescriptorProto # noqa: PLC0415
  30. proto = FileDescriptorProto.from_binary(proto_bytes)
  31. reg = create_file_registry(
  32. proto,
  33. lambda path: next((dep for dep in dependencies if dep.name == path), None),
  34. stubs=stubs,
  35. )
  36. res = reg.file(proto.name)
  37. assert res is not None # noqa: S101 # We just added the file.
  38. return res