如何创建通过未知选项的Groovy CliBuilder?

时间:2012-07-31 17:15:20

标签: groovy

我有以下内容:

final String scriptName = new File(getClass().protectionDomain.codeSource.location.path).getName()
final cli = new CliBuilder(
        stopAtNonOption: false,
        usage: "${scriptName} ARGUMENTS",
        width: 80)
cli.with {
    _ longOpt: "known-option-0", args: 1, argName: "KNOWN_OPTION_0", "Known option."
    _ longOpt: "known-option-1", args: 1, argName: "KNOWN_OPTION_1", "Known option."
}

我希望能够用:

来调用它
options = cli.parse(['--known-option-0=0', '--unknown-option=aoeu', '--known-option-1=1'])

这样就没有解析错误,无需在接受的选项列表中添加--unknown-option,并且设置了known-option-0和known-option-1。

如果我设置:

        stopAtNonOption: true,

没有发出错误,但是:

options.'known-option-0' == 0
options.'known-option-1' == false

如何解析所有已知选项并忽略未知选项?

1 个答案:

答案 0 :(得分:1)

class CliParser {
    final CliBuilder cli
    final List<Cli> options_list = []
    final List<String> arguments_list = []

    CliParser(CliBuilder cli) {
        this.cli = cli
    }

    Collection getOptions() {
        cli.options.getOptions()
    }

    Cli parse(List<String> args) {
        while (args.size() != 0) {
            groovy.util.OptionAccessor options = cli.parse(args)
            options_list.add(options)

            List<String> arguments = options.arguments()
            arguments_list.add(arguments[0])

            args = (arguments.size() > 1) ? arguments[1..-1] : []
        }

        return new Cli(options: options_list, arguments: arguments_list)
    }
}

class Cli {
    List<groovy.util.OptionAccessor> options
    List<String> arguments

    List<String> arguments() {
        arguments
    }

    List<Option> getOptions() {
        options.collect {
            it.getOptions()
        }
    }

    Object getProperty(String name) {
        final optionAccessor = options
                .find {
                    it.hasOption(name)
                }

        optionAccessor?.getProperty(name)
    }
}

final String scriptName = new File(getClass().protectionDomain.codeSource.location.path).getName()
final cliBuilder = new CliBuilder(
        stopAtNonOption: false,
        usage: "${scriptName} ARGUMENTS",
        width: 80)
cliBuilder.with {
    _ longOpt: "known-option-0", args: 1, argName: "KNOWN_OPTION_0", "Known option."
    _ longOpt: "known-option-1", args: 1, argName: "KNOWN_OPTION_1", "Known option."
}

final cliParser = new CliParser(cliBuilder)
final cli = cliParser.parse(args)