Skip to content

Instantly share code, notes, and snippets.

@coyarzun89
Created May 8, 2021 20:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coyarzun89/20f82245fc9432f894f4cb4be41be886 to your computer and use it in GitHub Desktop.
Save coyarzun89/20f82245fc9432f894f4cb4be41be886 to your computer and use it in GitHub Desktop.
custom rule on ktlint
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