ktlint icon indicating copy to clipboard operation
ktlint copied to clipboard

Provide an example of how to use ktlint programmatically (using API)

Open shyiko opened this issue 6 years ago • 1 comments

... but first improve the API.

Currently, in order to lint/format a file you need something like this:

//DEPS com.github.shyiko:ktlint:0.30.0

import com.github.shyiko.ktlint.core.KtLint
import com.github.shyiko.ktlint.internal.EditorConfig
import com.github.shyiko.ktlint.ruleset.standard.StandardRuleSetProvider

val file: File = ...
val editorConfig = EditorConfig.of(file.parentFile.canonicalPath) 
	?: emptyMap<String, String>()
val userData = editorConfig + mapOf("file_path" to file.absolutePath)
val ruleSets = listOf(StandardRuleSetProvider().get())
KtLint.lint(file.readText(), ruleSets, userData) { e ->
    println("${e.line}:${e.col} ${e.detail} (${e.ruleId})")
}

Code above has numerous issues (aside from being too complicated):

  • needless dependency on com.github.shyiko:ktlint (cli module)
    (com.github.shyiko:ktlint-core should be enough)
  • EditorConfig is part of com.github.shyiko.ktlint.internal (which does not guarantee backward-compatibly)
  • EditorConfig.of(...) result (basically .editorconfig content) is mixed with unrelated entries (e.g. "file_path")
  • error prone & poorly discoverable (magic "file_path" value)

shyiko avatar Feb 12 '19 07:02 shyiko

Any update?

UkonnRa avatar Mar 23 '21 11:03 UkonnRa

Several open source projects have implemented an integration with the KtLint API. There does not seem to be much value in adding another example implementation as part of KtLint (documentation) itself.

paul-dingemans avatar Nov 22 '22 20:11 paul-dingemans