[java-inspections] IDEA-360134 Support %n in format string

GitOrigin-RevId: c7d3b60eec4a72ded2132a3ab24e035baf2c1241
This commit is contained in:
Mikhail Pyltsin
2024-10-07 13:20:17 +02:00
committed by intellij-monorepo-bot
parent 77ec6df673
commit 81fe531f88
4 changed files with 54 additions and 1 deletions

View File

@@ -602,7 +602,30 @@ public final class StringConcatenationArgumentToLogCallInspection extends BaseIn
if (range == null) return null;
result.put(range, index);
}
int start = 0;
while ((start = formattedString.indexOf("%n", start)) != -1) {
int escaped = 0;
while (true) {
if (start - escaped == 0) {
break;
}
if(formattedString.charAt(start - escaped - 1) == '%') {
escaped++;
continue;
}
break;
}
if (escaped % 2 == 1) {
start++;
continue;
}
TextRange range = ExpressionUtils.findStringLiteralRange(expression, start, start + 2);
if (range == null) {
return null;
}
text = StringUtil.replaceSubstring(text, range, "\\n");
start++;
}
return new StringFormatArgumentToLogCallFix(result, text);
}

View File

@@ -0,0 +1,14 @@
import org.slf4j.*;
import java.text.MessageFormat;
class SimpleStringFormat {
Logger LOG = LoggerFactory.getLogger(SimpleStringFormat.class);
void f() {
LOG.in<caret>fo("foo \n{}", "bar");
LOG.info("foo %%n{}", "bar");
LOG.info("foo %%\n{}", "bar");
}
}

View File

@@ -0,0 +1,14 @@
import org.slf4j.*;
import java.text.MessageFormat;
class SimpleStringFormat {
Logger LOG = LoggerFactory.getLogger(SimpleStringFormat.class);
void f() {
LOG.in<caret>fo(String.format("foo %n%s", "bar"));
LOG.info(String.format("foo %%n%s", "bar"));
LOG.info(String.format("foo %%%n%s", "bar"));
}
}

View File

@@ -71,6 +71,8 @@ public class StringConcatenationArgumentToLogCallFixTest extends IGQuickFixesTes
public void testPreviousArgumentStringFormat() { assertQuickfixNotAvailable(InspectionGadgetsBundle.message("string.concatenation.argument.to.log.string.format.call.quickfix")); }
public void testConcatenationStringFormat() { doTest(InspectionGadgetsBundle.message("string.concatenation.argument.to.log.string.format.call.quickfix")); }
public void testSimpleStringFormatWithException() { doTest(InspectionGadgetsBundle.message("string.concatenation.argument.to.log.string.format.call.quickfix")); }
public void testStringFormatWithNewLine() { doTest( InspectionsBundle.message("fix.all.inspection.problems.in.file",
InspectionGadgetsBundle.message("string.concatenation.argument.to.log.call.display.name"))); }
@Override