5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Gradle】ビルド時にktlint(に限らずタスク類)を走らせる【Kotlin】

Posted at

やること

Kotlinのプロジェクトで、compileKotlin時にktlintを走らせます。
また、環境変数によって実行結果を分けます。

build.gradleKotlin-DSLで書きます。

準備: ktlintの導入

以下のように行いました。

build.gradle.kts
plugins {

    /* 略 */

    id("org.jlleitschuh.gradle.ktlint") version "9.2.1"
}

やりかた

以下のように、compileKotlinタスクにdependsOnktlintの実行を指定してやればできます。
サンプルではビルド前にフォーマッティングまでやっています。

build.gradle.kts
tasks.compileKotlin {
    dependsOn("ktlintFormat")
    kotlinOptions {
        jvmTarget = "1.8"
    }
}

応用

環境変数を使って「ローカルでは自動修復してエラー無しで続行、CI環境ではエラー」というように動作を分けることもやってみました。

build.gradle.kts
tasks.compileKotlin {
    val lintOption: String = if (System.getenv("IS_CI")?.toBoolean() == true) {
        "ktlintCheck" // CI環境ならチェック(失敗すると落ちる)
    } else {
        "ktlintFormat" // CI環境じゃなければfix(自動修正を走らせる)
    }

    dependsOn(lintOption)
    kotlinOptions {
        jvmTarget = "1.8"
    }
}

参考にさせて頂いた記事

5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?