Skip to content
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

Fix ComposePreviewPublic to not look into non-public methods #85

Merged
merged 1 commit into from
Sep 27, 2022
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
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