# imports-sorted

Source: https://api-genie.dev/docs/linter/protobuf/rules/imports-sorted

A rule of the Protobuf linter, which reads proto3 files; the reader rejects proto2 and editions files. 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**.

```proto
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'`.

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