How to create a custom rule for ktlint?

65 views Asked by At

Currently, ktlint is not catching the comment block bad format.

/**
 * 
 * 
 * */

Expected behavior
Ktlint should catch this bad format.

Correct format

/**
 *
 */

I want to make a custom rule or something else to solve the problem.

1

There are 1 answers

0
Gurgen Arustamyan On
import com.pinterest.ktlint.core.Rule
import com.pinterest.ktlint.core.RuleSet
import com.pinterest.ktlint.core.RuleSetProvider
import org.jetbrains.kotlin.com.intellij.lang.ASTNode
import org.jetbrains.kotlin.com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtDocComment
import org.jetbrains.kotlin.psi.KtElement

class DocCommentFormatRule : Rule("doc-comment-format") {

    override fun visit(node: ASTNode, autoCorrect: Boolean, emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit) {
        if (node.elementType == KtTokens.DOC_COMMENT) {
            val ktDocComment = PsiTreeUtil.getParentOfType(node.psi, KtDocComment::class.java)
            if (ktDocComment != null && !isCorrectFormat(ktDocComment)) {
                emit(node.startOffset, "Doc comment is not formatted correctly", false)
            }
        }
    }

    private fun isCorrectFormat(docComment: KtDocComment): Boolean {
        val text = docComment.text.trim()
        return text.startsWith("/**") && text.endsWith("*/")
    }

    class Provider : RuleSetProvider {
        override fun get() = RuleSet("doc-comment-format", DocCommentFormatRule())
    }
}
  1. Register custom rule: Register your custom rule so that Ktlint recognizes and applies it. This typically involves adding a service file in the resources folder of your project. Create a file named META-INF/services/com.pinterest.ktlint.core.RuleSetProvider and add the fully qualified name of your rule provider class (DocCommentFormatRule.Provider) to it.

  2. Run Ktlint: Once you've added the custom rule, you can run Ktlint on your Kotlin codebase, and it will enforce the correct format for Kotlin doc comments.

./gradlew ktlint

This will check your Kotlin code for compliance with the custom rule.