diff --git a/exe/protoc-gen-proto-plugin-demo b/exe/protoc-gen-proto-plugin-demo index 3469612..0c46365 100755 --- a/exe/protoc-gen-proto-plugin-demo +++ b/exe/protoc-gen-proto-plugin-demo @@ -5,12 +5,12 @@ require "proto_plugin" class Demo < ProtoPlugin::Base def run - request.file_to_generate.each do |f| - name = File.basename(f, ".proto") + files_to_generate.each do |f| + name = File.basename(f.name, ".proto") add_file(path: "#{name}.txt", content: <<~TXT) Parameters: #{parameters} - This file was generated from #{name}.proto! + This file was generated from #{f.name}! TXT end end diff --git a/lib/proto_plugin/base.rb b/lib/proto_plugin/base.rb index 50f93ee..c2c5adf 100644 --- a/lib/proto_plugin/base.rb +++ b/lib/proto_plugin/base.rb @@ -74,6 +74,34 @@ def parameters end end + # Returns an array of `Google::Protobuf::FileDescriptorProto` representing the files that + # were passed to `protoc` to be generated. + # + # @example `protoc --myplugin_out=. input_one.proto input_two.proto` + # [ + # , + # + # ] + # + # @return [Array] + def files_to_generate + @files_to_generate ||= request.file_to_generate.filter_map do |filename| + lookup_file(name: filename) + end + end + + # Finds a `Google::Protobuf::FileDescriptorProto` with the given `name` attribute. + # + # @return [Google::Protobuf::FileDescriptorProto] + # @return [nil] if the file was not found + def lookup_file(name:) + @index_by_filename ||= @request.proto_file.each_with_object({}) do |fd, hash| + hash[fd.name] = fd + end + + @index_by_filename[name] + end + # Returns the list of supported `CodeGeneratorResponse::Feature` values by the plugin. The returned # values are bitwise or-ed together and set on `response`. # diff --git a/test/proto_plugin/base_test.rb b/test/proto_plugin/base_test.rb index 3c43fe9..bdc4b0e 100644 --- a/test/proto_plugin/base_test.rb +++ b/test/proto_plugin/base_test.rb @@ -35,6 +35,19 @@ def run assert_equal("Hello World, Again!", @plugin.response.file.last.content) end + test "files_to_generate" do + files = @plugin.files_to_generate + + assert_equal(1, files.count) + assert_instance_of(Google::Protobuf::FileDescriptorProto, files.first) + assert_equal("test/fixtures/simple/simple.proto", files.first.name) + end + + test "lookup_file" do + refute_nil(@plugin.lookup_file(name: "test/fixtures/simple/simple.proto")) + assert_nil(@plugin.lookup_file(name: "test/fixtures/simple/missing.proto")) + end + test "parameters" do plugin = TestPlugin.new(request: Google::Protobuf::Compiler::CodeGeneratorRequest.new( parameter: "foo=bar,bare",