StyraInc / regal

Regal is a linter and language server for Rego, bringing your policy development experience to the next level!
https://docs.styra.com/regal
Apache License 2.0
251 stars 34 forks source link

Rule: `messy-imports` #781

Open anderseknert opened 3 months ago

anderseknert commented 3 months ago

I think it was @johanfylling who suggested that we should have a style category rule to enforce ordering of imports, as well as grouping based on the "base path" in the imports. Something along the lines of:

Avoid

package policy

import data.alpha.omega
import rego.v1
import data.beta.b
import data.alpha.beta
import data.beta.a

Prefer

package policy

import rego.v1

import data.alpha.beta
import data.alpha.omega

import data.beta.a
import data.beta.b

Logic is fairly simple: imports of language "directives" like rego.v1 should always come first. After that follows alphabetically ordered imports, where the "base" attribute, like "alpha" in "data.alpha" is used for grouping. This is 100% compatible with opa fmt, and if implemented, we should also ensure that we implement this in regal fix so that this convention can be applied automatically to a project.

anderseknert commented 3 months ago

One thing that I hadn't considered is comments. While it's hard to imagine scenarios where commenting imports adds much of value, and don't think it's common, we'd still need to deal with it I guess. And we'll need to do it in a way that's compatible with the formatter, which currently always separates a comment from the line above with an extra newline. Presence of comments will also make it much harder to rewrite the imports using regal fix...

We could either spend 90% of the effort here catering to that 1% of policies, or we could just bail out when we find comments somewhere between the first import and the last. As long as we document that behavior, I think that's good enough for a first implementation.