shyiko by ktlint

Build Status Maven Central ktlint

Kotlin linter in spirit of feross/standard (JavaScript) and gofmt (Go).

Features:

  • No configuration. Which means no decisions to make, nothing to argue about and no special files to manage.
    While this might sound extreme, keep in mind that ktlint tries to capture (reflect) official code style from kotlinlang.org (+ we respect you .editorconfig* and support additional ruleset|s).
  • Built-in formatter. So that you wouldn’t have to fix all style violations by hand.
  • Customizable output. plain (+ plain?group_by_file), json and checkstyle reporters are available out-of-the-box. It’s also easy to create your own.
  • A single executable jar with all dependencies included.

* as of 0.9.0 ktlint recognizes insert_final_newline, max_line_length and indent_size
(provided they are specified under [*.{kt,kts}]).

Installation | Usage | Integration with Maven / Gradle / IntelliJ IDEA / Emacs | Creating a ruleset | a reporter | Badge | FAQ

Standard rules

  • 4 spaces for indentation*;
  • No semicolons (unless used to separate multiple statements on the same line);
  • No wildcard / unused imports;
  • No consecutive blank lines;
  • No trailing whitespaces;
  • No Unit returns;
  • No empty ({}) class bodies;
  • Consistent string templates ($v instead of ${v}, ${p.v} instead of ${p.v.toString()});
  • Consistent order of modifiers;
  • Consistent spacing after keywords, commas; around colons, curly braces, infix operators, etc.

* Starting from 0.8.0 value of indent_size specified under [*{kt,kts}] section in .editorconfig takes precedence (if any). Official recommendation is to use 4 spaces, though. (see #43 for details)

More coming.

Installation

Skip all the way to the “Integration” section if you don’t plan to use ktlint’s command line interface.

curl -sSLO https://github.com/shyiko/ktlint/releases/download/0.9.2/ktlint &&
  chmod a+x ktlint

If you don’t have curl installed - replace curl -sL with wget -qO-.

If you are behind a proxy see - curl / wget manpage. Usually simple http_proxy=http://proxy-server:port https_proxy=http://proxy-server:port curl -sL ... is enough.

… or just download ktlint from the “release(s)” page (ktlint.asc contains PGP signature which you can verify with curl -sS https://keybase.io/shyiko/pgp_keys.asc | gpg --import && gpg --verify ktlint.asc).

On Mac OS X (or Linux) one can also use brew - brew install shyiko/ktlint/ktlint.

Usage

# check the style of all Kotlin files inside the current dir (recursively)
# (hidden folders will be skipped)
$ ktlint
  src/main/kotlin/Main.kt:10:10: Unused import
  
# check only certain locations (prepend ! to negate the pattern) 
$ ktlint "src/**/*.kt" "!src/**/*Test.kt"

# auto-correct style violations
# (if some errors cannot be fixed automatically they will be printed to stderr) 
$ ktlint -F "src/**/*.kt"

# use custom reporter
ktlint --reporter=plain?group_by_file
ktlint --reporter=checkstyle > ktlint-report-in-checkstyle-format.xml

on Windows you’ll have to use java -jar ktlint ....

ktlint --help for more.

Integration

… with Maven

pom.xml

...
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-antrun-plugin</artifactId>
    <version>1.7</version>
    <executions>
        <execution>
            <id>ktlint</id>
            <phase>verify</phase>
            <configuration>
            <target name="ktlint">
                <java taskname="ktlint" dir="${basedir}" fork="true" failonerror="true"
                    classname="com.github.shyiko.ktlint.Main" classpathref="maven.plugin.classpath">
                    <arg value="src/**/*.kt"/>
                    <!-- prepend "--reporter=plain?group_by_file" arg to change the reporter -->
                </java>
            </target>
            </configuration>
            <goals><goal>run</goal></goals>
        </execution>
        <execution>
            <id>ktlint-format</id>
            <configuration>
            <target name="ktlint">
                <java taskname="ktlint" dir="${basedir}" fork="true" failonerror="true"
                    classname="com.github.shyiko.ktlint.Main" classpathref="maven.plugin.classpath">
                    <arg value="-F"/>
                    <arg value="src/**/*.kt"/>
                </java>
            </target>
            </configuration>
            <goals><goal>run</goal></goals>
        </execution>
    </executions>
    <dependencies>
        <dependency>
            <groupId>com.github.shyiko</groupId>
            <artifactId>ktlint</artifactId>
            <version>0.9.2</version>
        </dependency>
        <!-- additional 3rd party ruleset(s) can be specified here -->
    </dependencies>
</plugin>
...

To check code style - mvn antrun:run@ktlint (it’s also bound to mvn verify).
To run formatter - mvn antrun:run@ktlint-format.

To redirect output to a file you can use something like:

<execution>
    <id>ktlint-generate-checkstyle-xml</id>
    <configuration>
    <target name="ktlint">
        <java taskname="ktlint" dir="${basedir}" fork="true" failonerror="true"
            classname="com.github.shyiko.ktlint.Main" classpathref="maven.plugin.classpath"
            output="${project.build.directory}/ktlint-checkstyle-report.xml" 
            logError="true">
            <arg value="--reporter=checkstyle"/>
            <arg value="src/**/*.kt"/>
        </java>
    </target>
    </configuration>
    <goals><goal>run</goal></goals>
</execution>

… with Gradle

build.gradle

apply plugin: 'java'

repositories {
    mavenCentral()
}

configurations {
    ktlint
}

dependencies {
    ktlint 'com.github.shyiko:ktlint:0.9.2'
    // additional 3rd party ruleset(s) can be specified here
    // just add them to the classpath (ktlint 'groupId:artifactId:version') and 
    // ktlint will pick them up
}

task ktlint(type: JavaExec) {
    main = "com.github.shyiko.ktlint.Main"
    classpath = configurations.ktlint
    args "src/**/*.kt"
    // prepend "--reporter=plain?group_by_file" arg to change the reporter
}

check.dependsOn ktlint

task ktlintFormat(type: JavaExec) {
    main = "com.github.shyiko.ktlint.Main"
    classpath = configurations.ktlint
    args "-F", "src/**/*.kt"
}

To check code style - gradle ktlint (it’s also bound to gradle check).
To run formatter - gradle ktlintFormat.

To redirect output to a file you can use something like:

task ktlintGenerateCheckstyleXML(type: Exec) {
  commandLine 'java', '-cp', configurations.ktlint.join(System.getProperty('path.separator')),
    'com.github.shyiko.ktlint.Main', '--reporter=checkstyle', 'src/**/*.kt'
  standardOutput = new FileOutputStream(new File(buildDir, "ktlint-checkstyle-report.xml"))
  ignoreExitValue = true
  doLast {
    standardOutput.close()
    if (execResult.exitValue != 0) {
      throw new GradleException("ktlint finished with non-zero exit value ${execResult.exitValue}")
    }
  }
}

Another option is to use Gradle plugin (in order of appearance):

Each plugin has some unique features (like incremental build support in case of jeremymailen/kotlinter-gradle) so check them out.

You might also want to take a look at diffplug/spotless which has a built-in support for ktlint. In addition to linting/formatting kotlin code it allows you to keep license headers, markdown documentation, etc. in check.

… with IntelliJ IDEA

While this is not strictly necessary it makes Intellij IDEA’s built-in formatter produce 100% ktlint-compatible code.

# inside project's root directory  
ktlint --apply-to-idea 
Option #2

Go to File -> Settings... -> Editor

Option #3

Go to File -> Settings... -> Editor

  • Code Style -> Kotlin
    • open Imports tab, select all Use single name import options and remove import java.util.* from Packages to Use Import with '*'.
    • open Blank Lines tab, change Keep Maximum Blank Lines -> In declarations & In code to 1.
    • (optional but recommended) open Wrapping and Braces tab, uncheck Method declaration parameters -> Align when multiline.
    • (optional but recommended) open Tabs and Indents tab, change Continuation indent to 4.
  • Inspections
    • change Severity level of Unused import directive, Redundant semicolon and (optional but recommended) Unused symbol to ERROR.

… with GNU Emacs

See whirm/flycheck-kotlin.

Integrated with something else? Send a PR.

Creating a ruleset

In a nutshell: “ruleset” is a JAR containing one or more Rules gathered together in a RuleSet. ktlint is relying on ServiceLoader to discover all available “RuleSet”s on the classpath (as a ruleset author, all you need to do is to include a META-INF/services/com.github.shyiko.ktlint.core.RuleSetProvider file containing a fully qualified name of your RuleSetProvider implementation).

A complete sample project (with tests and build files) is included in this repo under the ktlint-ruleset-template directory (make sure to check NoVarRuleTest as it contains some useful information).

Creating a reporter

Take a look at ktlint-reporter-plain.

In short, all you need to do is to implement a Reporter and make it available by registering a custom ReporterProvider using META-INF/services/com.github.shyiko.ktlint.core.ReporterProvider. Pack all of that into a JAR and you’re done.

To load a custom (3rd party) reporter use ktlint --reporter=groupId:artifactId:version / ktlint --reporter=/path/to/custom-ktlint-reporter.jar (see ktlint --help for more).

Badge

If you use ktlint in your project, consider including a badge in your readme to let people know that your code is checked by ktlint.

ktlint

[![ktlint](https://img.shields.io/badge/code%20style-%E2%9D%A4-FF4081.svg)](https://ktlint.github.io/)

FAQ

Why should I use ktlint?

Simplicity.

Spending time on configuration (& maintenance down the road) of hundred-line long style config file(s) is counter-productive. Instead of wasting your energy on something that has no business value - focus on what really matters (not debating whether to use tabs or spaces).

By using ktlint you put the importance of code clarity and community conventions over personal preferences. This makes things easier for people reading your code as well as frees you from having to document & explain what style potential contributor(s) have to follow.

ktlint is a single binary with both linter & formatter included. All you need is to drop it in (no need to get overwhelmed while choosing among dozens of code style options).

Can I have my own rules on top of ktlint?

Absolutely, “no configuration” doesn’t mean “no extensibility”. You can add your own ruleset(s) to discover potential bugs, check for anti-patterns, etc.

See Creating A Ruleset.

Once packaged in a JAR you can load it with

# enable additional 3rd party ruleset by pointing ktlint to its location on the file system
$ ktlint -R /path/to/custom/rulseset.jar "src/test/**/*.kt"

# you can also use <groupId>:<artifactId>:<version> triple in which case artifact is
# downloaded from Maven Central, JCenter or JitPack (depending on where it's located and 
# whether or not it's already present in local Maven cache)
$ ktlint -R com.github.username:rulseset:master-SNAPSHOT

How do I suppress an error?

This is meant primarily as an escape latch for the rare cases when ktlint is not able to produce the correct result (please report any such instances using GitHub Issues).

To disable a specific rule you’ll need to turn on the verbose mode (ktlint --verbose ...). At the end of each line you’ll see an error code. Use it as an argument for ktlint-disable directive (shown below).

import package.* // ktlint-disable no-wildcard-imports

/* ktlint-disable no-wildcard-imports */
import package.a.*
import package.b.*
/* ktlint-enable no-wildcard-imports */

To disable all checks:

import package.* // ktlint-disable

Development

Make sure to read CONTRIBUTING.md.

git clone https://github.com/shyiko/ktlint && cd ktlint
./mvnw # shows how to build, test, etc. project

This project is not affiliated with or endorsed by the Jetbrains.
All code, unless specified otherwise, is licensed under the MIT license.
Copyright (c) 2016 Stanley Shyiko.

compile "com.github.shyiko:ktlint:0.9.2"

Related Libraries

kotlin-argparser

Easy to use and concise yet powerful and robust command line argument parsing for Kotlin

Last updated 3 mins ago

ktlint

An anti-bikeshedding Kotlin linter with built-in formatter

Last updated 3 mins ago

ts2kt

Converter of TypeScript definition files to Kotlin declarations (stubs)

Last updated 3 mins ago

kotlin-frontend-plugin

Gradle Kotlin (http -//kotlinlang.org) plugin for frontend development

Last updated 3 mins ago

dokka

Documentation Engine for Kotlin

Last updated 3 mins ago