(Quick Reference) # 5 The Command Line Version: 6.0.0 ## 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 <<command name>>
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: `PROJECT_HOME/src/main/scripts/run-app.groovy` `[profile]/commands/run-app.groovy` `[profile]/commands/run-app.yml` 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
## 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. ## 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"
## 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 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.5 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.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-gorm-testing-support"
      testCompile "org.grails:grails-web-testing-support"
      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 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.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:
    apply plugin:"war"
    apply plugin:"org.grails.grails-web"
    apply plugin:"org.grails.grails-gsp"
    apply plugin:"asset-pipeline"
The default plugins are as follows: `war` - 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. `asset-pipeline` - The asset pipeline plugin enables the compilation of static assets (JavaScript, CSS etc.) 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-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. `org.grails.grails-plugin` - A plugin for Gradle for building Grails plugins. `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. `org.grails.grails-web` - The Grails Web gradle plugin configures Gradle to understand the Grails conventions and directory structure. | Quick Reference (hide)