Quickfix "Wrap with double quotes" properly handles single and double quotes inside JSON string

This commit is contained in:
Mikhail Golubev
2015-04-14 18:47:52 +03:00
parent 6099531802
commit 1c046432d4
2 changed files with 30 additions and 2 deletions
@@ -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) {