Hello Sonar Team !
context
I’m trying to implement a check to catch this issue :
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) //Noncompliant {{You are keeping the screen turned on, this will drain the battery very fast. Only use this feature if strictly necessary}}
I have mocked the appropriate packages :
- android.app.Activity
- android.view.Window & android.view.WindowManager
My check is as follow
@Rule(key = "EC505")
class KeepScreenOnCheck : CallAbstractCheck() {
override val functionsToVisit = listOf(
FunMatcher(qualifier = "android.view.Window") {
withNames(
"addFlags",
)
},
)
override fun visitFunctionCall(
callExpression: KtCallExpression,
resolvedCall: ResolvedCall<*>,
kotlinFileContext: KotlinFileContext
) {
kotlinFileContext.reportIssue(callExpression.calleeExpression!!, ERROR_MESSAGE)
}
}
and my sample
class KeepScreenOnCheckSample {
fun foo(window: Window) {
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) //Noncompliant {{You are keeping the screen turned on, this will drain the battery very fast. Only use this feature if strictly necessary}}
}
}
test output
org.junit.ComparisonFailure: ERROR: Expect some issues, but there's none. In file (KeepScreenOnCheckSample.kt:8)
[----------------------------------------------------------------------]
[ '-' means expected but not raised, '+' means raised but not expected ]
<KeepScreenOnCheckSample.kt>
- 008: Noncompliant {{You are keeping the screen turned on, this will drain the battery very fast. Only use this feature if strictly necessary}}
- 008: window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
[----------------------------------------------------------------------]
; expected:<[<KeepScreenOnCheckSample.kt>
008: Noncompliant {{You are keeping the screen turned on, this will drain the battery very fast. Only use this feature if strictly necessary}}
008: window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)]
> but was:<[ERROR: Expect some issues, but there's none.
<KeepScreenOnCheckSample.kt>]
For full code see this PR : EC505 - Keeping the screen turned on by 47tibo · Pull Request #8 · green-code-initiative/ecoCode-kotlin-android · GitHub
All advices are welcome