grails
5 The Command Line
Version: 6.2.1
5 The Command Line
The Grails 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:
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
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 Commands
In Grails, 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.3 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 |
|