• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

pinterest/ktlint: An anti-bikeshedding Kotlin linter with built-in formatter

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称(OpenSource Name):

pinterest/ktlint

开源软件地址(OpenSource Url):

https://github.com/pinterest/ktlint

开源编程语言(OpenSource Language):

Kotlin 99.7%

开源软件介绍(OpenSource Introduction):

Join the chat at https://kotlinlang.slack.com 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, html 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 / Continuous Integration | Creating a ruleset | a reporter | Badge | FAQ

Standard rules

  • annotation: 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
  • argument-list-wrapping: Argument list wrapping
  • chain-wrapping: When wrapping chained calls ., ?. and ?: should be placed on the next line
  • comment-spacing: The end of line comment sign // should be preceded and followed by exactly a space
  • enum-entry-name-case: Enum entry names should be uppercase underscore-separated names
  • filename: Files containing only one toplevel domain should be named according to that element.
  • final-newline: Newline at the end of each file (enabled by default) (set insert_final_newline=false in .editorconfig to disable (see EditorConfig section for more)).
  • import-ordering: Imports ordered consistently (see Custom ktlint EditorConfig properties for more)
  • indent: Indentation formatting - respects .editorconfig indent_size with no continuation indent (see EditorConfig section for more)
  • max-line-length: Ensures that lines do not exceed the given length of .editorconfig property max_line_length (see EditorConfig section for more). This rule does not apply in a number of situations. For example, in the case a line exceeds the maximum line length due to and comment that disables ktlint rules than that comment is being ignored when validating the length of the line. The .editorconfig property ktlint_ignore_back_ticked_identifier can be set to ignore identifiers which are enclosed in backticks, which for example is very useful when you want to allow longer names for unit tests.
  • modifier-order: Consistent order of modifiers
  • multiline-if-else: Braces required for multiline if/else statements
  • no-blank-line-before-rbrace: No blank lines before }
  • no-blank-lines-in-chained-method-calls: No blank lines in chained method expressions
  • no-consecutive-blank-lines: No consecutive blank lines
  • no-empty-class-body: No empty ({}) class bodies
  • no-empty-first-line-in-method-block: No leading empty lines in method blocks
  • no-line-break-after-else: Disallows line breaks after the else keyword if that could lead to confusion, for example:
    if (conditionA()) {
        doSomething()
    } else
    if (conditionB()) {
        doAnotherThing()
    }
  • no-line-break-before-assignment: When a line is broken at an assignment (=) operator the break comes after the symbol
  • no-multi-spaces: Except in indentation and in KDoc's it is not allowed to have multiple consecutive spaces
  • no-semi: No semicolons (unless used to separate multiple statements on the same line)
  • no-trailing-spaces: No trailing whitespaces
  • no-unit-return: No Unit returns (fun fn {} instead of fun fn: Unit {})
  • no-unused-imports: No unused imports
  • no-wildcard-imports: No wildcard imports expect imports listed in .editorconfig property ij_kotlin_packages_to_use_import_on_demand
  • package-name: No underscores in package names
  • parameter-list-wrapping: When class/function signature doesn't fit on a single line, each parameter must be on a separate line
  • string-template: Consistent string templates ($v instead of ${v}, ${p.v} instead of ${p.v.toString()})
  • trailing-comma: Consistent removal (default) or adding of trailing comma's (both on call and declaration site)

Spacing

  • annotation-spacing: Annotations should be separated by a single line break
  • colon-spacing: Consistent spacing around colon
  • comma-spacing: Consistent spacing around comma
  • curly-spacing: Consistent spacing around curly braces
  • dot-spacing: Consistent spacing around dots
  • double-colon-spacing: No spaces around ::
  • keyword-spacing: Consistent spacing around keywords
  • op-spacing: Consistent spacing around operators
  • paren-spacing: Consistent spacing around parenthesis
  • range-spacing: Consistent spacing around range operators
  • spacing-around-angle-brackets: No spaces around angle brackets
  • spacing-between-declarations-with-annotations: Declarations with annotations should be separated by a blank line
  • spacing-between-declarations-with-comments: Declarations with comments should be separated by a blank line
  • unary-op-spacing: No spaces around unary operators

Experimental rules

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

  • experimental:block-comment-initial-star-alignment: Lines in a block comment which (exclusive the indentation) start with a * should have this * aligned with the * in the opening of the block comment.
  • experimental:discouraged-comment-location: Detect discouraged comment locations (no autocorrect)
  • experimental:unnecessary-parentheses-before-trailing-lambda: An empty parentheses block before a lambda is redundant. For example some-string".count() { it == '-' }
  • function-signature: rewrites the function signature to a single line when possible (e.g. when not exceeding the max_line_length property) or a multiline signature otherwise. In case of function with a body expression, the body expression is placed on the same line as the function signature when not exceeding the max_line_length property. Optionally the function signature can be forced to be written as a multiline signature in case the function has more than a specified number of parameters (.editorconfig' property ktlint_function_signature_wrapping_rule_always_with_minimum_parameters`)

Spacing

  • experimental:fun-keyword-spacing: Consistent spacing after the fun keyword
  • experimental:function-return-type-spacing: Consistent spacing around the function return type
  • experimental:function-start-of-body-spacing: Consistent spacing before start of function body
  • experimental:function-type-reference-spacing: Consistent spacing in the type reference before a function
  • experimental:modifier-list-spacing: Consistent spacing between modifiers in and after the last modifier in a modifier list
  • experimental:nullable-type-spacing: No spaces in a nullable type
  • experimental:parameter-list-spacing: Consistent spacing inside the parameter list
  • experimental:spacing-between-function-name-and-opening-parenthesis: Consistent spacing between function name and opening parenthesis
  • experimental:type-parameter-list-spacing: Spacing after a type parameter list in function and class declarations

Wrapping

  • experimental:comment-wrapping: A block comment should start and end on a line that does not contain any other element. A block comment should not be used as end of line comment.
  • experimental:kdoc-wrapping: A KDoc comment should start and end on a line that does not contain any other element.

EditorConfig

Ktlint uses a limited set of .editorconfig properties for additional configuration. A sensible default value is provided for each property when not explicitly defined. Properties can be overridden, provided they are specified under [*.{kt,kts}]. Ktlint uses some properties defined by .editorconfig, IntelliJ IDEA and custom properties.

Disable rules

By default, no rules are disabled. The property disabled_rules holds a comma separated list (without spaces). Rules which are not defined in the standard ruleset have to be prefixed.

Example:

[*.{kt,kts}]
disabled_rules = some-standard-rule,experimental:some-experimental-rule,my-custom-ruleset:my-custom-rule

Trailing comma

Trailing comma's (both on call and declaration site) are disabled (e.g. not allowed) by. When enabling the properties, the trailing becomes mandatory where applicable.

Example:

[*.{kt,kts}]
ij_kotlin_allow_trailing_comma = false
ij_kotlin_allow_trailing_comma_on_call_site = false

Import layouts

By default, the same imports are allowed as in IntelliJ IDEA. The import path can be a full path, e.g. "java.util.List.*" as well as wildcard path, e.g. "kotlin.**".

The layout can be composed by the following symbols:

  • "*" - wildcard. There must be at least one entry of a single wildcard to match all other imports. Matches anything after a specified symbol/import as well.
  • "|" - blank line. Supports only single blank lines between imports. No blank line is allowed in the beginning or end of the layout.
  • "^" - alias import, e.g. "^android.*" will match all android alias imports, "^" will match all other alias imports.

Examples:

ij_kotlin_imports_layout=* # alphabetical with capital letters before lower case letters (e.g. Z before a), no blank lines
ij_kotlin_imports_layout=*,java.**,javax.**,kotlin.**,^ # default IntelliJ IDEA style, same as alphabetical, but with "java", "javax", "kotlin" and alias imports in the end of the imports list
ij_kotlin_imports_layout=android.**,|,^org.junit.**,kotlin.io.Closeable.*,|,*,^ # custom imports layout

Wildcard imports can be allowed for specific import paths (Comma-separated list, use "**" as wildcard for package and all subpackages). This setting overrides the no-wildcard-imports rule. This setting is best be used for allowing wildcard imports from libraries like Ktor where extension functions are used in a way that creates a lot of imports.

[*.{kt,kts}]
ij_kotlin_packages_to_use_import_on_demand = java.util.*,kotlinx.android.synthetic.**

Indent

By default, indenting is done with 4 spaces per indent level.

[*.{kt,kts}]
indent_size = 4 # possible values: number (e.g. 2), "unset" (makes ktlint ignore indentation completely)  
indent_style = space # or "tab"

Final newline

By default, a final newline is required at the end of the file.

[*.{kt,kts}]
insert_final_newline = true

Code style

By default, the offical Kotlin code style is applied. Alternatively, the code style can be set to android. Note that for the Android code style different default values might be applicable.

[*.{kt,kts}]
ktlint_code_style = official # Or "android"

Function signature

By default, the number of parameters in a function signature is not relevant when rewriting the function signature. Only the maximum line length determines when a function signature should be written on a single line or with multiple lines. This setting can be used, to force a multiline function signature in case the function contain at least a number of parameters even in case the function signature would fit on a single line.

[*.{kt,kts}]
ktlint_function_signature_rule_force_multiline_with_at_least_parameters= -1 # -1 to ignore the number of parameters or otherwise a positive number

Ignore identifiers enclosed in backticks

By default, the identifiers enclosed in backticks are not ignored.

According to https://kotlinlang.org/docs/reference/coding-conventions.html#names-for-test-methods it is acceptable to write method names in natural language. When using natural language, the description tends to be longer. This property allows lines containing an identifier between backticks to be longer than the maximum line length. (Since 0.41.0)

@Test
fun `Given a test with a very loooooooooooooooooooooong test description`() {
    
}
[*.{kt,kts}]
ktlint_ignore_back_ticked_identifier = false

Max line length

By default, the maximum line length is not set. The android code style sets the max line length to 100 (per Android Kotlin Style Guide).

[*.{kt,kts}]
max_line_length = -1 # Use "off" (or -1) to ignore max line length or a positive number to set max line length

IntelliJ IDEA .editorconfig autoformat issue

Unfortunately IntelliJ IDEA has .editorconfig autoformat issue that adds additional space into glob statements. For example, [*{kt,kts}] is formatted into [*{kt, kts}] (original ktlint issue). Such behaviour violates .editorconfig specification and leads to ignoring this section when ktlint is parsing it.

Overriding Editorconfig properties for specific directories

You could override properties for specific directories inside your project:

[*.{kt,kts}]
disabled_rules=import-ordering

# Note that in this case 'import-ordering' rule will be active and 'indent' will be disabled
[api/*.{kt,kts}]
disabled_rules=indent

Online demo

You can try ktlint online here using the standard or a custom ruleset without installing it to your PC.
To contribute or get more info, please visit the GitHub repository.

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.46.1/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:
    • (Releases up through 0.31.0) curl -sS https://keybase.io/shyiko/pgp_keys.asc | gpg --import && gpg --verify ktlint.asc
    • (Releases from 0.32.0 on) curl -sS https://keybase.io/ktlint/pgp_keys.asc | gpg --import && gpg --verify ktlint.asc

On macOS (or Linux) you can also use brew - brew install ktlint - or MacPorts - port install ktlint. On Arch Linux, you can install ktlint AUR.

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.

Command line usage

# Get help about all available commands
$ ktlint --help

# Check the style of all Kotlin files (ending with '.kt' or '.kts') inside the current dir (recursively).
# Hidden folders will be skipped.
$ ktlint
  
# Check only certain locations starting from the current directory.
#
# Prepend ! to negate the pattern, KtLint uses .gitignore pattern style syntax.
# Globs are applied starting from the last one.
#
# Hidden folders will be skipped.
# Check all '.kt' files in 'src/' directory, but ignore files ending with 'Test.kt':
ktlint "src/**/*.kt" "!src/**/*Test.kt"
# Check all '.kt' files in 'src/' directory, but ignore 'generated' directory and its subdirectories:
ktlint "src/**/*.kt" "!src/**/generated/**"

# 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, specifying report location. 
$ ktlint --reporter=plain --reporter=checkstyle,output=ktlint-report-in-checkstyle-format.xml

# Check against a baseline file.
$ ktlint --baseline=ktlint-baseline.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/pinterest/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.46.1</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 {
    mavenCentral()
}

configurations {
    ktlint
}

dependencies {
    ktlint("com.pinterest:ktlint:0.46.1") {
        attributes {
            attribute(Bundling.BUNDLING_ATTRIBUTE, getObjects().named(Bundling, Bundling.EXTERNAL))
        }
    }
    // 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
    mainClass.set("com.pinterest.ktlint.Main")
    args "src/**/*.kt"
    // to generate report in checkstyle format prepend following args:
    // "--reporter=plain", "--reporter=checkstyle,output=${buildDir}/ktlint.xml"
    // to add a baseline to check against prepend following args:
    // "--baseline=ktlint-baseline.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
    mainClass.set("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

该文章已有0人参与评论

请发表评论

全部评论

热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap