Search code examples
javagradlegradlew

gradle: tar task not creating a tar.gz


Hi I have a tar task that I made after looking at numerous methods and some SO posts.

task buildDist(type: Tar, dependsOn: jar) {
  print 'here'
  archiveName = 'xyz-' + version
  destinationDir = file('build/dist')
  extension = 'tar.gz'
  compression = Compression.GZIP

  from 'build/libs'
  include 'xyz.jar'
}
buildDist.mustRunAfter jar

I have the java plugin applied and the jar task makes the xyz.jar file available under build/libs. The build/dist directory does not exist yet, but I tried new File("build/dist") as well. That did not work either - I even pointed it to the build directory that exists - doesn't work. I run the entire script with /gradlew clean build. The print in the above code does print.


Solution

  • I am making a few assumptions here as you didn't post the output from running Gradle.

    The build task is just a normal Gradle task that doesn't do anything by itself. Instead, it depends on other tasks. If you create your own custom task and you like to have it included when executing build, you have to add a dependency to it. If this is not the problem and you have actually done this, please give some more details as to what makes it "not work" when you run build.

    If you want to test your task in isolation (e.g. to make sure it works correctly without running unit tests or whatever else that is unrelated), just run gradlew cleanBuildDist buildDist.

    A note about the 'print' statement - it executes doing the configuration phase, but this doesn't mean you can use it to test if the task actually executes. In fact, it will most likely print no matter what task you execute. If you wanted to print something on execution time, you would have to put it in a doLast block.

    There is a few other things you should change as well:

    • It is not a good practice to use relative references. Instead, use the buildDir property to get an absolute reference to the build directory.
    • Don't use deprecated methods like archiveName and destinationDir. Use archiveFileName and destinationDirectory instead.
    • The extension property is also deprecated, but it is ignored if you set the full name of the archive yourself. So just remove it. This also means you are missing the extension on the full name.
    • The from and include is a little fragile. Just use from jar.archivePath if you only want to gzip your application jar.

    Example:

    task buildDist(type: Tar, dependsOn: jar) {
      archiveFileName = "${jar.baseName}-${version}.tar.gz"
      destinationDirectory = file("$buildDir/dist")
      compression = Compression.GZIP
      from jar.archivePath
    }
    
    build.dependsOn buildDist
    

    Lastly, if your intention is to create a distribution of your application that is runnable on its own (with all required dependencies), you should consider using the distribution plugin and perhaps also the application plugin.