1
3

Android: ビルド時にktlintFormatが実行されるようにする

Last updated at Posted at 2024-07-11

n番煎じではありますが2024年時点のAndroidプロジェクト向けの記録を残しておきます。

:white_check_mark: Kotlin
:white_check_mark: Jetpack Compose
:white_check_mark: Gradle バージョン カタログ (libs.versions.toml)
:white_check_mark: Kotlin DSL (buid.gradle.kts)

Dependenciesの追加と設定

ktlint gradle pluginを導入します。
ついでにcompose向けのlint checkも入れておきます。
ライブラリやプラグインのバージョンは公式サイトで最新を調べて設定します。

libs.versions.toml
[libraries]
compose-lint-checks = { module = "com.slack.lint.compose:compose-lint-checks", version = "1.3.1" }

[plugins]
gradle-ktlint = { id = "org.jlleitschuh.gradle.ktlint", version = "12.1.1" }
build.gradle.kts
plugins {
    ...
    alias(libs.plugins.gradle.ktlint) apply false
}
app/build.grdle.kts
plugins {
    ...
    alias(libs.plugins.gradle.ktlint)
}


android {
    // ktlint configuration
    // see: https://github.com/JLLeitschuh/ktlint-gradle?tab=readme-ov-file#configuration
    ktlint {
        android.set(true)
    }
}

ktlintの設定ファイルをプロジェクトルートに作成します。

Compose名が小文字で始まっていると怒られるので@Composableアノテーションがついているfunctionの名前チェックをスキップする設定を入れておきます。

.editorconfig
root=true
[*.{kt,kts}]
ktlint_function_naming_ignore_when_annotated_with=Composable

gradle syncするとktlintFormatを含むktlintのgradleタスクが追加されます。
ktlintFormatを実行する準備が整いました。

コマンドラインから実行

$ ./gradlew ktlintFormat

AndroidStudioのgradleパネルから実行
スクリーンショット 2024-07-12 0.57.38.png

gradle タスクにktlintFormatを追加

次にpreBuildにktlintFormatタスクを登録します。

app/build.gradle.kts
import com.android.build.gradle.internal.tasks.factory.dependsOn

android {
    ...
    project.tasks.preBuild.dependsOn("ktlintFormat")
}

これでビルド時にktlintFormatが実行されるようになりました :tada:

1
3
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
1
3