Skip to content

Remove unused imports from built descriptor #504

@devnev

Description

@devnev

I'm trying to write a protoc plugin that may remove some elements from a proto and then output a new proto file. In the process, some of the imports may become unused, but at the moment such imports are left in the output. From reading the protoreflect source, it looks like FileBuilder.FromFile is adding all imports to the explicit import list, and then FileBuilder.Build adds all those imports regardless of whether they're still referenced.

Observed behaviour

func main() {
  descs, _ := protoparse.Parser{}.ParseFiles(os.Args[1:])
  for descIdx, fileDesc := range descs {
    fileBuilder, _ := builder.FromFile(fileDesc)
    // some arbitrary code that removes elements, e.g.
    fileBuilder.RemoveMessage("InternalMessage")
    descs[descIdx], _ = fileBuilder.Build()
  }
  protoprint.Printer{}.PrintProtosToFileSystem(descs, "out")
}
syntax = "proto3";
package demo;
import "google/protobuf/empty.proto";
message InternalMessage {
  google.protobuf.Empty empty = 1;
}

The above code will produce a proto file something like

syntax = "proto3";
package demo;
import "google/protobuf/empty.proto";

Desired behaviour

Some way to have the resulting proto stripped of the unused empty.proto import.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions