Linter rulesProtobufimports-sorted

imports-sorted

Since 0.9.0 · fixed by --fix

This rule checks whether the import statements of a Protobuf file are sorted by path.

Rule Details

Sorted imports are easier to scan, make duplicates obvious, and keep merge conflicts small when several people add imports to the same file.

The imports-sorted rule compares the paths of the import statements in the order they appear in the file, whatever their kind (plain, public or weak). At the first import whose path sorts before the path of the preceding one, it reports:

Imports are not sorted: '<import>' should come before '<previous import>'

Only the first import out of order is reported. Paths are compared character by character (by their byte values), so the comparison is case-sensitive: all upper-case letters sort before lower-case ones.

The rule is part of the strict and all rulesets.

Configuration

This rule has no options.

Examples

Good.

syntax = "proto3";

package acme.pets.v1;

import "acme/pets/v1/owner.proto";
import "google/protobuf/timestamp.proto";

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

Bad. The linter reports Imports are not sorted: 'acme/pets/v1/owner.proto' should come before 'google/protobuf/timestamp.proto'.

syntax = "proto3";

package acme.pets.v1;

import "google/protobuf/timestamp.proto";
import "acme/pets/v1/owner.proto";

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

Automatic fixes

When invoked with --fix, this rule sorts the import statements by path, keeping the kind (public or weak) of each import. Every import statement is replaced by the one that belongs at its place, so imports separated by other statements stay at the same places in the file.

The fix is only offered when none of the import statements has a comment, neither before, after nor inside the statement, since moving the statements would separate the comments from them. Otherwise the issue is reported without a fix, and the imports must be sorted by hand.

When Not to Use It

You may disable this rule if you group the imports in another way, for example the imports of the file’s own package first.

Compatibility

This rule is compatible with proto3 files. proto2 and editions files are rejected by the reader and are not linted.

Related rules