Linter rulesProtobufimport-used

import-used

Since 0.9.0 · fixed by --fix

This rule checks whether every file imported by a Protobuf file is actually used.

Rule Details

Unused imports add dependencies that are not needed: the generated code imports packages it does not use, which some languages reject, and the build has to fetch and compile more files.

The import-used rule collects the names a file refers to: the types of fields and map values, the request and response types of RPCs, the extended types, the custom options used in option names ((acme.options.v1.sensitive)), and the extensions and Any types in option values. It resolves these names like protoc does, among the declarations of the file, of the files it imports and of the files those import publicly. An import is used when it declares one of these names, or when one of the files it imports publicly, directly or indirectly, does.

For every import that is not used, the rule reports Import '<import>' is unused.

The rule does not report:

  • public imports, which are there for the importers of the file rather than for the file itself;
  • imports that are not found (see import-resolved), and imports whose file, or one of the files it imports publicly, cannot be read, for example because of syntax errors, or because it is a proto2 or editions file (google/protobuf/descriptor.proto is known built in, though);
  • any import of a file in which some name cannot be resolved: the name may come from a file the linter cannot read, so it cannot tell which imports are unused.

Configuration

This rule has no options.

Examples

Good.

syntax = "proto3";

package acme.pets.v1;

import "google/protobuf/timestamp.proto";

message Pet {
  string name = 1;
  google.protobuf.Timestamp born_at = 2;
}

Bad. The linter reports Import 'google/protobuf/duration.proto' is unused.

syntax = "proto3";

package acme.pets.v1;

import "google/protobuf/duration.proto";
import "google/protobuf/timestamp.proto";

message Pet {
  string name = 1;
  google.protobuf.Timestamp born_at = 2;
}

Automatic fixes

When invoked with --fix, this rule removes the unused import statements.

When Not to Use It

You may disable this rule if some imports are needed only for their side effects in the generated code, for example to register extensions. To keep a single import, add an // apigenie-lint-disable import-used comment to it.

Compatibility

This rule is compatible with proto3 files. proto2 and editions files are rejected by the reader and are not linted. The rule reads the imported files, and the files they import publicly, found in the import paths and in the directories above the importing file.

Related rules