すきま風

勉強したことのメモとか

ktlintをGradleに導入する

Gradle projectにKotlinの静的解析ツールktlintを設定します。
コードには以前記事にしたプロジェクトを利用します。

ソフトウェアバージョン

software version
OS MacOS Mojave
Spring Boot 2.2.0.M5
Java Corretto-11.0.4.11.1
Kotlin 1.3.50
Gradle 5.6.1
ktlint 0.34.2

build.gradleに依存とタスクを追加

公式を参考にbuild.gradleにコードを追加します。 argsの部分を自分のプロジェクトに合わせればOKです。
(plugin利用が推奨されていますが、勉強不足のためかmulti-project構成だといい感じに動作しなかったので、build.gradleにtaskを追加する方法を利用しています)

https://github.com/pinterest/ktlint#without-a-plugin

// 前略

plugins {
    id 'java'
    id 'org.springframework.boot' version '2.2.0.M5' apply false
    id 'org.jetbrains.kotlin.jvm' version '1.3.50'
    // .. 以下略
}

repositories {
    mavenCentral()
    jcenter()  // 追加
}

configurations {
    ktlint
}

dependencies {
    ktlint "com.pinterest:ktlint:0.34.2"
}

// 中略

task ktlint(type: JavaExec, group: "verification") {
    description = "Check Kotlin code style."
    classpath = configurations.ktlint
    main = "com.pinterest.ktlint.Main"
    args "adapters/**/*.kt", "applicatiohn/**/*.kt", "configuration/**/*.kt", "domain/**/*.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", "adapters/**/*.kt", "applicatiohn/**/*.kt", "configuration/**/*.kt", "domain/**/*.kt"
}

設定完了するとgradle taskにktlintが追加され、駄目な子がいるとちゃんと叱ってくれるようになります。

カスタマイズする

ktlintは.editorconfigでcustomizeできます。 IntelliJとKtlintにはimportの順番で差異があるようなのでimport-orderingを設定しています。

https://github.com/pinterest/ktlint#custom-editorconfig-properties

root = true

[*]
indent_style = space
indent_size = 2
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
end_of_line = lf
max_line_length = off

[*.{java,kt,gradle}]
indent_size = 4

# ktlint rules
disabled_rules = import-ordering

これで以下のチェックをスルーしてくれるようになります。

> Task :ktlint FAILED
/demo/domain/src/main/kotlin/com/example/demo/domain/entity/cart/Cart.kt:3:1: Imports must be ordered in lexicographic order without any empty lines in-between

IntelliJにktlintを適用する。

ktlintをIntelliJ projectに適用すると 適切にフォーマットしてくれたり不要インポートなどをエラーとして認識してくれたりするようになります。

https://ktlint.github.io/ https://github.com/pinterest/ktlint#option-1-recommended

# project rootで実行
$ ktlint --apply-to-idea-project

The following files are going to be updated:

    ./.idea/codeStyles/codeStyleConfig.xml
    ./.idea/codeStyles/Project.xml
    ./.idea/inspectionProfiles/profiles_settings.xml
    ./.idea/inspectionProfiles/ktlint.xml
    ./.idea/workspace.xml

Do you wish to proceed? [y/n]
(in future, use -y flag if you wish to skip confirmation)

実行後、IntelliJを再起動すると適用されます。