In my gradle project I have libs directory, which contains one jar file. I created gradle tasks, one is downloading from jenkins new jar version, and save in build direcotry, delete old jar.
Then I have two tasks to copy and update properties file:
Copy:
task copyJar(type: Sync) {
from 'build'
into 'libs'
include '*.jar'
}
Update:
task('updateJar') {
fileTree("libs").
def files = fileTree("libs").filter { it.isFile() }.files.name
if(!files.size() ==1) {
throw new GradleException('Error occured - In the libs folder, should be only one JAR file!')
}
def newJarFileName = files.first()
def newSDKVersion = newJarFileName.substring(0,newJarFileName.lastIndexOf('.'))
println newSDKVersion
def versionPropsFile = file('version.properties')
Properties versionProps = new Properties()
versionProps.load(new FileInputStream(versionPropsFile))
versionProps['VERSION_SDK'] = newSDKVersion
versionProps.store(versionPropsFile.newWriter(), null)
}
and both tasks work, but updateJar still sees that old jar file. Any possibility to reload/refresh what libs direcotry contains? How force gradle to do it, any default task?
1 Answer 1
You need to register the libs directory as a task input to the updateJar task. This lets gradle know that the outputs of the updateJar task depend on the contents of the libs directory (this is automatically done in the case of the copyAar task because it accesses its inputs declaratively. The updateJar task is programmatic, so gradle can't figure it out automatically).
Adding the following inside the updateJar task definition will do the trick:
inputs.dir('libs')
You may also notice that gradle skips the task when the libs directory isn't changed, because the inputs and outputs settings also control caching.
Note that in your specific example above, there is another issue: the updateJar task is doing work at configuration time, not at task execution time. This has a number of bad effects, such as incremental caching of work isn't possible, the updateJar task doing work even if it isn't executed.
This can be fixed by wrapping the part that does work in a doFirst {} block.
Put all of this together, and the task definition would look like this:
task('updateJar') {
doFirst {
def files = fileTree("libs").filter { it.isFile() }.files.name
if(!files.size() ==1) {
throw new GradleException('Error occured - In the libs folder, should be only one JAR file!')
}
def newJarFileName = files.first()
def newSDKVersion = newJarFileName.substring(0,newJarFileName.lastIndexOf('.'))
println newSDKVersion
def versionPropsFile = file('version.properties')
Properties versionProps = new Properties()
versionProps.load(new FileInputStream(versionPropsFile))
versionProps['VERSION_SDK'] = newSDKVersion
versionProps.store(versionPropsFile.newWriter(), null)
}
inputs.dir('libs')
}
3 Comments
./gradlew copyTxt updateTxt in console you will see: 0-text2.txt but it should be 0-text1.txt, which you can see in files structure.