(Quick Reference)

5 The Command Line - Reference Documentation

Authors: Graeme Rocher, Peter Ledbrook, Marc Palmer, Jeff Brown, Luke Daley, Burt Beckwith, Lari Hotari

Version: 3.0.1

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 [command name]

Grails searches the profile repository based on the profile of the current application. If the profile is for a web application then commmands a read from the web profile and the base profile which it inherits from.

Since command behavior is profile specific the web profile my 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 results in a search for the following files:

  • PROJECT_HOME/scripts/RunApp.groovy
  • PROFILE_REPOSITORY_PATH/profiles/web/commands/run-app.groovy (if the web profile is active)
  • PROFILE_REPOSITORY_PATH/profiles/web/commands/run-app.yml (for YAML defined 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

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

5.1 Interactive Mode

Interactive mode is the 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.

5.2 The Command Line and Profiles

When you create a Grails application with the create-app command by default the "web" profile is used:

grails create-app myapp

You can specify a different profile with the profile argument:

grails create-app myapp --profile=web-plugin

Profiles encapsulate the project commands, templates and plugins that are designed to work for a given profile. They are stored in the Grails Profile Repository on Github.

This repository is checked out locally and stored in the USER_HOME/.grails/repository directory.

Understanding a Profile's Structure

A profile is a simple directory that contains a profile.yml file and directorys containing the "commands", "skeleton" and "templates" defined by the profile. Example:

web
    * commands
        * create-controller.yml
        * run-app.groovy    
        …
    * skeleton
        * grails-app
            * controllers
            …
        * build.gradle
    * templates
        * artifacts
            * Controller.groovy
    * profile.yml

The above example is a snippet of structure of the 'web' profile. The profile.yml file is defined as follows:

description: Profile for Web applications
extends: base

As you can see it contains the description of the profile and a definition of which profiles this profile extends, since one profile can extend from another.

When the create-app command runs it takes the skeleton of the parent profiles and copies the skeletons into a new project structure. Child profiles overwrite files from the parent profile so if the parent defines a build.gradle then the child profile will override the parent.

Defining Profile Commands

A profile can define new commands that apply only to that profile using YAML or Groovy scripts. Below is an example of the create-controller command defined in YAML:

description: 
    - Creates a controller
    - usage: 'create-controller [controller name]'
    - completer: org.grails.cli.interactive.completers.DomainClassCompleter
    - argument: "Controller Name"
      description: "The name of the controller"     
steps:
 - command: render
   template: templates/artifacts/Controller.groovy
   destination: grails-app/controllers/artifact.package.path/artifact.nameController.groovy
 - command: render
   template: templates/testing/Controller.groovy
   destination: src/test/groovy/artifact.package.path/artifact.nameControllerSpec.groovy
 - command: mkdir
   location: grails-app/views/artifact.propertyName

Commands defined in YAML must define one or many steps. Each step is a command in itself. The available step types are:

  • render - To render a template to a given destination (as seen in the previous example)
  • mkdir - To make a directory specified by the location parameter
  • execute - To execute a command specified by the class parameter. Must be a class that implements the Command interface.
  • gradle - To execute one or many Gradle tasks specified by the tasks parameter.

For example to invoke a Gradle task, you can define the following YAML:

description: Creates a WAR file for deployment to a container (like Tomcat)
minArguments: 0
usage: |
 war
steps:
 - command: gradle
   tasks:
     - war

If you need more flexiblity than what the declarative YAML approach provides you can create Groovy script commands. Each Command script is extends from the GroovyScriptCommmand class and hence has all of the methods of that class available to it.

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

For more information on creating Groovy commands see the following section on creating custom Grails scripts.

5.3 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:

grails create-script hello-world

Will create a script called src/main/scripts/hello-world.groovy. Each Command script is extends from the GroovyScriptCommmand class and hence has all of the methods of that class available to it.

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

5.4 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 an 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")

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

5.5 Building with Gradle

Grails 3.0 uses the Gradle Build System for build related tasks such as compilation, runnings tests and producing binary distrubutions of your project. It is recommended to use Gradle 2.2 or above with Grails 3.0.

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.0 (currently 2.3) 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:

$ gradle assemble

5.5.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 "web" profile can be seen below:

dependencies {
  compile 'org.springframework.boot:spring-boot-starter-logging'
  compile('org.springframework.boot:spring-boot-starter-actuator')
  compile 'org.springframework.boot:spring-boot-autoconfigure'
  compile 'org.springframework.boot:spring-boot-starter-tomcat'
  compile 'org.grails:grails-dependencies'
  compile 'org.grails:grails-web-boot'

compile 'org.grails.plugins:hibernate' compile 'org.grails.plugins:cache' compile 'org.hibernate:hibernate-ehcache'

runtime 'org.grails.plugins:asset-pipeline' runtime 'org.grails.plugins:scaffolding'

testCompile "org.grails:grails-plugin-testing' testCompile "org.grails.plugins:geb'

// Note: It is recommended to update to a more robust driver (Chrome, Firefox etc.) testRuntime 'org.seleniumhq.selenium:selenium-htmlunit-driver:2.44.0'

console 'org.grails:grails-console' }

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.5.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 CommandGradle Task
cleanclean
compileclasses
packageassemble
run-apprun
test-apptest
warassemble

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.0 (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.5.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 "io.spring.dependency-management" version "0.3.1.RELEASE"
}

apply plugin: "spring-boot" apply plugin: "war" apply plugin: "asset-pipeline" apply plugin: "org.grails.grails-web" apply plugin: "org.grails.grails-gsp" apply plugin: "maven"

The default plugins are as follows:

  • dependency-management - The dependency management plugin allows Gradle to read Maven BOM files that define the default dependency versions used by Grails.
  • spring-boot - The Spring Boot Gradle plugin enhances the default packaging tasks provided by Gradle to allow for the creation of runnable JAR/WAR files.
  • war - The WAR plugin changes the packaging so that Gradle creates as WAR file from you application. You can comment out this plugin if you wish to create only a runnable JAR file for standalone deployment.
  • asset-pipeline - The asset pipeline plugin enables the compilation of static assets (JavaScript, CSS etc.)
  • maven - The maven plugin allows installing your application into a local maven repository

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-core - The primary Grails plugin for Gradle, included by all other plugins and designed to operate with all profiles.
  • 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-gsp - The Grails GSP plugin adds precompilation of GSP files for production deployments.
  • org.grails.grails-doc - A plugin for Gradle for using Grails 2.0's documentation engine.