grails <<command name>>
5 The Command Line
Version: 6.2.3
Table of Contents
5 The Command Line
Grails 3.0’s command line system differs greatly from previous versions of Grails and features APIs for invoking Gradle for build related tasks, as well as performing code generation.
When you type:
Grails searches the profile repository based on the profile of the current application. If the profile is for a web application then commands are read from the web profile and the base profile which it inherits from.
Since command behavior is profile specific the web profile may provide different behavior for the run-app
command then say a profile for running batch applications.
When you type the following command:
grails run-app
It will first search the application, and then the profile for commands:
To get a list of all commands and some help about the available commands type:
grails help
which outputs usage instructions and the list of commands Grails is aware of:
grails <<environment>>* <<target>> <<arguments>>*'
| Examples:
$ grails dev run-app
$ grails create-app books
| Available Commands (type grails help 'command-name' for more info):
| Command Name Command Description
----------------------------------------------------------------------------------------------------
clean Cleans a Grails application's compiled sources
compile Compiles a Grails application
...
Refer to the Command Line reference in the Quick Reference menu of the reference guide for more information about individual commands |
Arguments
The grails
command is a front to a gradle
invocation, because of this there can be unexpected side-effects.
For example, when executing grails -Dapp.foo=bar run-app
the app.foo
system property won’t be available to your application. This is because bootRun
in your build.gradle
configures the system properties.
To make this work you can simply append all System.properties
to bootRun
in build.gradle
like:
bootRun{
systemProperties System.properties // Please note not to use '=', because this will override all configured systemProperties. This will append them.
}
Or if you only want to pass through a limited set, you can prefix your system properties using an arbitrary prefix and configure bootRun
like:
bootRun{
bootRun {
systemProperties System.properties.inject([:]){acc,item-> item.key.startsWith('boot.')?acc << [(item.key.substring('boot.'.length())):item.value]:acc }
}
}
In this example only system properties starting with boot.
are passed through.
Application and JVM arguments should be specified in bootRun
as well.
bootRun{
bootRun {
jvmArgs('-Dspring.output.ansi.enabled=always')
args('--app.foo=bar','--app.bar=foo') // Override the `app.foo` and `app.bar` config options (`grailsApplication.config`)
}
}
non-interactive mode
When you run a script manually and it prompts you for information, you can answer the questions and continue running the script. But when you run a script as part of an automated process, for example a continuous integration build server, there’s no way to "answer" the questions. So you can pass the \--non-interactive
switch to the script command to tell Grails to accept the default answer for any questions, for example whether to install a missing plugin.
For example:
grails war --non-interactive
The Grails Forge New Command-Line Interface (CLI) has undergone significant changes compared to its previous versions, primarily focusing on code generation. One notable alteration is the removal of APIs for invoking Gradle for tasks related to building using Gradle Tooling APIs. This shift in responsibility aligns with the framework’s evolution and its integration with the Gradle build system.
Accessing the Grails CLI
The Grails CLI (Command Line Interface) can be swiftly and effortlessly accessed by simply typing the following command into your terminal or command prompt:
grails
This command allows developers to quickly initiate the Grails CLI and begin working with the framework, making it an easy entry point for those looking to start their Grails projects.
The New Grails CLI! is the preferred method for initiating new Grails projects. This command-line interface offers various options for creating projects, enabling you to select your preferred build tools, test frameworks, GORM implementation, and more. Additionally, the CLI provides commands for generating essential components like controllers and domain classes.
The Grails Forge Website
You can also begin your Grails application without the need to install the Grails CLI by visiting the Grails Forge website. This web-based platform allows you to initiate Grails projects conveniently, bypassing the installation of the CLI.
Understanding the New Grails Command-line Interface (CLI)
Once the Grails CLI has been successfully installed, you can activate it using the "grails" command. For example:
grails create-app myapp
A Grails framework CLI project is recognizable by the presence of the "grails-cli.yml" file, which is automatically generated at the project’s root if it was created using the CLI. This file contains information about the project’s profile, default package, and other variables.
Here is an example of a "grails-cli.yml" configuration for a default Grails web application:
applicationType: web
defaultPackage: com.example
testFramework: spock
sourceLanguage: groovy
buildTool: gradle
gormImpl: gorm-hibernate5
servletImpl: spring-boot-starter-tomcat
features:
- app-name
- asset-pipeline-grails
- base
- geb
- gorm-hibernate5
- gradle
- grails-application
- grails-console
- grails-dependencies
- grails-gorm-testing-support
- grails-gradle-plugin
- grails-gsp
- grails-url-mappings
- grails-web
- grails-web-testing-support
- h2
- logback
- micronaut-inject-groovy
- readme
- scaffolding
- spock
- spring-boot-autoconfigure
- spring-boot-starter
- spring-boot-starter-tomcat
- yaml
This "grails-cli.yml" configuration sets the default values for various aspects of the Grails web application, including the application type, default package, test framework, source language, build tool, GORM implementation, servlet implementation, and a list of enabled features.
Grails Default Package Configuration
The project’s default package is determined based on the project’s name. For instance, running the following command:
grails create-app myapp
Will set the default package to myapp
.
If you wish to specify your own default package when creating the application, you can do so by prefixing the application name with the package like this:
grails create-app com.example.myapp
In this case, "com.example" becomes the default package for your project.
Gradle Build Tool
Grails now utilizes the Gradle Build System for project management. The project’s build configuration is specified in the build.gradle
file, where you define critical aspects of your project such as its version, required dependencies, and the repositories from which these dependencies should be sourced. Here’s an example of how this is done:
plugins {
id 'org.grails.grails-web' version 'x.y.z' // Grails plugin
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter'
implementation 'org.grails:grails-core'
// Add more dependencies as needed...
}
grails {
pathingJar = true
}
Utilizing Gradle Build Tool
To interact with your Grails project and perform various tasks related to building and running it, you should employ Gradle commands. Here are a few examples:
-
Building the Grails application:
gradle build
-
Running the Grails application:
gradle bootRun
-
Listing available Gradle tasks:
gradle tasks
By invoking these Gradle commands, you can effectively manage your Grails application’s lifecycle.
It is important to remember that Grails leverages the power of Gradle for streamlined project management, including build automation and dependency resolution. This approach allows for greater flexibility and control over your Grails projects.
5.1 Interactive Mode
Interactive mode is a feature of the Grails command line which keeps the JVM running and allows for quicker execution of commands. To activate interactive mode type 'grails' at the command line and then use TAB completion to get a list of commands:
If you need to open a file whilst within interactive mode you can use the open
command which will TAB complete file paths:
Even better, the open
command understands the logical aliases 'test-report' and 'dep-report', which will open the most recent test and dependency reports respectively. In other words, to open the test report in a browser simply execute open test-report
. You can even open multiple files at once: open test-report test/unit/MyTests.groovy
will open the HTML test report in your browser and the MyTests.groovy
source file in your text editor.
TAB completion also works for class names after the create-*
commands:
If you need to run an external process whilst interactive mode is running you can do so by starting the command with a !:
Note that with ! (bang) commands, you get file path auto completion - ideal for external commands that operate on the file system such as 'ls', 'cat', 'git', etc.
To exit interactive mode enter the exit
command. Note that if the Grails application has been run with run-app
normally it will terminate when the interactive mode console exits because the JVM will be terminated. An exception to this would be if the application were running in forked mode which means the application is running in a different JVM. In that case the application will be left running after the interactive mode console terminates. If you want to exit interactive mode and stop an application that is running in forked mode, use the quit
command. The quit
command will stop the running application and then close interactive mode.
With Grails Forge, when you execute the grails
command without any arguments, the Grails Command Line Interface (CLI) enters interactive mode. In this mode, it functions like a shell, allowing you to run multiple CLI commands without the need to re-initialize the CLI runtime. This mode is particularly useful when working with code-generation commands (such as create-controller
), creating multiple projects, or exploring various CLI features.
One of the advantages of interactive mode is the availability of tab-completion. You can simply press the TAB key to view possible options for a given command or flag. Here’s an example of the available options in interactive mode:
grails>
--help --verbose -V -v create-app create-domain-class create-restapi create-webapp
--stacktrace --version -h -x create-controller create-plugin create-web-plugin
Help and Information
You can access general usage information for Grails commands using the help flag associated with a specific command.
grails> create-app -h
Usage: grails create-app [-hivVx] [--list-features] [-g=GORM Implementation] [--jdk=<javaVersion>]
[-s=Servlet Implementation] [-t=TEST] [-f=FEATURE[,FEATURE...]]... [NAME]
Creates an application
[NAME] The name of the application to create.
-f, --features=FEATURE[,FEATURE...]
The features to use. Possible values: h2, scaffolding, gorm-hibernate5,
spring-boot-starter-jetty, springloaded, spring-boot-starter-tomcat,
micronaut-http-client, cache-ehcache, hibernate-validator, postgres,
mysql, cache, database-migration, grails-gsp, hamcrest, gorm-mongodb,
assertj, mockito, spring-boot-starter-undertow, micronaut-inject-groovy,
github-workflow-java-ci, jrebel, testcontainers, sqlserver,
grails-console, views-markup, asset-pipeline-grails, views-json,
gorm-neo4j, asciidoctor, embedded-mongodb, grails-web-console,
logbackGroovy, mongo-sync, shade, geb, properties
-g, --gorm=GORM Implementation
Which GORM Implementation to configure. Possible values: hibernate,
mongodb, neo4j.
-h, --help Show this help message and exit.
-i, --inplace Create a service using the current directory
--jdk, --java-version=<javaVersion>
The JDK version the project should target
--list-features Output the available features and their descriptions
-s, --servlet=Servlet Implementation
Which Servlet Implementation to configure. Possible values: none, tomcat,
jetty, undertow.
-t, --test=TEST Which test framework to use. Possible values: junit, spock.
-v, --verbose Create verbose output.
-V, --version Print version information and exit.
-x, --stacktrace Show full stack trace when exceptions occur.
You can also obtain a list of available features by using the --list-features flag with any of the create commands.
grails> create-app --list-features
Available Features
(+) denotes the feature is included by default
Name Description
---------------------------------- ---------------
CI/CD
github-workflow-java-ci [PREVIEW] Adds a Github Actions Workflow to Build and Test Grails Application
Cache
cache The Grails Cache plugin provides powerful and easy to use caching functionality to Grails applications and plugins.
cache-ehcache The Grails Cache Ehcache plugin extends the Cache plugin and uses Ehcache as the storage provider for cached content.
Client
micronaut-http-client Adds support for the Micronaut HTTP client
Configuration
properties Creates a properties configuration file
Database
database-migration Adds support for Liquibase database migrations. The Database Migration plugin helps you manage database changes while developing Grails applications.
embedded-mongodb Executes an embedded mongo database for integration or functional testing
gorm-hibernate5 (+) Adds support for Hibernate5 using GORM
gorm-mongodb Configures GORM for MongoDB for Groovy applications
gorm-neo4j Configures GORM for Neo4j for Groovy applications
h2 (+) Adds the H2 driver and default config
mongo-sync Adds support for the MongoDB Synchronous Driver
mysql Adds the MySQL driver and default config
postgres Adds the PostgresSQL driver and default config
sqlserver Adds the SQL Server driver and default config
testcontainers Use Testcontainers to run a database or other software in a Docker container for tests
Development Tools
assertj AssertJ fluent assertions framework
hamcrest Hamcrest matchers for JUnit
jrebel Adds support for class reloading with JRebel (requires separate JRebel installation)
springloaded Adds support for class reloading with Spring Loaded
Documentation
asciidoctor Adds support for creating Asciidoctor documentation
Logging
logbackGroovy Gives you the ability to use groovy to configure logback instead of XML.
Management
grails-web-console A web-based Groovy console for interactive runtime application management and debugging
Other
geb (+) This plugins configure Geb for Grails framework to write automation tests.
grails-console (+) Starts the Grails console, which is an extended version of the regular Groovy console.
micronaut-inject-groovy (+) micronaut-inject-groovy
scaffolding (+) The GrailsĀ® framework Scaffolding plugin replicates much of the functionality from Grails 2, but uses the fields plugin instead.
Packaging
shade Adds the ability to build a Fat/Shaded JAR
Server
spring-boot-starter-jetty spring-boot-starter-jetty
spring-boot-starter-tomcat (+) spring-boot-starter-tomcat
spring-boot-starter-undertow spring-boot-starter-undertow
Validation
hibernate-validator Adds support for the Hibernate Validator
mockito Mockito test mocking framework for JUnit
View Rendering
asset-pipeline-grails (+) The Asset-Pipeline is a plugin used for managing and processing static assets in JVM applications primarily via Gradle (however not mandatory). Read more at https://github.com/bertramdev/asset-pipeline
grails-gsp (+) grails-gsp
views-json JSON views are written in Groovy, end with the file extension gson and reside in the grails-app/views directory. They provide a DSL for producing output in the JSON format.
views-markup Markup views are written in Groovy, end with the file extension gml and reside in the grails-app/views directory. They provide a DSL for producing output in the XML.
5.2 Creating Custom Scripts
You can create your own Command scripts by running the create-script command from the root of your project. For example the following command will create a script called src/main/scripts/hello-world.groovy
:
grails create-script hello-world
In general Grails scripts should be used for scripting the Gradle based build system and code generation. Scripts cannot load application classes and in fact should not since Gradle is required to construct the application classpath. |
See below for an example script that prints "Hello World":
description "Example description", "grails hello-world"
println "Hello World"
The description
method is used to define the output seen by grails help
and to aid users of the script. The following is a more complete example of providing a description taken from the generate-all
command:
description( "Generates a controller that performs CRUD operations and the associated views" ) {
usage "grails generate-all <<DOMAIN CLASS>>"
flag name:'force', description:"Whether to overwrite existing files"
argument name:'Domain Class', description:'The name of the domain class'
}
As you can see this description profiles usage instructions, a flag and an argument. This allows the command to be used as follows:
grails generate-all MyClass --force
Template Generation
Plugins and applications that need to define template generation tasks can do so using scripts. A example of this is the Scaffolding plugin which defines the generate-all
and generate-controllers
commands.
Every Grails script implements the TemplateRenderer interface which makes it trivial to render templates to the users project workspace.
The following is an example of the create-script command written in Groovy:
description( "Creates a Grails script" ) {
usage "grails create-script <<SCRIPT NAME>>"
argument name:'Script Name', description:"The name of the script to create"
flag name:'force', description:"Whether to overwrite existing files"
}
def scriptName = args[0]
def model = model(scriptName)
def overwrite = flag('force') ? true : false
render template: template('artifacts/Script.groovy'),
destination: file("src/main/scripts/${model.lowerCaseName}.groovy"),
model: model,
overwrite: overwrite
If a script is defined in a plugin or profile, the template(String)
method will search for the template in the application before using the template provided by your plugin or profile. This allows users of your plugin or profile to customize what gets generated.
It is common to provide an easy way to allow users to copy the templates from your plugin or profile. Here is one example on how the angular scaffolding copies templates.
templates("angular/**/*").each { Resource r ->
String path = r.URL.toString().replaceAll(/^.*?META-INF/, "src/main")
if (path.endsWith('/')) {
mkdir(path)
} else {
File to = new File(path)
SpringIOUtils.copy(r, to)
println("Copied ${r.filename} to location ${to.canonicalPath}")
}
}
The "model"
Executing the model
method with a Class
/String
/File
/Resource
will return an instance of Model. The model contains several properties that can help you generate code.
Example:
def domain = model(com.foo.Bar)
domain.className == "FooBar"
domain.fullName == "com.foo.FooBar"
domain.packageName == "com.foo"
domain.packagePath == "com/foo"
domain.propertyName == "fooBar"
domain.lowerCaseName == "foo-bar"
In addition, an asMap
method is available to turn all of the properties into a map to pass to the render
method.
Working with files
All scripts have access to methods on the FileSystemInteraction class. It contains helpful methods to copy, delete, and create files.
5.3 Creating Custom Commands
You can create your own commands by running the create-command command from the root of your project. For example the following command will create a command called grails-app/commands/HelloWorldCommand
:
grails create-command HelloWorld
Unlike scripts, commands cause the Grails environment to start and you have full access to the application context and the runtime. |
Since Grails 3.2.0, commands have similar abilities as scripts in regards to retrieving arguments, template generation, file access, and model building.
If you created a command in a previous version of grails, you can update your command to have those abilities by changing which trait you are implementing.
Commands created in Grails 3.1.x or lower implement the ApplicationCommand trait by default which requires your command to implement the following method:
boolean handle(ExecutionContext executionContext)
Commands created in Grails 3.2.0 or higher implement the GrailsApplicationCommand trait by default which requires your command to implement the following method:
boolean handle()
Commands defined this way still have access to the execution context via a variable called "executionContext". |
Custom commands can be executed using grails run-command:
grails run-command my-example
Commands can also be executed using the runCommand gradle task. Note that the gradle task uses camelCase:
gradle runCommand -Pargs="my-example"
If the grails server is a subproject (e.g., in a project created with the angular profile), the subproject command can still be invoked from the gradle wrapper in the parent project:
./gradlew server:runCommand -Pargs="my-example"
With Gradle, a custom command is a piece of functionality that you can add to your Grails application and execute via the command-line interface (CLI). These commands are not part of the core Grails framework but are extensions you can create to perform specific tasks or operations that are unique to your application’s requirements. Custom commands are a powerful way to automate various tasks, interact with your application, and perform administrative functions from the command line. When you run custom commands, they cause the Grails environment to start, giving you full access to the application context and the runtime, allowing you to work with the application’s resources, services, and configuration as needed within your custom command.
There are several reasons why you might want to write a custom command for your Grails application:
-
Automating Tasks: Custom commands allow you to automate routine tasks, such as data migration, database updates, or batch processing, by encapsulating the logic in a command that can be executed on-demand.
-
Administrative Operations: You can use custom commands for administrative tasks like user management, system maintenance, and configuration management, making it easier to manage your application in different environments.
-
Integration: Custom commands can be used to integrate your Grails application with other systems or services. For example, you can create a command to synchronize data with an external API.
-
Customized Workflows: If your application has unique workflows or processes, custom commands provide a way to execute these workflows from the command line.
In Grails, you can create custom commands by implementing the GrailsApplicationCommand trait. By default, this trait requires your command to implement the handle() method as following:
boolean handle()
Commands defined this way still have access to the execution context via a variable called "executionContext." |
Here’s a step-by-step guide on how to create custom commands using the GrailsApplicationCommand trait with examples, and how to run these commands.
In Grails, you can create custom commands by implementing the GrailsApplicationCommand
trait. Custom commands allow you to add functionality to your Grails application that can be executed via the command-line interface (CLI). Here’s a step-by-step guide on how to create custom commands using the GrailsApplicationCommand
trait with examples, and how to run these commands.
Step 1: Create a Custom Command
To create a custom command, you need to create a Groovy class that implements the GrailsApplicationCommand
trait. This trait provides methods for command execution. Let’s create a simple example command that greets the user:
// grails-app/commands/com/example/GreetCommand.groovy
package com.example
import grails.dev.commands.GrailsApplicationCommand
class GreetCommand implements GrailsApplicationCommand {
String getName() {
return "greet"
}
String getDescription() {
return "Greet the user"
}
boolean handle() {
println("Hello, user!")
return true // Return true to indicate successful execution
}
}
In this example, we’ve created a GreetCommand
class that implements the GrailsApplicationCommand
trait. It provides a getName()
method to define the command name, a getDescription()
method for a brief description, and the run()
method to specify the code to execute when the command is run.
Step 2: Build Your Grails Application
Before you can use the runCommand task, ensure you have built your Grails application using the following command:
./gradlew assemble
This command will compile your application and make it ready for running custom commands.
Step 3: Run the Custom Command
To run the custom command, use Gradle’s runCommand task. Open your terminal and navigate to your Grails application’s root directory. Then, run the custom command with the following Gradle command:
./gradlew runCommand -Pargs="greet"
In the command above, replace "greet" with the name of your custom command. This will execute the GreetCommand, and you will see the output.
Here’s the expected final output when you run the greet command:
Hello, user!
Additional Features: Command Arguments and Options
Grails also supports command-line arguments and options for custom commands. You can define these in your command class by implementing the GrailsApplicationCommand
interface. Here’s an example of a command that takes a name as an argument and an optional --loud
option to make the greeting louder:
// grails-app/commands/com/example/GreetCommand.groovy
package com.example
import grails.dev.commands.GrailsApplicationCommand
class GreetCommand implements GrailsApplicationCommand {
String getName() {
return "greet"
}
String getDescription() {
return "Greet the user with options"
}
boolean handle() {
def args = commandLine.args
String name = args.size() > 0 ? args[0] : "user"
boolean loud = args.contains("--loud")
if (loud) {
println("HELLO, $name! (LOUD)")
} else {
println("Hello, $name!")
}
return true
}
}
Now you can run the greet
command with arguments and options:
# Greet the user with the default message
./gradlew runCommand -Pargs="greet"
# Greet a specific user
./gradlew runCommand -Pargs="greet Alice"
# Greet loudly
./gradlew runCommand -Pargs="greet --loud"
# Greet a specific user loudly
./gradlew runCommand -Pargs="greet Alice --loud"
This allows you to create more versatile and interactive custom commands for your Grails application.
In summary, creating custom commands in Grails using the GrailsApplicationCommand
trait is a powerful way to extend your application’s functionality beyond the web interface. You can define the command’s name, description, and logic, and then execute it from the command line, optionally passing arguments and options as needed.
Using the executionContext
in the Grails Custom Commands
In Grails, the executionContext is a runtime context object that provides valuable information about the current execution environment of a Grails application. It includes details such as the application’s environment (e.g., development, production, test) and allows developers to access this context within custom commands.
Custom commands in Grails can use the executionContext to make informed decisions and perform specific tasks based on the current runtime environment. For example, developers can write conditional logic in custom commands that execute differently in production, development, or testing environments. This flexibility enables custom commands to adapt and behave differently depending on the context in which they are run, making them versatile tools for managing and extending Grails applications.
Suppose you have a Grails application that manages customer data, and you want to create a custom command to perform data backup. In this scenario, you may want the backup process to behave differently depending on whether you’re running it in a development, staging, or production environment.
Here’s an example of how you can create a custom command that uses the executionContext to determine the backup behavior:
// grails-app/commands/com/example/BackupCommand.groovy
package com.example
import grails.dev.commands.GrailsApplicationCommand
class BackupCommand implements GrailsApplicationCommand {
String getName() {
return "backup"
}
String getDescription() {
return "Backup customer data"
}
boolean handle() {
// Access the executionContext to determine the environment
def environment = executionContext.environment
if (environment == "production") {
// Perform a full backup in the production environment
println("Performing a full backup of customer data (Production)")
// Add production-specific backup logic here
} else {
// Perform a partial backup in other environments
println("Performing a partial backup of customer data (Non-production)")
// Add non-production backup logic here
}
return true // Return true to indicate successful execution
}
}
In this example:
-
The custom command, named
BackupCommand
, is created to back up customer data. -
It checks the
executionContext
to determine the current environment. -
If the environment is "production," it performs a full backup with production-specific logic.
-
In all other environments, it performs a partial backup with non-production logic.
When you run this custom command using ./gradlew runCommand -Pargs="backup"
, it will adapt its behavior based on whether you’re in a production or non-production environment, demonstrating how the executionContext
can be used to make environment-specific decisions in a realistic scenario.
How to Create a Custom Command from a Grails Plugin
You can create custom commands not only within your Grails application but also from a Grails plugin. Here’s how to do it:
-
Create a Grails Plugin: If you don’t already have a Grails plugin, you can create one using Grails' plugin generation commands. For example:
grails create-plugin my-plugin
-
Define the Command: Inside your Grails plugin, define the custom command by creating a Groovy class that implements the
GrailsApplicationCommand
trait or interface, providing the necessary methods likegetName()
,getDescription()
, andhandle()
. -
Build and Package the Plugin: To publish the plugin, you should use the Gradle maven-publish plugin. Update your plugin’s build.gradle file to include the following configuration:
publishing { publications { mavenJava(MavenPublication) { from components.java } } repositories { maven { url "file://path/to/your/local/repo" // Adjust the path accordingly } } }
Then, you can publish the plugin to your local repository:
./gradlew publishToMavenLocal
-
Add the Plugin as a Dependency: Instead of using the grails install-plugin command, you should add the plugin as a dependency in your Grails application’s build.gradle file. Include the following dependency:
dependencies { // ... implementation 'com.example:my-plugin:1.0.0' // Replace with your plugin's group and version // ... }
Make sure to replace "com.example:my-plugin:1.0.0" with the appropriate group and version for your plugin
-
Run the Custom Command: Now, you can run the custom command from your Grails application’s root directory using the Gradle
runCommand
task, as previously explained:./gradlew runCommand -Pargs="your-command-name"
Replace
"your-command-name"
with the name of the custom command you defined in your plugin.
By following these steps, you can create and run custom commands from a Grails plugin, extending the functionality of your Grails application as needed. This approach allows you to modularize your custom functionality and share it across multiple Grails projects if necessary.
5.4 Creating a Grails Project
Creating a project is the primary usage of the CLI. The primary command for creating a new project is create-app, which creates a standard Grails web application that communicates over HTTP. For other types of application, see the documentation below.
Command | Description | Options | Example |
---|---|---|---|
create-app / create-webapp |
Creates a Grails web application |
|
|
create-restapi |
Creates a Grails REST API application |
|
|
create-plugin |
Creates a Grails Plugin application |
|
|
create-web-plugin |
Creates a Grails Web Plugin application |
|
|
| Flag | Description | Example
The create-
command flags
The "create-*" commands are used to produce a fundamental Grails project, allowing for the inclusion of optional flags to select additional features, to customize GORM settings, an embedded servlet, the test framework, and the Java version.
Flag | Description | Example |
---|---|---|
-jdk, --java-version |
The JDK version the project should target |
|
-s, --servlet |
Which Servlet Implementation to configure. Possible values: none, tomcat, jetty, undertow. |
|
-g, --gorm |
Which GORM Implementation to configure. Possible values: hibernate, mongodb, neo4j. |
|
-t, --test |
Which test framework to use. Possible values: junit, spock. |
|
-f, --features |
The features to use. Possible values: h2, gorm-hibernate5, spring-boot-starter-jetty, springloaded, micronaut-http-client, cache-ehcache, hibernate-validator, postgres, mysql, cache, database-migration, grails-gsp, hamcrest, gorm-mongodb, assertj, mockito, spring-boot-starter-undertow, micronaut-inject-groovy, github-workflow-java-ci, jrebel, testcontainers, sqlserver, grails-console, views-markup, views-json, gorm-neo4j, asciidoctor, embedded-mongodb, grails-web-console, logbackGroovy, mongo-sync, shade, properties |
|
-i, --inplace |
Create a project using the current directory |
|
5.5 Re-using Grails scripts
Grails ships with a lot of command line functionality out of the box that you may find useful in your own scripts (See the command line reference in the reference guide for info on all the commands).
Any script you create can invoke another Grails script simply by invoking a method:
testApp()
The above will invoke the test-app
command. You can also pass arguments using the method arguments:
testApp('--debug-jvm')
Invoking Gradle
Instead of invoking another Grails CLI command you can invoke Gradle directory using the gradle
property.
gradle.compileGroovy()
Invoking Ant
You can also invoke Ant tasks from scripts which can help if you need to writing code generation and automation tasks:
ant.mkdir(dir:"path")
5.6 Building with Gradle
Since Grails 3.1 the Gradle Build System is used for build related tasks such as compilation, runnings tests and producing binary distributions of your project. It is recommended to use Gradle 2.2 or above with Grails 3.1 (and higher).
The build is defined by the build.gradle
file which specifies the version of your project, the dependencies of the project and the repositories where to find those dependencies (amongst other things).
When you invoke the grails
command the version of Gradle that ships with Grails 3.1 (currently 2.9) is invoked by the grails
process via the Gradle Tooling API:
# Equivalent to 'gradle classes'
$ grails compile
You can invoke Gradle directly using the gradle
command and use your own local version of Gradle, however you will need Gradle 2.2 or above to work with Grails 3.0 (and higher):
$ gradle assemble
5.6.1 Defining Dependencies with Gradle
Dependencies for your project are defined in the dependencies
block. In general, you can follow the Gradle documentation on dependency management to understand how to configure additional dependencies.
The default dependencies for the Grails Web application can be seen below:
dependencies {
implementation("org.grails:grails-core")
implementation("org.grails:grails-logging")
implementation("org.grails:grails-plugin-databinding")
implementation("org.grails:grails-plugin-i18n")
implementation("org.grails:grails-plugin-interceptors")
implementation("org.grails:grails-plugin-rest")
implementation("org.grails:grails-plugin-services")
implementation("org.grails:grails-plugin-url-mappings")
implementation("org.grails:grails-web-boot")
implementation("org.grails.plugins:gsp")
implementation("org.grails.plugins:hibernate5")
implementation("org.grails.plugins:scaffolding")
implementation("org.hibernate:hibernate-core:5.6.15.Final")
implementation("org.springframework.boot:spring-boot-autoconfigure")
implementation("org.springframework.boot:spring-boot-starter")
implementation("org.springframework.boot:spring-boot-starter-actuator")
implementation("org.springframework.boot:spring-boot-starter-logging")
implementation("org.springframework.boot:spring-boot-starter-tomcat")
implementation("org.springframework.boot:spring-boot-starter-validation")
compileOnly("io.micronaut:micronaut-inject-groovy")
console("org.grails:grails-console")
runtimeOnly("com.bertramlabs.plugins:asset-pipeline-grails:4.3.0")
runtimeOnly("com.h2database:h2")
runtimeOnly("javax.xml.bind:jaxb-api:2.3.1")
runtimeOnly("org.apache.tomcat:tomcat-jdbc")
runtimeOnly("org.fusesource.jansi:jansi:1.18")
runtimeOnly("org.glassfish.web:el-impl:2.2.1-b05")
testImplementation("io.micronaut:micronaut-inject-groovy")
testImplementation("org.grails:grails-gorm-testing-support")
testImplementation("org.grails:grails-web-testing-support")
testImplementation("org.grails.plugins:geb")
testImplementation("org.seleniumhq.selenium:selenium-api:4.10.0")
testImplementation("org.seleniumhq.selenium:selenium-remote-driver:4.10.0")
testImplementation("org.seleniumhq.selenium:selenium-support:4.10.0")
testImplementation("org.spockframework:spock-core")
testRuntimeOnly("org.seleniumhq.selenium:selenium-chrome-driver:4.10.0")
testRuntimeOnly("org.seleniumhq.selenium:selenium-firefox-driver:4.10.0")
testRuntimeOnly("org.seleniumhq.selenium:selenium-safari-driver:4.10.0")
testImplementation("io.micronaut:micronaut-http-client")
}
Note that version numbers are not present in the majority of the dependencies. This is thanks to the dependency management plugin which configures a Maven BOM that defines the default dependency versions for certain commonly used dependencies and plugins:
dependencyManagement {
imports {
mavenBom 'org.grails:grails-bom:' + grailsVersion
}
applyMavenExclusions false
}
5.6.2 Working with Gradle Tasks
As mentioned previously the grails
command uses an embedded version of Gradle and certain Grails commands that existed in previous versions of Grails map onto their Gradle equivalents. The following table shows which Grails command invoke which Gradle task:
Grails Command | Gradle Task |
---|---|
clean |
clean |
compile |
classes |
package |
assemble |
run-app |
bootRun |
test-app |
check |
test-app --unit |
test |
test-app --integration |
integrationTest |
war |
assemble |
You can invoke any of these Grails commands using their Gradle equivalents if you prefer:
$ gradle test
Note however that you will need to use a version of Gradle compatible with Grails 3.1 (Gradle 2.2 or above). If you wish to invoke a Gradle task using the version of Gradle used by Grails you can do so with the grails
command:
$ grails gradle compileGroovy
However, it is recommended you do this via interactive mode, as it greatly speeds up execution and provides TAB completion for the available Gradle tasks:
$ grails
| Enter a command name to run. Use TAB for completion:
grails> gradle compileGroovy
...
To find out what Gradle tasks are available without using interactive mode TAB completion you can use the Gradle tasks
task:
gradle tasks
5.6.3 Grails plugins for Gradle
When you create a new project with the create-app command, a default build.gradle
is created. The default build.gradle
configures the build with a set of Gradle plugins that allow Gradle to build the Grails project:
plugins {
id "groovy"
id "org.grails.grails-web"
id "org.grails.grails-gsp"
id "com.github.erdi.webdriver-binaries"
id "war"
id "idea"
id "com.bertramlabs.asset-pipeline"
id "application"
id "eclipse"
}
The default plugins are as follows:
* groovy
- The Groovy plugin add support for Groovy projects. It can deal with Groovy code mixed with Groovy and Java. Read More: The Groovy Plugin
* com.github.erdi.webdriver-binaries
- A plugin that downloads and caches WebDriver binaries specific to the OS the build runs on. Read More at GitHub README
* war
- The The WAR plugin changes the packaging so that Gradle creates as WAR file from your application. You can comment out this plugin if you wish to create only a runnable JAR file for standalone deployment.
* idea
- The IDEA plugin generates files that are used by IntelliJ IDEA, thus making it possible to open the project from IDEA. Read More: The IDEA Plugin
* com.bertramlabs.asset-pipeline
- The asset pipeline plugin enables the compilation of static assets (JavaScript, CSS etc.)
* application
- The Application plugin facilitates creating an executable JVM application. Read More: The Application Plugin
* eclipse
- The Eclipse plugins generate files that are used by the Eclipse IDE, thus making it possible to import the project into Eclipse (File - Import… - Existing Projects into Workspace). Read More: The Eclipse Plugin
Many of these are built in plugins provided by Gradle or third party plugins. The Gradle plugins that Grails provides are as follows:
-
org.grails.grails-doc
- A plugin for Gradle for using Grails 2.0’s documentation engine. -
org.grails.grails-gsp
- The Grails GSP plugin adds pre-compilation of GSP files for production deployments. -
org.grails.grails-plugin
- A plugin for Gradle for building Grails plugins. -
org.grails.grails-web
- The Grails Web gradle plugin configures Gradle to understand the Grails conventions and directory structure. -
org.grails.grails-plugin-publish
- A plugin for publishing Grails plugins to the central repository. -
org.grails.grails-profile
- A plugin for use when creating Grails Profiles. -
org.grails.grails-profile-publish
- A plugin for publishing Grails profiles to the central repository.