rewrite icon indicating copy to clipboard operation
rewrite copied to clipboard

Managing imports post code trasformation.

Open amishra-u opened this issue 8 months ago • 1 comments

What problem are you trying to solve?

Currently, recipe authors must manually invoke AddImport or RemoveImport visitors based on the specific code transformations they apply. This process is verbose, especially since import changes can be inferred from the resulting type or member references in the transformed code.

Moreover, AddImport may add ambiguous imports, and there's no easy way fix or prevent in all cases.

Describe the solution you'd like

Introduce a FixImport visitor that can be invoked after the main code transformation. This visitor would automatically:

  1. Add any required imports,
  2. Remove unused imports,
  3. Convert references to fully qualified names when an import would result in ambiguity.

Optionally, the FixImport visitor could accept an import layout configuration to maintain consistent formatting.

Before

{
   someTransformation()
   maybeAddImport("foo")
   maybeAddImport("bar")
   maybeRemoveImport("baz")
}

After

{
   someTransformation()
   doAfterVisit(new FixImport(/*optional import layout*/))
}

We can also create recipe on top of FixImport Visitor which anyone can add to declarative recipe to fix the erroneous imports caused by other recipes.

Are you interested in contributing this feature to OpenRewrite?

Yes

amishra-u avatar May 15 '25 18:05 amishra-u

Thanks for the suggestion and offer to help @amishra-u ! It's indeed a common sight to have to wrangle explicit imports even when using JavaTemplate to make changes. I suppose we could indeed deduce which types where dropped by diffing the replaced element tree, but I wonder if we're able to do so efficiently enough to forgo the explicit import handling.

We'd also have to account for any missing types, which unfortunately haven't been completely phased out despite your help to close the gap when related to Lombok. These are a particular concern when it comes to removing imports, as we still see missing imports when frameworks like Mockito are involved.

Not quite sure if we'd be able to cover all those cases before fully switching over, and it's a bit of a high bar for us to have two ways to do things. Any thoughts here @knutwannheden ?

timtebeek avatar May 17 '25 22:05 timtebeek