首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Kotlin Linting RuleSetProvider‘尾随逗号’

Kotlin Linting RuleSetProvider‘尾随逗号’
EN

Stack Overflow用户
提问于 2020-11-29 08:25:12
回答 1查看 1.1K关注 0票数 2

我一直在尝试使用Pinterest ktlint库创建一个规则集,但我无法删除子参数列表中的一部分。

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

由于Kotlin支持‘拖尾逗号’的更新,打破了我所有的静态代码分析(SonarQube Gradle plugin2.8)。因此,我决定创建一个RuleSetProvider,以便在项目中找到的所有参数列表的结尾处删除这个恼人的逗号',‘。

代码语言:javascript
复制
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
) 

这就是我目前尝试获取并替换逗号的方法,但是当我能够打印参数行时,逗号就不在那里了。?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-12-26 00:29:50

请看下面的规则,我已经发送了PR:

代码语言:javascript
复制
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)
                }
            }
        }
    }
}

以及测试结果:

代码语言:javascript
复制
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)
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65055798

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档