6.5 Creating 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:

  1. description:
  2. - Creates a controller
  3. - usage: 'create-controller <<controller name>>'
  4. - completer: org.grails.cli.interactive.completers.DomainClassCompleter
  5. - argument: "Controller Name"
  6. description: "The name of the controller"
  7. steps:
  8. - command: render
  9. template: templates/artifacts/Controller.groovy
  10. destination: grails-app/controllers/`artifact.package.path`/`artifact.name`Controller.groovy
  11. - command: render
  12. template: templates/testing/Controller.groovy
  13. destination: src/test/groovy/`artifact.package.path`/`artifact.name`ControllerSpec.groovy
  14. - command: mkdir
  15. 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:

  1. description: Creates a WAR file for deployment to a container (like Tomcat)
  2. minArguments: 0
  3. usage: |
  4. war
  5. steps:
  6. - command: gradle
  7. tasks:
  8. - 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:

  1. description( "Creates a Grails script" ) {
  2. usage "grails create-script <<SCRIPT NAME>>"
  3. argument name:'Script Name', description:"The name of the script to create"
  4. flag name:'force', description:"Whether to overwrite existing files"
  5. }
  6. def scriptName = args[0]
  7. def model = model(scriptName)
  8. def overwrite = flag('force') ? true : false
  9. render template: template('artifacts/Script.groovy'),
  10. destination: file("src/main/scripts/${model.lowerCaseName}.groovy"),
  11. model: model,
  12. overwrite: overwrite

For more information on creating CLI commands see the section on creating custom scripts in the Command Line section of the user guide.