KT-5717 "Replace 'when' with 'if'" loses a comment

#KT-5717 Fixed
This commit is contained in:
Valentin Kipyatkov
2016-02-11 21:36:45 +03:00
parent 0809be59df
commit 0ed8eb0512
4 changed files with 27 additions and 2 deletions
@@ -21,7 +21,10 @@ import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.idea.intentions.SelfTargetingRangeIntention
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.combineWhenConditions
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.idea.util.CommentSaver
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.KtWhenExpression
import org.jetbrains.kotlin.psi.buildExpression
class WhenToIfIntention : SelfTargetingRangeIntention<KtWhenExpression>(KtWhenExpression::class.java, "Replace 'when' with 'if'"), LowPriorityAction {
override fun applicabilityRange(element: KtWhenExpression): TextRange? {
@@ -33,6 +36,8 @@ class WhenToIfIntention : SelfTargetingRangeIntention<KtWhenExpression>(KtWhenEx
}
override fun applyTo(element: KtWhenExpression, editor: Editor?) {
val commentSaver = CommentSaver(element)
val factory = KtPsiFactory(element)
val ifExpression = factory.buildExpression {
val entries = element.entries
@@ -57,6 +62,7 @@ class WhenToIfIntention : SelfTargetingRangeIntention<KtWhenExpression>(KtWhenEx
}
}
element.replace(ifExpression)
val result = element.replace(ifExpression)
commentSaver.restore(result)
}
}
@@ -0,0 +1,8 @@
fun foo(b: Boolean) {
<caret>when {
// comment 1
b -> 1 // comment 2
else -> 2
}
}
@@ -0,0 +1,5 @@
fun foo(b: Boolean) {
if (// comment 1
b) 1 // comment 2
else 2
}
@@ -1564,6 +1564,12 @@ public class IntentionTestGenerated extends AbstractIntentionTest {
KotlinTestUtils.assertAllTestsPresentByMetadata(this.getClass(), new File("idea/testData/intentions/branched/ifWhen/whenToIf"), Pattern.compile("^([\\w\\-_]+)\\.kt$"), true);
}
@TestMetadata("comment.kt")
public void testComment() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/intentions/branched/ifWhen/whenToIf/comment.kt");
doTest(fileName);
}
@TestMetadata("whenWithDotQualifiedExpression.kt")
public void testWhenWithDotQualifiedExpression() throws Exception {
String fileName = KotlinTestUtils.navigationMetadata("idea/testData/intentions/branched/ifWhen/whenToIf/whenWithDotQualifiedExpression.kt");