Introduce StringFormat Refaster rule

XXX: Requires dropping JDK 11 support, or a means of filtering by target
language level.
This commit is contained in:
Stephan Schroevers
2024-02-11 21:23:06 +01:00
parent 7daa39a0b5
commit 51dc075f1c
3 changed files with 29 additions and 0 deletions

View File

@@ -9,10 +9,12 @@ import com.google.common.base.Joiner;
import com.google.common.base.Strings; import com.google.common.base.Strings;
import com.google.common.base.Utf8; import com.google.common.base.Utf8;
import com.google.common.collect.Streams; import com.google.common.collect.Streams;
import com.google.errorprone.annotations.FormatMethod;
import com.google.errorprone.refaster.Refaster; import com.google.errorprone.refaster.Refaster;
import com.google.errorprone.refaster.annotation.AfterTemplate; import com.google.errorprone.refaster.annotation.AfterTemplate;
import com.google.errorprone.refaster.annotation.AlsoNegation; import com.google.errorprone.refaster.annotation.AlsoNegation;
import com.google.errorprone.refaster.annotation.BeforeTemplate; import com.google.errorprone.refaster.annotation.BeforeTemplate;
import com.google.errorprone.refaster.annotation.Repeated;
import com.google.errorprone.refaster.annotation.UseImportPolicy; import com.google.errorprone.refaster.annotation.UseImportPolicy;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
@@ -348,4 +350,23 @@ final class StringRules {
return string.startsWith(prefix, fromIndex); return string.startsWith(prefix, fromIndex);
} }
} }
/**
* Prefer {@link String#formatted(Object...)} over {@link String#format(String, Object...)}, as
* the former works more nicely with text blocks, while the latter does not appear advantageous in
* any circumstance (assuming one targets JDK 15+).
*/
static final class StringFormatted {
@BeforeTemplate
@FormatMethod
String before(String format, @Repeated Object args) {
return String.format(format, args);
}
@AfterTemplate
@FormatMethod
String after(String format, @Repeated Object args) {
return format.formatted(args);
}
}
} }

View File

@@ -124,4 +124,8 @@ final class StringRulesTest implements RefasterRuleCollectionTestCase {
boolean testStringStartsWith() { boolean testStringStartsWith() {
return "foo".substring(1).startsWith("bar"); return "foo".substring(1).startsWith("bar");
} }
String testStringFormatted() {
return String.format("%s%s", "foo", "bar");
}
} }

View File

@@ -124,4 +124,8 @@ final class StringRulesTest implements RefasterRuleCollectionTestCase {
boolean testStringStartsWith() { boolean testStringStartsWith() {
return "foo".startsWith("bar", 1); return "foo".startsWith("bar", 1);
} }
String testStringFormatted() {
return "%s%s".formatted("foo", "bar");
}
} }