ktlint baseline

Josh Feinberg
2 min readDec 7, 2020

Adding ktlint to a large existing project already can be a headache. Despite the tools obvious advantages, it becomes hard to force it upon a team to solve a bunch of style issues right at the front. This is where the idea of the baseline file for ktlint came from.

For those that aren’t familiar, ktlint describes itself as “an anti-bikeshedding Kotlin linter with built-in formatter”. This means that a project can guarantee certain code styling standards throughout their project.

Now you may notice that it says it contains a formatter, which is true. A new project could add the ktlintFormat task (found here) and run ./gradlew ktlintFormat and be done with it. This however brings in the cost that it might produce large amounts of changes depending on the size of the code base, while also requiring a developer to manually fix the errors that cannot be resolved automatically by the formatter.

Those who have used Android’s linter know it comes with a functionality called baseline. To configure it, in a modules gradle file you simply add it to the lint options like so:

lintOptions {
baseline file("lint-baseline.xml")
}

After the first run of lint, it will generate a xml file containing all the lint errors that currently exist in the project. In future runs, only warnings and errors that don’t exist in the baseline will be reported. This can be hugely helpful when making lint abort on error as developers can no longer add new lint issues, but do not need to go fix all existing ones.

As of the 0.40.0 release, similar functionality was added to ktlint. The PR here gives a quick view of how it works.

A new flag, --baseline <FILE_NAME> was added that can be put into your current ktlint commands. This will, just as in Android lint, generate an xml file on first run with your current baseline and in subsequent runs will not return those as errors. To use this flag, you can simply run ktlint --baseline=ktlint-baseline.xml and the file should be generated.

If you would like to add it to your gradle file, simply put is an argument:

task ktlint(type: JavaExec, group: LifecycleBasePlugin.VERIFICATION_GROUP) {
description = "Check Kotlin code style."
classpath = configurations.ktlint
main = 'com.pinterest.ktlint.Main'
args '*/src/**/*.kt', '--baseline=ktlint-baseline.xml'
}

I hope this proves helpful to everyone and please feel free to file issues or message me if you have any issues with the new functionality.

--

--