mirror of
https://gitflic.ru/project/openide/openide.git
synced 2026-09-27 10:03:11 +07:00
Quickfix "Wrap with double quotes" properly handles single and double quotes inside JSON string
This commit is contained in:
@@ -139,15 +139,42 @@ public class JsonStandardComplianceInspection extends LocalInspectionTool {
|
||||
@Override
|
||||
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
|
||||
final PsiElement element = descriptor.getPsiElement();
|
||||
final String rawText = element.getText();
|
||||
if (element instanceof JsonLiteral || element instanceof JsonReferenceExpression) {
|
||||
final String content = JsonPsiUtil.stripQuotes(element.getText());
|
||||
String content = JsonPsiUtil.stripQuotes(rawText);
|
||||
if (element instanceof JsonStringLiteral && rawText.startsWith("'")) {
|
||||
content = escapeSingleQuotedStringContent(content);
|
||||
}
|
||||
// TODO: find out better way to replace element and skip reformatting step afterwards
|
||||
final ASTNode replacement = new JsonElementGenerator(project).createValue("\"" + content + "\"").getNode();
|
||||
element.getParent().getNode().replaceChild(element.getNode(), replacement);
|
||||
}
|
||||
else if (element != null) {
|
||||
LOG.error("Quick fix was applied to unexpected element", element.getText(), element.getParent().getText());
|
||||
LOG.error("Quick fix was applied to unexpected element", rawText, element.getParent().getText());
|
||||
}
|
||||
}
|
||||
|
||||
@NotNull
|
||||
private static String escapeSingleQuotedStringContent(@NotNull String content) {
|
||||
final StringBuilder result = new StringBuilder();
|
||||
boolean nextCharEscaped = false;
|
||||
for (int i = 0; i < content.length(); i++) {
|
||||
final char c = content.charAt(i);
|
||||
if ((nextCharEscaped && c != '\'') || (!nextCharEscaped && c == '"')) {
|
||||
result.append('\\');
|
||||
}
|
||||
if (c != '\\' || nextCharEscaped) {
|
||||
result.append(c);
|
||||
nextCharEscaped = false;
|
||||
}
|
||||
else {
|
||||
nextCharEscaped = true;
|
||||
}
|
||||
}
|
||||
if (nextCharEscaped) {
|
||||
result.append('\\');
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,6 +30,7 @@ public class JsonQuickFixTest extends JsonTestCase {
|
||||
checkWrapInDoubleQuotes("'foo\\\"", "\"foo\\\"\"");
|
||||
checkWrapInDoubleQuotes("{\"foo\": b<caret>ar}", "{\"foo\": \"bar\"}");
|
||||
checkWrapInDoubleQuotes("{\"foo\": 'b<caret>ar'}", "{\"foo\": \"bar\"}");
|
||||
checkWrapInDoubleQuotes("'foo\\n\\'\"\\\\\\\"bar", "\"foo\\n'\\\"\\\\\\\"bar\"");
|
||||
}
|
||||
|
||||
private void checkWrapInDoubleQuotes(@NotNull String before, @NotNull String after) {
|
||||
|
||||
Reference in New Issue
Block a user