Groovy script, grab ivy configuration
Published on 14 August 2019
The subject of the ticket is the configuration of a Gradle build script. I want to be able to use a Groovy script without referencing the Gradle project to which it is attached. I want to be able to run this Groovy script outside of Gradle without the Ivy annotations for external dependency retrieval causing performance or compilation issues for the Gradle build script. To illustrate the configuration, I am relying on two scripts: a Gradle build script and a Groovy script. At the beginning of the Groovy script, on line 2, there is an instruction to pull an external dependency using the Ivy dependency manager.
#!/usr/bin/env groovy
@Grab("commons-io:commons-io:2.6")
import org.apache.commons.io.FileUtils
static String getSeparator() {
System.getProperty("file.separator")
}
String from = "${System.getProperty("user.home")}${separator}.config${separator}transmission${separator}torrents"
String to = "${System.getProperty("user.home")}${separator}Documents${separator}torrents_completed"
File fromDlDir = new File("${System.getProperty("user.home")}${separator}Téléchargements")
File fromDir = new File(from)
File toDir = new File(to)
Collection<File> torrentFiles = FileUtils.listFiles(
fromDir,
["torrent"] as String[],
false)
torrentFiles.addAll(FileUtils.listFiles(
fromDlDir,
["torrent", "torrent.added"] as String[],
false))
torrentFiles.empty ?: torrentFiles.each { it ->
FileUtils.copyFileToDirectory(it, toDir)
}
println torrentFiles.size()
In the build.gradle file, let’s now see how to harmonize the two dependency managers, Ivy and Gradle. The alignment between the two is handled on lines 26, 30, 37, 38, and 39. This way, I can run my Groovy script manually, and the Gradle compilation is not hindered by @Grab. The dependencies for the Groovy script do not need to be provided in Gradle. On the other hand, I cannot run the Groovy script from Gradle.
plugins {
id "java"
id "groovy"
}
repositories {
mavenCentral()
jcenter()
}
sourceSets {
main {
java { srcDirs = [] }
groovy { srcDirs =["src/main/java", "src/main/groovy"] }
resources {
srcDirs =["src/main/resources"]
}
}
test {
java { srcDirs = [] }
groovy { srcDirs =["src/test/java", "src/test/groovy"] }
}
}
configurations {
ivy
}
dependencies {
ivy "org.apache.ivy:ivy:$ivy_version"
implementation "org.codehaus.groovy:groovy-all:$groovy_version"
}
tasks.withType(GroovyCompile) {
groovyClasspath += configurations.ivy
}
ticket reference onhttps://stackoverflow.com/a/18174033/837404[stackoverflow]