M. Justin
M. Justin

Reputation: 21114

Does Gradle provide a way to add a task without including it in the build script?

I have a few custom Gradle tasks I've created perform analysis on the build, which I'll make use of when doing certain types changes (e.g. viewing changes in included dependencies as I upgrade library versions). These are tasks for my own benefit, and not something I want committed to source control. Therefore, I ideally want them specified externally to build.gradle and included in a manner that does not require changing any of the committed build files. Otherwise, the custom tasks will undoubtably be accidentally included in a commit and will need to be backed out later.

To make it concrete, here's a simplified version of a task which prints all compile-time dependencies:

task dependencyList {
    doLast {
        println "Compile dependencies:"
        def selectedDeps = project.configurations.compileClasspath.incoming.resolutionResult.allDependencies.collect { dep ->
            "${dep.selected}"
        }
        selectedDeps.unique().sort().each { println it }
    }
}

How can I execute this task against my Gradle build without making any changes to build.groovy or other files that would normally be committed to source control with the project?

Upvotes: 2

Views: 1479

Answers (1)

M. Justin
M. Justin

Reputation: 21114

An initialization script can be used for this purpose, adding the custom task to the project(s) in the build:

allprojects {
    task dependencyList {
        doLast {
            println "Compile dependencies:"
            def selectedDeps = project.configurations.compileClasspath.incoming.resolutionResult.allDependencies.collect { dep ->
                "${dep.selected}"
            }
            selectedDeps.unique().sort().each { println it }
        }
    }
}

Gradle provides a number of ways to use the initialization script, which are listed in the feature's documentation:

  • Specify a file on the command line. The command line option is -I or --init-script followed by the path to the script. [...]
  • Put a file called init.gradle (or init.gradle.kts for Kotlin) in the USER_HOME/.gradle/ directory.
  • Put a file that ends with .gradle (or .init.gradle.kts for Kotlin) in the USER_HOME/.gradle/init.d/ directory.
  • Put a file that ends with .gradle (or .init.gradle.kts for Kotlin) in the GRADLE_HOME/init.d/ directory, in the Gradle distribution. [...]

For a task which should only be present in the build on demand, the --init-script command line option would be the option to use.

gradle --init-script /path/to/dependency-list.gradle dependencyList

Upvotes: 3

Related Questions