Skip to content

Commit

Permalink
style: Create ForbiddenImportsRule to avoid java.io.File imports in l…
Browse files Browse the repository at this point in the history
…ib and app projects
  • Loading branch information
guicamest committed Oct 18, 2023
1 parent bb69331 commit 5220120
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 13 deletions.
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
package com.sleepcamel.ktlint

import com.pinterest.ktlint.rule.engine.core.api.ElementType
import com.pinterest.ktlint.rule.engine.core.api.Rule
import com.pinterest.ktlint.rule.engine.core.api.RuleId
import org.jetbrains.kotlin.com.intellij.lang.ASTNode
import org.jetbrains.kotlin.psi.KtImportDirective
import org.jetbrains.kotlin.psi.stubs.elements.KtStubElementTypes

class ForbiddenImportsRule : Rule(
ruleId = RuleId("$CUSTOM_RULE_SET_ID:forbidden"),
Expand All @@ -14,17 +15,12 @@ class ForbiddenImportsRule : Rule(
autoCorrect: Boolean,
emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit
) {
if (node.elementType == ElementType.IMPORT_LIST) {
val children = node.getChildren(null)
if (children.isNotEmpty()) {
children.forEach { println(it) }
val first = children.first()
println(first)
if (node.elementType == KtStubElementTypes.IMPORT_DIRECTIVE) {
val importDirective = node.psi as KtImportDirective
val path = importDirective.importPath?.pathStr
if (path.orEmpty() == "java.io.File") {
emit(node.startOffset, "File has a forbidden import: $path", false)
}
// if (node is LeafPsiElement && node.textMatches("var") &&
// getNonStrictParentOfType(node, KtStringTemplateEntry::class.java) == null
// ) {
// emit(node.startOffset, "Unexpected var, use val instead", false)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@ class ForbiddenImportsRuleTest {
val fileContent = """
import java.io.File
""".trimIndent()
System.setProperty("ktlintDebug", "ast")

wrappingRuleAssertThat(fileContent)
.hasLintViolationWithoutAutoCorrect(
line = 1,
col = 1,
detail = "no-java-io-file-import"
detail = "File has a forbidden import: java.io.File"
)
}
}

0 comments on commit 5220120

Please sign in to comment.