Androidアプリのライブラリ依存関係をメンテナンスしてみた

2021/07/25

Androidアプリを長い間メンテナンスしていると、AndroidXへのマイグレーション、Firebase導入、メンテされなくなったライブラリの入れ替えなどで build.gradledependencies に手を入れる機会が増えてきます。

結果、ライブラリの依存関係がカオスになりがち。

この問題、前々から悩ましいと思っていつつ目を瞑っていたのですが、targetSdkVersion30対応でライブラリの見直しをしているアプリがいくつかあるので、これを期にライブラリ依存関係をメンテナンスすることにしました。

とは言え、手作業で検証してたらキリがないし正確にやりきる自信もありません。

こういうときはツールに頼るのが一番。ということでいくつか試してみたところ、 dependency-analysis-android-gradle-plugin がいい感じでした。と言うか、これしか上手くいかなかった……

使い方

自分は build.gradle を古い書式で使っているので、 公式サイトのwiki にある通り、rootの build.gradle で以下のように設定しました。

buildscript {
  repositories {
    mavenCentral()
  }
  dependencies {
    classpath "com.autonomousapps:dependency-analysis-gradle-plugin:${latest_version}"
  }
}

apply plugin: "com.autonomousapps.dependency-analysis"

公式サイト見るといろいろな使い方や設定ができるみたいなんですが、とりあえず buildHealth を実行すれば解析してくれます。

以下はとある自作アプリの実行結果です。

E:\AndroidStudio\Example>gradlew buildHealth
(snip)
> Task :buildHealth
Advice for root project
Looking good! No changes needed

Advice for project :app
Unused dependencies which should be removed:
- implementation("androidx.browser:browser:1.3.0")
- implementation("com.squareup.okhttp3:okhttp:4.9.0")
- implementation("com.google.firebase:firebase-analytics:19.0.0")
- implementation("androidx.exifinterface:exifinterface:1.3.2")

Transitively used dependencies that should be declared directly as indicated:
- implementation("javax.inject:javax.inject:1")
- implementation("androidx.coordinatorlayout:coordinatorlayout:1.1.0")
- implementation("androidx.core:core:1.5.0")

Dependencies which could be compile-only:
- compileOnly("androidx.annotation:annotation:1.2.0") (was implementation)

This build is composed of 1 individual projects, with an average complexity of 98.0 nodes and 287.0 edges. If you follow all of this advice, the resultant complexity will average 91.0 nodes and 251.0 edges.

See machine-readable report at E:\AndroidStudio\Example\build\reports\dependency-analysis\advice-holistic.json

BUILD SUCCESSFUL in 55s
90 actionable tasks: 90 executed
E:\AndroidStudio\Example>

こんな感じでアドバイスをしてくれます。便利!

と言うか、なぜ使っていない okhttp の依存関係が残っているんだ……

その他のツール

nebula-plugins/gradle-lint-plugin はNetflix製ということで真っ先に試したんですが、どうやらAndroidは非対応のようです。

could not get unknown property compileClasspathConfigurationName · Issue #342 でメンテナの方が

Internally we don’t use this plugin in android projects and we ourselves have extremely limited knowledge of android gradle features. Feel free to contribute a PR if you have ideas on how to resolve the issue.

とコメントしていて期待薄。

もうひとつ r-cohen/unused-dep も試しましたがこちらも上手くいかず。このツールはAndroid専用なんですが、 After two hours still doing the same. · Issue #1 を見る限りではメンテナンスが追い付いていないっぽいです。

ということで、現時点では dependency-analysis-android-gradle-plugin 一択なのかなー、という感じです。




関連(するかもしれない)記事


おススメ