Utilities.swift 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. * Copyright 2024, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import Foundation
  17. import GRPCProtobufCodeGen
  18. import SwiftProtobuf
  19. import SwiftProtobufPluginLibrary
  20. import Testing
  21. import struct GRPCCodeGen.CodeGenerationRequest
  22. import struct GRPCCodeGen.CodeGenerator
  23. protocol UsesDescriptorSet {
  24. static var descriptorSetName: String { get }
  25. static var fileDescriptorName: String { get }
  26. static var descriptorSet: DescriptorSet { get throws }
  27. static var fileDescriptor: FileDescriptor { get throws }
  28. }
  29. extension UsesDescriptorSet {
  30. static var descriptorSet: DescriptorSet {
  31. get throws {
  32. try loadDescriptorSet(named: Self.descriptorSetName)
  33. }
  34. }
  35. static var fileDescriptor: FileDescriptor {
  36. get throws {
  37. let descriptorSet = try Self.descriptorSet
  38. if let fileDescriptor = descriptorSet.fileDescriptor(named: fileDescriptorName + ".proto") {
  39. return fileDescriptor
  40. } else {
  41. throw MissingFileDescriptor()
  42. }
  43. }
  44. }
  45. }
  46. struct MissingFileDescriptor: Error {}
  47. private func loadDescriptorSet(
  48. named name: String,
  49. withExtension extension: String = "pb"
  50. ) throws -> DescriptorSet {
  51. let maybeURL = Bundle.module.url(
  52. forResource: name,
  53. withExtension: `extension`,
  54. subdirectory: "Generated"
  55. )
  56. let url = try #require(maybeURL)
  57. let data = try #require(try Data(contentsOf: url))
  58. let descriptorSet = try Google_Protobuf_FileDescriptorSet(serializedBytes: data)
  59. return DescriptorSet(proto: descriptorSet)
  60. }
  61. func parseDescriptor(
  62. _ descriptor: FileDescriptor,
  63. extraModuleImports: [String] = [],
  64. accessLevel: CodeGenerator.Config.AccessLevel = .internal
  65. ) throws -> CodeGenerationRequest {
  66. let parser = ProtobufCodeGenParser(
  67. protoFileModuleMappings: .init(),
  68. extraModuleImports: extraModuleImports,
  69. accessLevel: accessLevel
  70. )
  71. return try parser.parse(descriptor: descriptor)
  72. }