dropbox / dependency-guard

A Gradle plugin that guards against unintentional dependency changes.
Apache License 2.0
390 stars 14 forks source link

Add Gradle Init Script to Documentation? #106

Open handstandsam opened 5 months ago

handstandsam commented 5 months ago

The configuration phase to appropriately run dependency-guard is very expensive. An alternate option to having it "always installed" is to run it via a Gradle init script.

In this example, it will run the dependencyGuardBaseline tasks for all projects that have the plugin applied. The code iterates through all projects and only applies it to those who are com.android.library or com.android.application. This can be modified as desired.

dependency-guard.gradle

/**
 * Gradle init-script which applies the plugin to existing Gradle projects.
 *
 * Run it with the following:
 * ./gradlew --init-script dependency-guard.gradle dependencyGuardBaseline
 */
settingsEvaluated {
  rootProject {
    buildscript {
      repositories {
        mavenCentral()
        gradlePluginPortal()
        google()
        mavenLocal()
      }

      dependencies {
        classpath("com.dropbox.dependency-guard:dependency-guard:0.4.3")
      }
    }
    afterEvaluate {
      allprojects {
        project.afterEvaluate {
          // filtering for android library and app plugins in this case, but you could change this logic as needed.
          if (plugins.findPlugin("com.android.library") != null || plugins.findPlugin("com.android.application") != null) {
            plugins.apply("com.dropbox.dependency-guard")
            dependencyGuard {
              configuration("debugRuntimeClasspath") {
                modules = true
              }
            }
          }
        }
      }
    }
  }
}

I can then just run ./gradlew --init-script dependency-guard.gradle dependencyGuardBaseline

Additionally I can target a project specifically with./gradlew --init-script dependency-guard.gradle :app:dependencyGuard if desired. (to avoid configuring all projects when configuration on demand is enabled)