Kotlin Linting RuleSetProvider 'trailing-comma'

5.4k views Asked by At

I been trying to create a Ruleset using Pinterest ktlint Library but I can't remove the part of a children parameter list.

https://github.com/pinterest/ktlint/issues/709

Due to the update on Kotlin to support 'trailing-commas', is breaking all my static code analysis (SonarQube Gradle plugin 2.8). So I decided to create a RuleSetProvider to find a remove from the code this annoying comma ',' at the end of all the parameter list found in the project.

class NoTrailingCommaRule : Rule("no-trailing-comma") {

override fun visit(
    node: ASTNode,
    autoCorrect: Boolean,
    emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit
) {
    if (node.elementType == ElementType.COMMA) {
        node.parents().forEach {
            if (it.elementType == ElementType.VALUE_PARAMETER_LIST) {
                if (it.text.contains("pepe")) {
                    println("############# IS PEPE ###############")
                    println("ParamList-> " + it.text)
                    println("-------------------------------------")

                    if (it is PsiParameterList) {
                        it.parameters.forEach { param ->
                            println("   -> ${param.text}")
//                            if (next.elementType == ElementType.COMMA)
//                                println("     -> comma,")
                            println("---==---")
                        }
                        println("#####################################")
                    }
                }
            }
        }
    }
  }
}

/// Sample class to lint
data class PEPE(
   val pepe: String,
   var pepe1: List<String> = emptyList(), //<- This is the kind of comma I want to remove
) 

Thats my current attempt of trying to get the comma and replace, but when I'm able to print the parameter line the comma is not there.

1

There are 1 answers

0
Padi On BEST ANSWER

See rule below for which I have sent a PR:

package com.pinterest.ktlint.ruleset.experimental

import com.pinterest.ktlint.core.Rule
import com.pinterest.ktlint.core.ast.ElementType
import com.pinterest.ktlint.core.ast.children
import org.jetbrains.kotlin.com.intellij.lang.ASTNode
import org.jetbrains.kotlin.psi.psiUtil.endOffset

class NoTrailingCommaRule : Rule("no-trailing-comma") {

    override fun visit(
        node: ASTNode,
        autoCorrect: Boolean,
        emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit
    ) {
        if (node.elementType == ElementType.VALUE_ARGUMENT_LIST || node.elementType == ElementType.VALUE_PARAMETER_LIST) {
            val lastNode = node
                .children()
                .filter { it.elementType != ElementType.WHITE_SPACE }
                .filter { it.elementType != ElementType.EOL_COMMENT }
                .filter { it.elementType != ElementType.RPAR }
                .last()
            if (lastNode.elementType == ElementType.COMMA) {
                emit(lastNode.psi.endOffset - 1, "Trailing command in argument list is redundant", true)
                if (autoCorrect) {
                    node.removeChild(lastNode)
                }
            }
        }
    }
}

and the tests:

package com.pinterest.ktlint.ruleset.experimental

import com.pinterest.ktlint.core.LintError
import com.pinterest.ktlint.test.format
import com.pinterest.ktlint.test.lint
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test

class NoTrailingCommaRuleTest {
    @Test
    fun testFormatIsCorrectWithArgumentList() {
        val code =
            """
            val list1 = listOf("a", "b",)
            val list2 = listOf(
                "a",
                "b", // The comma before the comment should be removed without removing the comment itself
            )
            """.trimIndent()
        val autoCorrectedCode =
            """
            val list1 = listOf("a", "b")
            val list2 = listOf(
                "a",
                "b" // The comma before the comment should be removed without removing the comment itself
            )
            """.trimIndent()

        assertThat(NoTrailingCommaRule().lint(code)).isEqualTo(
            listOf(
                LintError(line = 1, col = 28, ruleId = "no-trailing-comma", detail = "Trailing command in argument list is redundant"),
                LintError(line = 4, col = 8, ruleId = "no-trailing-comma", detail = "Trailing command in argument list is redundant"),
            )
        )
        assertThat(NoTrailingCommaRule().format(code))
            .isEqualTo(autoCorrectedCode)
    }

    @Test
    fun testFormatIsCorrectWithValueList() {
        val code =
            """
            data class Foo1(
               val bar: Int, // The comma before the comment should be removed without removing the comment itself
            )
            data class Foo2(val bar: Int,)
            """.trimIndent()
        val autoCorrectedCode =
            """
            data class Foo1(
               val bar: Int // The comma before the comment should be removed without removing the comment itself
            )
            data class Foo2(val bar: Int)
            """.trimIndent()

        assertThat(NoTrailingCommaRule().lint(code)).isEqualTo(
            listOf(
                LintError(line = 2, col = 16, ruleId = "no-trailing-comma", detail = "Trailing command in argument list is redundant"),
                LintError(line = 4, col = 29, ruleId = "no-trailing-comma", detail = "Trailing command in argument list is redundant"),
            )
        )
        assertThat(NoTrailingCommaRule().format(code))
            .isEqualTo(autoCorrectedCode)
    }
}