Skip to content

Commit

Permalink
Fix ComposePreviewPublic to not look into non-public methods (#85)
Browse files Browse the repository at this point in the history
`ComposePreviewPublic` was looking into private/internal methods and could have false positives if they used `PreviewParameter`s. This patch changes that behavior and adds a test to prevent regressions.
  • Loading branch information
mrmans0n committed Sep 27, 2022
1 parent 6833a74 commit e95198f
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,12 @@ class ComposePreviewPublic : ComposeKtVisitor {
override fun visitComposable(function: KtFunction, autoCorrect: Boolean, emitter: Emitter) {
// We only want previews
if (!function.isPreview) return
// ...that if it is public, none of it's params is tagged as preview
if (function.isPublic && function.valueParameters.none { it.isPreviewParameter }) return
// ...and if it isn't public, all params are tagged as preview
if (!function.isPublic && function.valueParameters.all { it.isPreviewParameter }) return
// We only care about public methods
if (!function.isPublic) return
// If the method is public, none of it's params should be tagged as preview
if (function.valueParameters.none { it.isPreviewParameter }) return

// If we got here, it's a public method in a @Preview composable with a @PreviewParameter parameter
emitter.report(function, ComposablesPreviewShouldNotBePublic, true)
if (autoCorrect) {
function.addModifier(KtTokens.PRIVATE_KEYWORD)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,24 @@ class ComposePreviewPublicCheckTest {
}
}

@Test
fun `passes when a non-public preview composable uses preview params`() {
@Language("kotlin")
val code =
"""
@Preview
@Composable
private fun MyComposable(@PreviewParameter(User::class) user: User) {
}
@Preview
@Composable
internal fun MyComposable(@PreviewParameter(User::class) user: User) {
}
""".trimIndent()
val errors = rule.lint(code)
assertThat(errors).isEmpty()
}

@Test
fun `passes when a private preview composable uses preview params`() {
@Language("kotlin")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,23 @@ class ComposePreviewPublicCheckTest {
)
}

@Test
fun `passes when a non-public preview composable uses preview params`() {
@Language("kotlin")
val code =
"""
@Preview
@Composable
private fun MyComposable(@PreviewParameter(User::class) user: User) {
}
@Preview
@Composable
internal fun MyComposable(@PreviewParameter(User::class) user: User) {
}
""".trimIndent()
ruleAssertThat(code).hasNoLintViolations()
}

@Test
fun `autofix makes private the public preview`() {
@Language("kotlin")
Expand Down

0 comments on commit e95198f

Please sign in to comment.