I am starting to get deeper into Gradle by migrating one project I have From Maven 3.6.3 to Gradle 6.5.1.
I'm arriving at the stage where I have to build a War file in the impl module that is slightly customized: I rename the Jars in the lib folder, and include via an overlay (from a Jar built in the api module from the same project) some resources. The current Maven configuration is the following:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<outputFileNameMapping>@{groupId}@-@{artifactId}@-@{version}@.@{extension}@</outputFileNameMapping>
<webResources>
<resource>
<directory>src/main/webapp</directory>
</resource>
</webResources>
<overlays>
<!-- Include the OpenAPI spec -->
<overlay>
<groupId>com.project.rest</groupId>
<artifactId>api</artifactId>
<type>jar</type>
<includes>
<include>specs/</include>
</includes>
</overlay>
</overlays>
</configuration>
</plugin>
So I'm trying to come up with something similar for Gradle regarding the libraries renaming.
I saw in the documentation of the plugin that there is a rename
method in the plugin:
Renames a source file. The closure will be called with a single parameter, the name of the file. The closure should return a String object with a new target name. The closure may return null, in which case the original name will be used.
The issue is that is takes the name of file in parameter, whereas I would need (in order to mimic the outputFileNameMapping
option) to get the dependency so I could extract its metadata.
So I assume this is not the right option. Is there a way to achieve this with Gradle?
Thanks
The gradle war plugin has a number of configuration options, including archiveFileName (or archiveName on older versions of gradle). archiveFileName by default is set to: [archiveBaseName]-[archiveAppendix]-[archiveVersion]-[archiveClassifier].[archiveExtension]
This can be declared in the war {} block in your build.gradle. You should be able to do something like this:
war {
archiveFileName = "${project.group}-${project.name}-$archiveVersion.$archiveExtension"
}
For more on the available configuration options, see the War documentation
This will rename the war file itself.
If you want to rename contents of the war file instead, you can use the war.rootSpec.rename(), like so:
// make a copy of the implementation configuration that can be resolved so we can loop over it.
configurations {
implementationList {
extendsFrom implementation
canBeResolved true
}
}
war {
rootSpec.rename({ fileInWar ->
def returnValue = fileInWar
project.configurations.implementationList.resolvedConfiguration.resolvedArtifacts.each {
if (it.file.name == fileInWar) {
def depInfo = it.moduleVersion.id
print "$returnValue -> "
returnValue = "${depInfo.group}.${depInfo.name}-${depInfo.version}.${it.extension}"
println "$returnValue"
}
}
return returnValue
})
}
However, note that this will not resolve conflicts if you have duplicate dependencies.