PY-21161 Handle not-trivial format specs in printf-style formatting better

This commit is contained in:
Mikhail Golubev
2016-10-25 21:30:13 +03:00
parent 84422a7250
commit 06286a59a2
4 changed files with 13 additions and 10 deletions
@@ -46,6 +46,7 @@ import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import static com.jetbrains.python.codeInsight.intentions.ConvertFormatOperatorToMethodIntention.convertFormatSpec;
import static com.jetbrains.python.psi.PyUtil.as;
/**
@@ -221,13 +222,12 @@ public class PyConvertToFStringIntention extends PyBaseIntentionAction {
else {
final SubstitutionChunk subsChunk = (SubstitutionChunk)chunk;
final char conversionChar = subsChunk.getConversionType();
final String widthAndPrecision;
if (StringUtil.isNotEmpty(subsChunk.getWidth()) || StringUtil.isNotEmpty(subsChunk.getPrecision())) {
widthAndPrecision = StringUtil.notNullize(subsChunk.getWidth()) + "." + StringUtil.notNullize(subsChunk.getPrecision());
}
else {
widthAndPrecision = "";
String widthAndPrecision = StringUtil.notNullize(subsChunk.getWidth());
if (StringUtil.isNotEmpty(subsChunk.getPrecision())) {
widthAndPrecision += "." + subsChunk.getPrecision();
}
final String conversionFlags = subsChunk.getConversionFlags();
result.append("{");
@@ -251,10 +251,7 @@ public class PyConvertToFStringIntention extends PyBaseIntentionAction {
result.append(":");
}
if (StringUtil.isNotEmpty(conversionFlags)) {
final String conversionStr = String.valueOf(conversionChar);
result.append(ConvertFormatOperatorToMethodIntention.convertFormatSpec(conversionFlags, widthAndPrecision, conversionStr));
}
result.append(convertFormatSpec(StringUtil.notNullize(conversionFlags), widthAndPrecision, String.valueOf(conversionChar)));
if (StringUtil.isNotEmpty(widthAndPrecision)) {
result.append(widthAndPrecision);
@@ -0,0 +1 @@
'%.5d %3.5d %3d %20s %-#d' % (1, 2, 3, 'spam', 4)
@@ -0,0 +1 @@
f'{1:.5d} {2:3.5d} {3:3d} {"spam":>20} {4:<#d}'
@@ -96,6 +96,10 @@ public class PyConvertToFStringIntentionTest extends PyIntentionTestCase {
doTest();
}
public void testPercentOperatorWidthAndPrecision() {
doTest();
}
public void testExtractItemAndAttributeAccess() {
assertSameElements(PyConvertToFStringIntention.extractItemsAndAttributes("{0.foo.bar.baz}"), ".foo", ".bar", ".baz");
assertSameElements(PyConvertToFStringIntention.extractItemsAndAttributes("{0[foo][.!:][}]}"), "[foo]", "[.!:]", "[}]");