Skip to content

Conversation

JohannisK
Copy link
Contributor

What's changed?

This PR fixes an issue where the template generator incorrectly modified statements when using JavaCoordinates to add statements before or after existing code, rather than replacing them.

What's your motivation?

When using JavaTemplate to add a statement before an existing method invocation (e.g., using firstStatement() coordinates), the template generator would incorrectly prefix the new statement with variable declarations like Object o =. This happened because the generator didn't distinguish between REPLACEMENT mode (where such prefixes ensure valid compilation) and addition modes (BEFORE/AFTER) where the statement should remain unmodified.

For example, when adding String newLine = "test"; before o.get();, the generator would produce the invalid statement: Object o = String newLine = "test";

Solution

  • Added the JavaCoordinates.Mode parameter to the contextFreeTemplate method signature
  • Modified template generation logic to only add variable declaration prefixes when in REPLACEMENT mode
  • Applied the fix consistently across Java, Groovy, and Kotlin template generators

@JohannisK JohannisK self-assigned this Aug 14, 2025
@JohannisK JohannisK added the bug Something isn't working label Aug 14, 2025
@github-project-automation github-project-automation bot moved this to In Progress in OpenRewrite Aug 14, 2025
Copy link
Contributor

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Some suggestions could not be made:

  • rewrite-gradle/src/main/java/org/openrewrite/gradle/marker/GradleDependencyConfiguration.java
    • lines 26-26

…entTest.java

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Copy link
Contributor

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Some suggestions could not be made:

  • rewrite-gradle/src/main/java/org/openrewrite/gradle/marker/GradleDependencyConfiguration.java
    • lines 26-26

@timtebeek timtebeek marked this pull request as draft August 19, 2025 10:43
@knutwannheden
Copy link
Contributor

As discussed with @JohannisK we want to explore a different approach, as it doesn't seem quite right to link this behavior to the mode.

@timtebeek timtebeek closed this Sep 29, 2025
@github-project-automation github-project-automation bot moved this from In Progress to Done in OpenRewrite Sep 29, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
Status: Done
Development

Successfully merging this pull request may close these issues.

3 participants