Grails Programmer : How to customize the war name generated by "grails war" command?

$ grails --version
| Grails Version: 3.1.1
| Groovy Version: 2.4.5
| JVM Version: 1.8.0_45
$ grails create-app myapp
| Application created at /Users/sdelamo/Documents/test/myapp

If I run:

$ cd my app
$ grails war
| Built application to build/libs using environment: production

Note how the grails war command uses by default the production environment. See the generated output:

$ ls -la build/libs
total 235648
drwxr-xr-x   4 softamo  staff       136 Feb 20 17:30 .
drwxr-xr-x  13 softamo  staff       442 Feb 20 17:30 ..
-rw-r--r--   1 softamo  staff  63561794 Feb 20 17:30 myapp-0.1.war
-rw-r--r--   1 softamo  staff  57083136 Feb 20 17:30 myapp-0.1.war.original

I can explicitly tell the command to use a different environment

$ cd my app
$ grails -Dgrails.env=test war
| Built application to build/libs using environment: test

The generated war file uses the same naming:

$ ls -la build/libs
total 235648
drwxr-xr-x   4 softamo  staff       136 Feb 20 17:32 .
drwxr-xr-x  13 softamo  staff       442 Feb 20 17:30 ..
-rw-r--r--   1 softamo  staff  63561790 Feb 20 17:32 myapp-0.1.war
-rw-r--r--   1 softamo  staff  57083132 Feb 20 17:32 myapp-0.1.war.original

I want to change the default naming slightly. I want to add the environment to the name. When the user does not pass an environment, the name should reflect the production environment; the default environment.

It is easy to achieve. Just add the next two lines to the bottom of your build.gradle (or at least after apply plugin 'war')

String env = System.getProperty('grails.env') ?: 'prod'
war.baseName "${rootProject.name}-${env}"

And voila:

$ grails clean;grails -Dgrails.env=test war
| Built application to build/libs using environment: test
$ ls -la build/libs
total 471296
drwxr-xr-x   6 softamo  staff       204 Feb 20 17:37 .
drwxr-xr-x  13 softamo  staff       442 Feb 20 17:30 ..
-rw-r--r--   1 softamo  staff  63561790 Feb 20 17:37 myapp-test-0.1.war
-rw-r--r--   1 softamo  staff  57083132 Feb 20 17:37 myapp-test-0.1.war.original

droggo, a user in the Grails Slack channel pointed me to this solution.

Tags: #grails