Skip to content
forked from pinterest/ktlint

An anti-bikeshedding Kotlin linter with built-in formatter

License

Notifications You must be signed in to change notification settings

Sethathi/ktlint

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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 and Android Kotlin Style Guide (+ we respect your .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.

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

Standard rules

  • 4 spaces for indentation
    (unless a different indent_size value is set in .editorconfig (see EditorConfig section for more))
  • No semicolons (unless used to separate multiple statements on the same line)
  • No unused imports
  • No consecutive blank lines
  • No blank lines before }
  • No trailing whitespaces
  • No Unit returns (fun fn {} instead of fun fn: Unit {})
  • No empty ({}) class bodies
  • No spaces around range (..) operator
  • No newline before (binary) + & -, *, /, %, &&, ||
  • No wildcard imports
  • When wrapping chained calls ., ?. and ?: should be placed on the next line
  • When a line is broken at an assignment (=) operator the break comes after the symbol
  • When class/function signature doesn't fit on a single line, each parameter must be on a separate line
  • 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, parens, infix operators, comments, etc
  • Newline at the end of each file (enabled by default) (set insert_final_newline=false in .editorconfig to disable (see EditorConfig section for more)).
  • Imports ordered in alphabetic order with no spaces between major groups

Experimental rules

New rules will be added into the experimental ruleset, which can be enabled by passing the --experimental flag to ktlint.

  • Indentation formatting - respects .editorconfig indent_size with no continuation indent
  • Annotation formatting - multiple annotations should be on a separate line than the annotated declaration; annotations with parameters should each be on separate lines; annotations should be followed by a space
  • No underscores in package names
  • Braces required for multiline if/else statements

EditorConfig

ktlint recognizes the following .editorconfig properties (provided they are specified under [*.{kt,kts}]):
(values shown below are the defaults and do not need to be specified explicitly)

[*.{kt,kts}]
# possible values: number (e.g. 2), "unset" (makes ktlint ignore indentation completely)  
indent_size=4
# true (recommended) / false
insert_final_newline=true
# possible values: number (e.g. 120) (package name, imports & comments are ignored), "off"
# it's automatically set to 100 on `ktlint --android ...` (per Android Kotlin Style Guide)
max_line_length=off

Custom EditorConfig properties

# Comma-separated list of rules to disable (Since 0.34.0)
# Note that rules in any ruleset other than the standard ruleset will need to be prefixed 
# by the ruleset identifier.
disabled_rules=no-wildcard-imports,experimental:annotation,my-custom-ruleset:my-custom-rule

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/pinterest/ktlint/releases/download/0.36.0/ktlint &&
  chmod a+x ktlint &&
  sudo mv ktlint /usr/local/bin/

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

On macOS (or Linux) you can also use brew - brew install 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.

Usage

# check the style of all Kotlin files inside the current dir (recursively)
# (hidden folders will be skipped)
$ ktlint --color [--color-name="RED"]
  src/main/kotlin/Main.kt:10:10: Unused import
  
# check only certain locations (prepend ! to negate the pattern,
# Ktlint uses .gitignore pattern style syntax)
$ 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"

# print style violations grouped by file
$ ktlint --reporter=plain?group_by_file
# print style violations as usual + create report in checkstyle format 
$ ktlint --reporter=plain --reporter=checkstyle,output=ktlint-report-in-checkstyle-format.xml

# install git hook to automatically check files for style violations on commit
# Run "ktlint installGitPrePushHook" if you wish to run ktlint on push instead
$ ktlint installGitPreCommitHook

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.8</version>
    <executions>
        <execution>
            <id>ktlint</id>
            <phase>verify</phase>
            <configuration>
            <target name="ktlint">
                <java taskname="ktlint" dir="${basedir}" fork="true" failonerror="true"
                    classpathref="maven.plugin.classpath" classname="com.pinterest.ktlint.Main">
                    <arg value="src/**/*.kt"/>
                    <!-- to generate report in checkstyle format prepend following args: -->
                    <!-- 
                    <arg value="--reporter=plain"/>
                    <arg value="--reporter=checkstyle,output=${project.build.directory}/ktlint.xml"/>
                    -->
                    <!-- see https://github.com/shyiko/ktlint#usage for more -->                    
                </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"
                    classpathref="maven.plugin.classpath" classname="com.pinterest.ktlint.Main">
                    <arg value="-F"/>
                    <arg value="src/**/*.kt"/>
                </java>
            </target>
            </configuration>
            <goals><goal>run</goal></goals>
        </execution>
    </executions>
    <dependencies>
        <dependency>
            <groupId>com.pinterest</groupId>
            <artifactId>ktlint</artifactId>
            <version>0.36.0</version>
        </dependency>
        <!-- additional 3rd party ruleset(s) can be specified here -->
    </dependencies>
</plugin>
...

If you want ktlint to run before code compilation takes place - change <phase>verify</phase> to <phase>validate</phase> (see Maven Build Lifecycle for more).

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

Another option is to use a dedicated Maven plugin - gantsign/ktlint-maven-plugin.

... with Gradle

(with a plugin - Recommended)

Gradle plugins (in order of appearance):

  • jlleitschuh/ktlint-gradle
    Gradle plugin that automatically creates check and format tasks for project Kotlin sources, supports different kotlin plugins and Gradle build caching.

  • jeremymailen/kotlinter-gradle
    Gradle plugin featuring incremental build support, file reports, and *.kts source support.

You might also want to take a look at diffplug/spotless or autostyle/autostyle that have 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.

(without a plugin)

build.gradle

// kotlin-gradle-plugin must be applied for configuration below to work
// (see https://kotlinlang.org/docs/reference/using-gradle.html)

apply plugin: 'java'

repositories {
    jcenter()
}

configurations {
    ktlint
}

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

task ktlint(type: JavaExec, group: "verification") {
    description = "Check Kotlin code style."
    classpath = configurations.ktlint
    main = "com.pinterest.ktlint.Main"
    args "src/**/*.kt"
    // to generate report in checkstyle format prepend following args:
    // "--reporter=plain", "--reporter=checkstyle,output=${buildDir}/ktlint.xml"
    // see https://github.com/pinterest/ktlint#usage for more
}
check.dependsOn ktlint

task ktlintFormat(type: JavaExec, group: "formatting") {
    description = "Fix Kotlin code style deviations."
    classpath = configurations.ktlint
    main = "com.pinterest.ktlint.Main"
    args "-F", "src/**/*.kt"
}

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

See Making your Gradle tasks incremental by Niklas Baudy on how to make tasks above incremental.

... with IntelliJ IDEA

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

Option #1 (recommended)

(inside project's root directory)

ktlint applyToIDEAProject
# or if you want to be compliant with Android Kotlin Style Guide
ktlint --android applyToIDEAProject
Option #2

Apply to all IDEA projects:

$ ./ktlint applyToIDEA

Or if you want to use android specific code style:

$ ./ktlint --android applyToIDEA
Option #3

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

  • General -> Auto Import
    • check Optimize imports on the fly (for current project).
  • Code Style -> Kotlin
    • Set from... -> Predefined style -> Kotlin style guide (Kotlin plugin 1.2.20+).
    • open Code Generation tab
      • uncheck Line comment at first column;
      • select Add a space at comment start.
    • open Imports tab
      • select Use single name import (all of them);
      • 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 and Before '}' to 0.
    • (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 the same value as Indent (4 by default).
  • Inspections
    • change Severity level of Unused import directive and Redundant semicolon to ERROR.

... with GNU Emacs

See whirm/flycheck-kotlin.

... with Vim

See w0rp/ale.

Integrated with something else? Send a PR.

Creating a ruleset

See also Writing your first ktlint rule by Niklas Baudy.

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.pinterest.ktlint.core.RuleSetProvider file containing a fully qualified name of your RuleSetProvider implementation).

Once packaged in a JAR e.g. via ./gradlew build 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"

Loading custom (3rd party) ruleset via built-in maven dependency resolver is deprecated, see pinterest#451.

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).

AST

While writing/debugging Rules it's often helpful to have an AST printed out to see the structure rules have to work with. ktlint >= 0.15.0 has a printAST subcommand (or --print-ast flag for ktlint < 0.34.0) specifically for this purpose (usage: ktlint --color printAST <file>). An example of the output is shown below.

$ printf "fun main() {}" | ktlint --color printAST --stdin

1: ~.psi.KtFile (~.psi.stubs.elements.KtFileElementType.kotlin.FILE)
1:   ~.psi.KtPackageDirective (~.psi.stubs.elements.KtPlaceHolderStubElementType.PACKAGE_DIRECTIVE) ""
1:   ~.psi.KtImportList (~.psi.stubs.elements.KtPlaceHolderStubElementType.IMPORT_LIST) ""
1:   ~.psi.KtScript (~.psi.stubs.elements.KtScriptElementType.SCRIPT)
1:     ~.psi.KtBlockExpression (~.KtNodeType.BLOCK)
1:       ~.psi.KtNamedFunction (~.psi.stubs.elements.KtFunctionElementType.FUN)
1:         ~.c.i.p.impl.source.tree.LeafPsiElement (~.lexer.KtKeywordToken.fun) "fun"
1:         ~.c.i.p.impl.source.tree.PsiWhiteSpaceImpl (~.c.i.p.tree.IElementType.WHITE_SPACE) " "
1:         ~.c.i.p.impl.source.tree.LeafPsiElement (~.lexer.KtToken.IDENTIFIER) "main"
1:         ~.psi.KtParameterList 
  (~.psi.stubs.elements.KtPlaceHolderStubElementType.VALUE_PARAMETER_LIST)
1:           ~.c.i.p.impl.source.tree.LeafPsiElement (~.lexer.KtSingleValueToken.LPAR) "("
1:           ~.c.i.p.impl.source.tree.LeafPsiElement (~.lexer.KtSingleValueToken.RPAR) ")"
1:         ~.c.i.p.impl.source.tree.PsiWhiteSpaceImpl (~.c.i.p.tree.IElementType.WHITE_SPACE) " "
1:         ~.psi.KtBlockExpression (~.KtNodeType.BLOCK)
1:           ~.c.i.p.impl.source.tree.LeafPsiElement (~.lexer.KtSingleValueToken.LBRACE) "{"
1:           ~.c.i.p.impl.source.tree.LeafPsiElement (~.lexer.KtSingleValueToken.RBRACE) "}"

   format: <line_number:> <node.psi::class> (<node.elementType>) "<node.text>"
   legend: ~ = org.jetbrains.kotlin, c.i.p = com.intellij.psi
   

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.pinterest.ktlint.core.ReporterProvider. Pack all of that into a JAR and you're done.

To load a custom (3rd party) reporter use ktlint --reporter=name,artifact=/path/to/custom-ktlint-reporter.jar (see ktlint --help for more).

Loading custom (3rd party) reporter via built-in maven dependency resolver is deprecated, see pinterest#451.

Third-party:

Badge

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.

How do I suppress an error for a line/block/file?

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

How do I globally disable a rule?

See the EditorConfig section for details on how to use the disabled_rules property.

You may also pass a list of disabled rules via the --disabled_rules command line flag. It has the same syntax as the EditorConfig property.

Development

Make sure to read CONTRIBUTING.md.

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

To open ktlint in Intellij IDEA:
File -> Open... (you may need to right-click on pom.xml (in the project dir) and then Maven -> Reimport).
You'll also need to set "Project SDK" to 1.8, "Project language level" to 8 in "Project Settings" (File -> Project Structure...).
To run ktlint - right-click on ktlint/src/main/kotlin/com/pinterest/ktlint/Main.kt -> Run.

Access to the latest master snapshot

Whenever a commit is added to the master branch a snapshot build is automatically uploaded to Sonatype's snapshots repository. If you are eager to try upcoming changes (that might or might not be included in the next stable release) you can do so by changing version of ktlint to <latest-version>-SNAPSHOT + adding a repo:

Maven
...
<repository>
    <id>sonatype-snapshots</id>
    <url>https://oss.sonatype.org/content/repositories/snapshots</url>
    <snapshots>
        <enabled>true</enabled>
    </snapshots>
    <releases>
        <enabled>false</enabled>
    </releases>
</repository>
...
Gradle
repositories {
  maven {
    url "https://oss.sonatype.org/content/repositories/snapshots"
  }
}

Legal

This project is not affiliated with nor endorsed by JetBrains.
All code, unless specified otherwise, is licensed under the MIT license.
Copyright (c) 2019 Pinterest, Inc.
Copyright (c) 2016-2019 Stanley Shyiko.

About

An anti-bikeshedding Kotlin linter with built-in formatter

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Kotlin 91.8%
  • Ruby 3.6%
  • Python 3.5%
  • Other 1.1%