Skip to content

Managing imports post code transformation #5435

Description

@amishra-u

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    Status
    Backlog

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions