imports-sorted

Since 0.9.0 · fixed by --fix · In the rulesets: Strict at error, All at error

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.

Turn the rule off if you group the imports in another way, for example the imports of the file’s own package first.

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

--fix 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.

Turn it off or change its severity

In apigenie.yaml, off turns the rule off and warning or error sets its severity; a rule with options takes the severity and the options as a pair, [warning, options]. lint.protobuf has the details.

commands:
  lint:
    protobuf:
      rules:
        imports-sorted: off

Related rules

Last updated on View as Markdown
Was this helpful?