Skip to content

Commit 5c675e8

Browse files
BoykoAlextimtebeekgithub-actions[bot]
authored
"value" attr when adding another attribute (#5962)
* "value" attr when adding another attribute * Apply suggestion Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --------- Co-authored-by: Tim te Beek <timtebeek@gmail.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Tim te Beek <tim@moderne.io>
1 parent 1c3ec10 commit 5c675e8

2 files changed

Lines changed: 10 additions & 12 deletions

File tree

rewrite-java-test/src/test/java/org/openrewrite/java/AddOrUpdateAnnotationAttributeTest.java

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2335,36 +2335,29 @@ void attributeWithShallowType() {
23352335
"required",
23362336
"true",
23372337
null,
2338-
false,
2338+
true,
23392339
false)
23402340
),
23412341
java(
23422342
"""
23432343
package org.example;
23442344
public @interface Bar {
2345-
}
2346-
"""
2347-
),
2348-
java(
2349-
"""
2350-
package org.example;
2351-
public @interface Foo {
2352-
boolean required();
2345+
String value() default "";
23532346
}
23542347
"""
23552348
),
23562349
java(
23572350
"""
23582351
import org.example.Bar;
23592352
2360-
@Bar
2353+
@Bar("q")
23612354
public class A {
23622355
}
23632356
""",
23642357
"""
23652358
import org.example.Foo;
23662359
2367-
@Foo(required = true)
2360+
@Foo(required = true, value = "q")
23682361
public class A {
23692362
}
23702363
"""

rewrite-java/src/main/java/org/openrewrite/java/AddOrUpdateAnnotationAttribute.java

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,12 @@ public J.Annotation visitAnnotation(J.Annotation original, ExecutionContext ctx)
144144
// ADD the value into the argument list when there was no existing value to update and no requirements on a pre-existing old value, e.g. @Foo(name="old") to @Foo(value="new", name="old")
145145
if (oldAttributeValue == null && newAttributeValue != null && !attributeNameOrValIsAlreadyPresent(a.getArguments(), getAttributeValues())) {
146146
J.Assignment as = createAnnotationAssignment(a, attributeName(), newAttributeValue);
147-
a = a.withArguments(ListUtils.concat(as, a.getArguments()));
147+
List<Expression> args = a.getArguments();
148+
// Case for existing attribute: `@Foo("q")` -> @Foo(value = "q")
149+
if (args.size() == 1 && !(args.get(0) instanceof J.Assignment)) {
150+
args = singletonList(createAnnotationAssignment(a, "value", a.getArguments().get(0)));
151+
}
152+
a = a.withArguments(ListUtils.concat(as, args));
148153
}
149154

150155
if (original != a) {

0 commit comments

Comments
 (0)