Customise distZip to change root directory name

I’m using distZip to produce a zipped distribution of my project. The current task creates a zip file with a single directory at the root called MyProject-version. Is there a way to change this to MyProject? (i.e. lose the trailing version number)

Thanks

See https://docs.gradle.org/current/dsl/org.gradle.api.tasks.bundling.Zip.html

archiveName = '[baseName].[extension]'

Thanks for your reply.

Changing archiveName appears to set both the zipfile’s name and the internal root directory. I was hoping to keep the zipfile versioned and the internal root directory not. Is this possible?

Sorry, I misunderstood you. I assume you using distZip from application or distribution plugins?

That might be a bit harder due to the way the copySpec is created when the plugin is applied. I have not tested the following, but maybe that works for you.

into('MyProject') {
  distributions.main.contents
}

A simple workaround would be to set the archiveName to be what you want the internal root to be named, and then change the archive file name in a doLast at the end.

Thanks, I took the approach of renaming the archive in a doLast like so:

distZip {
  //The target zipfile name should be versioned but 
  //internal root directory not. By default the distZip
  //task uses the same property (archiveName) for
  //both. To workaround, suppress the version in
  //the archiveName property (by setting version = null)
  //then, once the task is complete, we rename the
  //zip as a post-processing step to add the version
  //back on.

  //note that archivePath is a derived property.
  //its return value is sensitive to the version
  //property (among others).

  def versionedPath = archivePath
  version = null
  doLast {
    archivePath.renameTo(versionedPath)
  }
}

I’m not a huge fan of this approach since it relies on mutating external variables to infer the archive name, but it seems to be the simplest/most generic. It would be nicer to have a way of just configuring these values once.

Does that not cause your task to always be out of date?

1 Like