-
-
Notifications
You must be signed in to change notification settings - Fork 755
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add StringShouldBeRawString.kt rule #5705
Merged
Merged
Changes from 2 commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
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
160 changes: 160 additions & 0 deletions
160
...-style/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/style/StringShouldBeRawString.kt
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,160 @@ | ||
package io.gitlab.arturbosch.detekt.rules.style | ||
|
||
import io.gitlab.arturbosch.detekt.api.CodeSmell | ||
import io.gitlab.arturbosch.detekt.api.Config | ||
import io.gitlab.arturbosch.detekt.api.Debt | ||
import io.gitlab.arturbosch.detekt.api.Entity | ||
import io.gitlab.arturbosch.detekt.api.Issue | ||
import io.gitlab.arturbosch.detekt.api.Rule | ||
import io.gitlab.arturbosch.detekt.api.Severity | ||
import io.gitlab.arturbosch.detekt.api.config | ||
import io.gitlab.arturbosch.detekt.api.internal.Configuration | ||
import org.jetbrains.kotlin.com.intellij.psi.PsiElement | ||
import org.jetbrains.kotlin.psi.KtBinaryExpression | ||
import org.jetbrains.kotlin.psi.KtElement | ||
import org.jetbrains.kotlin.psi.KtExpression | ||
import org.jetbrains.kotlin.psi.KtParenthesizedExpression | ||
import org.jetbrains.kotlin.psi.KtStringTemplateExpression | ||
import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypesAndPredicate | ||
import org.jetbrains.kotlin.psi2ir.deparenthesize | ||
|
||
/** | ||
* This rule reports when the string can be converted to Kotlin raw string. | ||
* Usage of a raw string is preferred as that avoids the need for escaping strings escape characters like \n, \t, ". | ||
* Raw string also allows us to represent multiline string without the need of \n. | ||
* Also, see [Kotlin coding convention](https://kotlinlang.org/docs/coding-conventions.html#strings) for | ||
* recommendation on using multiline strings | ||
* | ||
* <noncompliant> | ||
* val windowJson = "{\n" + | ||
* " \"window\": {\n" + | ||
* " \"title\": \"Sample Quantum With AI and ML Widget\",\n" + | ||
* " \"name\": \"main_window\",\n" + | ||
* " \"width\": 500,\n" + | ||
* " \"height\": 500\n" + | ||
* " }\n" + | ||
* "}" | ||
* | ||
* val patRegex = "/^(\\/[^\\/]+){0,2}\\/?\$/gm\n" | ||
* </noncompliant> | ||
* | ||
* <compliant> | ||
* val windowJson = """ | ||
* { | ||
* "window": { | ||
* "title": "Sample Quantum With AI and ML Widget", | ||
* "name": "main_window", | ||
* "width": 500, | ||
* "height": 500 | ||
* } | ||
* } | ||
* """.trimMargin() | ||
* | ||
* val patRegex = """/^(\/[^\/]+){0,2}\/?$/gm""" | ||
* </compliant> | ||
*/ | ||
class StringShouldBeRawString(config: Config) : Rule(config) { | ||
override val issue = Issue( | ||
javaClass.simpleName, | ||
Severity.Style, | ||
"The string can be converted to raw string.", | ||
Debt.FIVE_MINS, | ||
) | ||
|
||
@Configuration("maximum escape characters allowed") | ||
private val maxEscapedCharacterCount by config(2) | ||
|
||
@Configuration("list of characters to ignore") | ||
private val ignoredCharacters by config(emptyList<String>()) | ||
|
||
private val KtElement.leftMostElementOfLeftSubtree: KtElement | ||
get() { | ||
val leftChild = (this as? KtBinaryExpression)?.left?.deparenthesize() ?: return this | ||
return leftChild.leftMostElementOfLeftSubtree | ||
} | ||
|
||
private val KtElement.rightMostElementOfRightSubtree: KtElement | ||
get() { | ||
val leftChild = (this as? KtBinaryExpression)?.right?.deparenthesize() ?: return this | ||
return leftChild.rightMostElementOfRightSubtree | ||
} | ||
|
||
override fun visitStringTemplateExpression(expression: KtStringTemplateExpression) { | ||
super.visitStringTemplateExpression(expression) | ||
if (maxEscapedCharacterCount == Int.MAX_VALUE) { | ||
return | ||
} | ||
val maxEscapedCharacterCount = this.maxEscapedCharacterCount.coerceAtLeast(0) | ||
val expressionParent = expression.getParentExpressionAfterParenthesis() | ||
val rootElement = expression.getRootExpression() | ||
if ( | ||
expressionParent !is KtBinaryExpression || | ||
(rootElement != null && expression.isPivotElementInTheTree(rootElement)) | ||
) { | ||
val shouldReport = | ||
rootElement.getStringSequenceExcludingRawString().flatMap { stringTemplateExpressionText -> | ||
REGEX_FOR_ESCAPE_CHARS.findAll(stringTemplateExpressionText).filter { | ||
it.value !in ignoredCharacters | ||
} | ||
}.take(maxEscapedCharacterCount + 1).toList().size > maxEscapedCharacterCount | ||
BraisGabin marked this conversation as resolved.
Show resolved
Hide resolved
|
||
if (shouldReport) { | ||
report( | ||
CodeSmell( | ||
issue, | ||
Entity.from(rootElement ?: expression), | ||
"String with escape characters should be converted to raw string", | ||
) | ||
) | ||
} | ||
} | ||
} | ||
|
||
private fun KtStringTemplateExpression.isPivotElementInTheTree( | ||
rootElement: KtElement, | ||
): Boolean { | ||
val leftMostElementOfLeftSubtree = rootElement.leftMostElementOfLeftSubtree | ||
return this == if (leftMostElementOfLeftSubtree is KtStringTemplateExpression) { | ||
leftMostElementOfLeftSubtree | ||
} else { | ||
rootElement.rightMostElementOfRightSubtree | ||
} | ||
} | ||
|
||
private fun KtElement?.getStringSequenceExcludingRawString(): Sequence<String> { | ||
atulgpt marked this conversation as resolved.
Show resolved
Hide resolved
|
||
this ?: return sequence { yield("") } | ||
|
||
fun KtElement?.getStringSequence(): Sequence<KtStringTemplateExpression> = sequence { | ||
BraisGabin marked this conversation as resolved.
Show resolved
Hide resolved
|
||
if (this@getStringSequence is KtStringTemplateExpression) { | ||
yield(this@getStringSequence) | ||
} else if (this@getStringSequence is KtBinaryExpression) { | ||
yieldAll(left?.deparenthesize().getStringSequence()) | ||
yieldAll(right?.deparenthesize().getStringSequence()) | ||
} | ||
} | ||
|
||
return this.getStringSequence().filter { | ||
(it.text.startsWith("\"\"\"") && it.text.endsWith("\"\"\"")).not() | ||
}.map { | ||
it.text | ||
} | ||
} | ||
|
||
private fun KtExpression.getParentExpressionAfterParenthesis(): PsiElement? = | ||
|
||
this.getParentOfTypesAndPredicate(true, PsiElement::class.java) { it !is KtParenthesizedExpression } | ||
|
||
private fun KtElement.getRootExpression(): KtElement? { | ||
return this.getParentOfTypesAndPredicate( | ||
false, | ||
KtBinaryExpression::class.java, | ||
KtParenthesizedExpression::class.java, | ||
KtStringTemplateExpression::class.java, | ||
) { | ||
val parent = (it as KtExpression).parent | ||
parent !is KtBinaryExpression && parent !is KtParenthesizedExpression | ||
}?.deparenthesize() | ||
} | ||
|
||
companion object { | ||
private val REGEX_FOR_ESCAPE_CHARS = """\\[t"\\n]""".toRegex() | ||
} | ||
} |
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
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If the user doesn't want this rule s/he should disable it. We don't need to have two different ways to disable it.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sure. But currently if we set Int.MAX_VALUE in the
detekt.yml
the working of rule breaks. BTW @BraisGabin is there any sanitisation on user input throughdetekt.yml
?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Int.MAX_VALUE doesn't seems like a sane value. We shouldn't care about that. If they would like the max value of a long it wouldn't work either 🤷.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
And there is little sanitation on that regard as far as I know.