Skip to content

Firestore adapter lifecycle lint checks #1340

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

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
package com.firebaseui.lint

import com.android.tools.lint.client.api.UElementHandler
import com.android.tools.lint.detector.api.Category.Companion.CORRECTNESS
import com.android.tools.lint.detector.api.Detector
import com.android.tools.lint.detector.api.Implementation
import com.android.tools.lint.detector.api.Issue
import com.android.tools.lint.detector.api.JavaContext
import com.android.tools.lint.detector.api.Scope
import com.android.tools.lint.detector.api.Severity.WARNING
import org.jetbrains.uast.UCallExpression
import org.jetbrains.uast.UClass
import org.jetbrains.uast.UField
import org.jetbrains.uast.visitor.AbstractUastVisitor
import java.util.EnumSet

class FirestoreRecyclerAdapterLifecycleDetector : Detector(), Detector.UastScanner {

override fun getApplicableUastTypes() = listOf(UClass::class.java)

override fun createUastHandler(context: JavaContext) = MissingLifecycleMethodsVisitor(context)

class MissingLifecycleMethodsVisitor(
private val context: JavaContext
) : UElementHandler() {
private val FIRESTORE_RECYCLER_ADAPTER_TYPE =
"FirestoreRecyclerAdapter"

override fun visitClass(node: UClass) {
val adapterReferences = node
.fields
.filter { FIRESTORE_RECYCLER_ADAPTER_TYPE == it.type.canonicalText }
.map { AdapterReference(it) }

node.accept(AdapterStartListeningMethodVisitor(adapterReferences))
node.accept(AdapterStopListeningMethodVisitor(adapterReferences))

adapterReferences.forEach {
if (it.hasCalledStart && !it.hasCalledStop) {
context.report(
ISSUE_MISSING_LISTENING_STOP_METHOD,
it.uField,
context.getLocation(it.uField),
"Have called .startListening() without .stopListening()."
)
} else if (!it.hasCalledStart) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this trigger if startListening is not called but setLifecycleOwner is called?

Copy link
Contributor Author

@pavlospt pavlospt Jun 6, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nope have not taken that into account, but I was thinking of it as well. I am not quite sure on the proper approach to solve this.

Currently setLifecycleOwner is applied on FirestoreRecyclerOptions which should be applied on FirestoreRecyclerAdapter, but there is nothing stopping the user of using both that method, as well as, the start/stopListening ones. So I am not quite sure how to prioritize those two together and chose to just add warnings based on the general usage and existence of lifecycle method invocations. That lets the user decide which warning to suppress, effectively acknowledging that it is the desired behavior and not just a method call that they forgot to invoke.

@samtstern I am open to suggestions on the matter if you have anything to suggest :D

Edit 1: I would probably turn the invocation of startListening after setLifecycleOwner has been called, into a RuntimeException so as to give a clear option on the user. Not sure if it should just be a Lint check since in the future those two method calls might conflict in an unpredictable way!

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think (as @SUPERCILEX mentioned) understanding lifecycle in a lint could be very tricky. Would you be ok with reducing this PR down to just the start/stop calls and not the lifecycle bits?

We'd also have to do the work to ship our custom lint checks, which may be kind of slow, but we don't have to do that in this PR.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure I can do that :)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@samtstern I removed setLifecyleOwner related Lint checks and code :)

context.report(
ISSUE_MISSING_LISTENING_START_METHOD,
it.uField,
context.getLocation(it.uField),
"Have not called .startListening()."
)
}
}
}
}

class AdapterStartListeningMethodVisitor(
private val adapterReferences: List<AdapterReference>
) : AbstractUastVisitor() {
private val START_LISTENING_METHOD_NAME = "startListening"

override fun visitCallExpression(node: UCallExpression): Boolean =
if (START_LISTENING_METHOD_NAME == node.methodName) {
adapterReferences
.find { it.uField.name == node.receiver?.asRenderString() }
?.let {
it.hasCalledStart = true
}
true
} else {
super.visitCallExpression(node)
}
}

class AdapterStopListeningMethodVisitor(
private val adapterReferences: List<AdapterReference>
) : AbstractUastVisitor() {
private val STOP_LISTENING_METHOD_NAME = "stopListening"

override fun visitCallExpression(node: UCallExpression): Boolean =
if (STOP_LISTENING_METHOD_NAME == node.methodName) {
adapterReferences
.find { it.uField.name == node.receiver?.asRenderString() }
?.let {
it.hasCalledStop = true
}
true
} else {
super.visitCallExpression(node)
}
}

companion object {
val ISSUE_MISSING_LISTENING_START_METHOD = Issue.create(
"FirestoreAdapterMissingStartListeningMethod",
"Checks if FirestoreAdapter has called .startListening() method.",
"If a class is using a FirestoreAdapter and does not call startListening it won't be " +
"notified on changes.",
CORRECTNESS, 10, WARNING,
Implementation(
FirestoreRecyclerAdapterLifecycleDetector::class.java,
EnumSet.of(Scope.JAVA_FILE)
)
)

val ISSUE_MISSING_LISTENING_STOP_METHOD = Issue.create(
"FirestoreAdapterMissingStopListeningMethod",
"Checks if FirestoreAdapter has called .stopListening() method.",
"If a class is using a FirestoreAdapter and has called .startListening() but missing " +
" .stopListening() might cause issues with RecyclerView data changes.",
CORRECTNESS, 10, WARNING,
Implementation(
FirestoreRecyclerAdapterLifecycleDetector::class.java,
EnumSet.of(Scope.JAVA_FILE)
)
)
}
}

data class AdapterReference(
val uField: UField,
var hasCalledStart: Boolean = false,
var hasCalledStop: Boolean = false
)
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,9 @@ import com.android.tools.lint.client.api.IssueRegistry
* Registry for custom FirebaseUI lint checks.
*/
class LintIssueRegistry : IssueRegistry() {
override val issues = listOf(NonGlobalIdDetector.NON_GLOBAL_ID)
override val issues = listOf(
NonGlobalIdDetector.NON_GLOBAL_ID,
FirestoreRecyclerAdapterLifecycleDetector.ISSUE_MISSING_LISTENING_START_METHOD,
FirestoreRecyclerAdapterLifecycleDetector.ISSUE_MISSING_LISTENING_STOP_METHOD
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package com.firebaseui.lint

import com.android.tools.lint.checks.infrastructure.TestFiles.java
import com.firebaseui.lint.FirestoreRecyclerAdapterLifecycleDetector.Companion.ISSUE_MISSING_LISTENING_START_METHOD
import com.firebaseui.lint.FirestoreRecyclerAdapterLifecycleDetector.Companion.ISSUE_MISSING_LISTENING_STOP_METHOD
import com.firebaseui.lint.LintTestHelper.configuredLint
import org.junit.Test

class FirestoreRecyclerAdapterLifecycleDetectorTest {

@Test
fun `Checks missing startListening() method call`() {
configuredLint()
.files(java("""
|public class MissingStartListeningMethodCall {
| private FirestoreRecyclerAdapter adapter;
|}
""".trimMargin()))
.issues(ISSUE_MISSING_LISTENING_START_METHOD)
.run()
.expect("""
|src/MissingStartListeningMethodCall.java:2: Warning: Have not called .startListening(). [FirestoreAdapterMissingStartListeningMethod]
| private FirestoreRecyclerAdapter adapter;
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|0 errors, 1 warnings
""".trimMargin())
}

@Test
fun `Checks missing stopListening() method call`() {
configuredLint()
.files(java("""
|public class MissingStopListeningMethodCall {
| private FirestoreRecyclerAdapter adapter;
|
| public void onStart() {
| adapter.startListening();
| }
|}
""".trimMargin()))
.issues(ISSUE_MISSING_LISTENING_STOP_METHOD)
.run()
.expect("""
|src/MissingStopListeningMethodCall.java:2: Warning: Have called .startListening() without .stopListening(). [FirestoreAdapterMissingStopListeningMethod]
| private FirestoreRecyclerAdapter adapter;
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|0 errors, 1 warnings
""".trimMargin())
}

@Test
fun `Checks no warnings when startListening & stopListening methods called`() {
configuredLint()
.files(java("""
|public class HasCalledStartStopListeningMethods {
| private FirestoreRecyclerAdapter adapter;
|
| public void onStart() {
| adapter.startListening();
| }
|
| public void onStop() {
| adapter.stopListening();
| }
|}
""".trimMargin()))
.issues(ISSUE_MISSING_LISTENING_START_METHOD, ISSUE_MISSING_LISTENING_STOP_METHOD)
.run()
.expectClean()
}
}
18 changes: 18 additions & 0 deletions internal/lint/src/test/java/com/firebaseui/lint/LintTestHelper.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.firebaseui.lint

import com.android.tools.lint.checks.infrastructure.TestLintTask
import java.io.File

object LintTestHelper {
// Nasty hack to make lint tests pass on Windows. For some reason, lint doesn't
// automatically find the Android SDK in its standard path on Windows. This hack looks
// through the system properties to find the path defined in `local.properties` and then
// sets lint's SDK home to that path if it's found.
private val sdkPath = System.getProperty("java.library.path").split(';').find {
it.contains("SDK", true)
}

fun configuredLint(): TestLintTask = TestLintTask.lint().apply {
sdkHome(File(sdkPath ?: return@apply))
}
}
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
package com.firebaseui.lint

import com.android.tools.lint.checks.infrastructure.TestFiles.xml
import com.android.tools.lint.checks.infrastructure.TestLintTask
import com.android.tools.lint.checks.infrastructure.TestLintTask.lint
import com.firebaseui.lint.LintTestHelper.configuredLint
import com.firebaseui.lint.NonGlobalIdDetector.Companion.NON_GLOBAL_ID
import org.junit.Test
import java.io.File

class NonGlobalIdDetectorTest {
@Test
Expand Down Expand Up @@ -42,18 +40,4 @@ class NonGlobalIdDetectorTest {
|+ android:id="@+id/invalid"/>
|""".trimMargin())
}

companion object {
// Nasty hack to make lint tests pass on Windows. For some reason, lint doesn't
// automatically find the Android SDK in its standard path on Windows. This hack looks
// through the system properties to find the path defined in `local.properties` and then
// sets lint's SDK home to that path if it's found.
private val sdkPath = System.getProperty("java.library.path").split(';').find {
it.contains("SDK", true)
}

fun configuredLint(): TestLintTask = lint().apply {
sdkHome(File(sdkPath ?: return@apply))
}
}
}