Created
March 30, 2023 15:23
-
-
Save drawers/9bdc1b471a6a96ffe346904b1ce947bf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import io.gitlab.arturbosch.detekt.api.* | |
import org.jetbrains.kotlin.psi.* | |
import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType | |
class DoubleNegativeTakeUnless(config: Config = Config.empty) : Rule(config) { | |
override val issue = Issue( | |
"DoubleNegativeTakeUnless", | |
Severity.Style, | |
"Using double negatives with `takeUnless` can make the code harder to read.", | |
Debt.FIVE_MINS | |
) | |
override fun visitCallExpression(expression: KtCallExpression) { | |
val calleeExpression = expression.calleeExpression?.text ?: return | |
if (calleeExpression == "takeUnless") { | |
val lambdaExpression = expression.lambdaArguments.firstOrNull() ?: return | |
val negations = lambdaExpression.collectDescendantsOfType<KtPrefixExpression> { | |
it.baseExpression?.let { baseExpr -> | |
baseExpr is KtSimpleNameExpression && it.operationReference.text == "!" | |
} ?: false | |
} | |
if (negations.isNotEmpty()) { | |
report( | |
CodeSmell( | |
issue, | |
Entity.from(expression), | |
"Double negative detected with `takeUnless`. " + | |
"Consider using `takeIf` and simplifying the condition." | |
) | |
) | |
} | |
} | |
super.visitCallExpression(expression) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment