-
-
Save coyarzun89/20f82245fc9432f894f4cb4be41be886 to your computer and use it in GitHub Desktop.
custom rule on ktlint
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class PrefixDataOnDtoModelsRule : Rule("prefix-data-on-dto-model") { | |
companion object { | |
const val DATA_PREFIX = "Data" | |
const val IMPORT_DTO = "data.dto" | |
} | |
override fun visit( | |
node: ASTNode, | |
autoCorrect: Boolean, | |
emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit | |
) { | |
if (node.elementType == ElementType.PACKAGE_DIRECTIVE) { | |
val qualifiedName = (node.psi as KtPackageDirective).qualifiedName | |
if (qualifiedName.isEmpty()) { | |
return | |
} | |
if (qualifiedName.endsWith(IMPORT_DTO)) { | |
node.treeParent.children().forEach { | |
checkClassesWithoutDataPrefix(it, autoCorrect, emit) | |
} | |
} | |
} | |
} | |
private fun checkClassesWithoutDataPrefix( | |
node: ASTNode, | |
autoCorrect: Boolean, | |
emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit | |
) { | |
if (node.elementType == ElementType.CLASS) { | |
val klass = node.psi as KtClass | |
if (klass.name?.startsWith(DATA_PREFIX, ignoreCase = true) != true) { | |
emit( | |
node.startOffset, | |
"'${klass.name}' class is not using " + | |
"the prefix Data. Classes inside any 'data.dto' package should " + | |
"use that prefix", | |
true | |
) | |
if (autoCorrect) { | |
klass.setName("$DATA_PREFIX${klass.name}") | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment