Description
Could you expand on how to create your own rulesets? I looked into ServiceLoader javadocs and have the following understanding:
You should have a directory structure similar to:
(taken from the ktlint-ruleset-template)
Project/
src/main/
kotlin/
CustomRuleSetProvider
Rules
resources/
META-INF.services/
com.github.shyiko.ktlint.core.RuleSetProvider
From the project directory you should be able to run:
jar cf ruleset.jar Project/
And then this can be used by ktlint as:
ktlint -R ruleset.jar ....
Although my rule is never reached! Could you please give more details on how exactly this jar should be created?
Here is what my resources look like:
//resources/META-INF.services
//com.github.shyiko.ktlint.core.RuleSetProvider
mypackage.CustomRuleSetProvider
Here is my CustomRuleSetProvider
//CustomRuleSetProvider
package mypackage
import com.github.shyiko.ktlint.core.RuleSet
import com.github.shyiko.ktlint.core.RuleSetProvider
class CustomRuleSetProvider : RuleSetProvider {
override fun get(): RuleSet = RuleSet("custom", TestVisit())
}
Here is my Rule, which naively prints a test message on each visit.
//TestVisit
package mypackage
import com.github.shyiko.ktlint.core.Rule
import org.jetbrains.kotlin.com.intellij.lang.ASTNode
import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafPsiElement
import org.jetbrains.kotlin.com.intellij.psi.util.PsiTreeUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.psi.KtStringTemplateEntry
class TestVisit : Rule("test-visit") {
override fun visit(
node: ASTNode,
autoCorrect: Boolean,
emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit
) {
emit(node.startOffset, "test", false)
}
}