Grails脚本和使用Groovy CLIBuilder传递参数?

时间:2013-01-12 11:20:25

标签: grails groovy

我创建了一个非常简单的脚本,并希望将参数传递给脚本。

像:

grails> helloworld -n Howdy
grails> helloworld -name Howdy

使用脚本:

target(main: 'Hello World') {
    def cli = new CliBuilder()
    cli.with
            {
                h(longOpt: 'help', 'Help - Usage Information')
                n(longOpt: 'name', 'Name to say hello to', args: 1, required: true)
            }
    def opt = cli.parse(args)
    if (!opt) return
    if (opt.h) cli.usage()
    println "Hello ${opt.n}"
}

我似乎每次尝试都失败了。该脚本一直抱怨-n选项不存在。

当我调试脚本的值时,参数args参数看起来像是重新排列的值。

使用以下方法调用脚本时

grails> helloworld -n Howdy 

脚本中args的值是: Howdy -n

我在这里错过了什么?有什么建议吗?

2 个答案:

答案 0 :(得分:1)

您的问题是您通过grails shell运行代码。我已将您的代码转换为CLI.groovy,如下所示:

class CLI{
 public static void main(String [] args){
     def cli = new CliBuilder()
     cli.with
            {
                h(longOpt: 'help', 'Help - Usage Information')
                n(longOpt: 'name', 'Name to say hello to', args: 1, required: true)
             }
      def opt = cli.parse(args)
      if (!opt) return
      if (opt.h) cli.usage()
      println "Hello ${opt.n}"
      }
 }

之后我使用groovy命令从linux shell运行它:

 archer@capitan $ groovy CLI -n Daddy

输出:

 archer@capitan $ groovy CLI -n Daddy
 Hello Daddy

所以它就像一个魅力。

答案 1 :(得分:0)

我对site:github.com grailsScript CliBuilder进行了Google搜索,但遇到了:

https://github.com/Grails-Plugin-Consortium/grails-cxf/blob/master/scripts/WsdlToJava.groovy

这给了我一个提示,args变量需要格式化。不幸的是,它将-n Howdy变为Howdy\n-n(不确定为什么重新排列顺序或添加换行符)。

上面的github页面有一个doSplit()方法来处理其中的一些,但它保留了重新排列的顺序。我发现的最好的方法是删除-nHowdy之间的空格,这将适用于CliBuilder。

以下是我的工作:

target(main: 'Hello World') {
    def cli = new CliBuilder()
    cli.with
            {
                h(longOpt: 'help', 'Help - Usage Information')
                n(longOpt: 'name', 'Name to say hello to', args: 1, required: true)
            }
    def ops = doSplit(args)
    def opt = cli.parse(ops)
    if (!opt) return
    if (opt.h) cli.usage()
    println "Hello ${opt.n}"
}

private doSplit(String string){
    string.split(/(\n|[ ]|=)/).collect{ it.trim() }.findResults  { it && it != '' ? it : null }
}

使用以下代码运行:helloworld -nHowdy

相关问题