Groovy CliBuilder 使用

Groovy CliBuilder 使用

第一版本

直接使用 CliBuiler


def cli = new CliBuilder(usage: "运行脚本检查 dev 和 master 有没有同步")
cli.with {
    pid longOpt: 'projectId', required: true, '需要 projectId ', type: String.class
    pt longOpt: 'privateToken', required: true, '可以访问 gitlab api 的 token', type: String.class
}
def opt = cli.parse(args)

String projectId = opt.pid
String privateToken = opt.pt

option 的参数如下

Property Type Picocli equivalent Description
argName String names Short name for the option, will be prefixed with a single hyphen.
longOpt String names Long name for the option, will be prefixed with two hyphens unless acceptLongOptionsWithSingleHyphen is true. An option must have either a long name or a short name (or both).
args int or String arity args indicates the number of parameters for this option. A String value of '+' indicates at least one up to any number of parameters. The minimum number of parameters depends on the type (booleans require no parameters) and the optionalArg setting. args can often be omitted if a type is specified.
optionalArg boolean arity If optionalArg=true, then args=3 is the equivalent of arity="0..3" in picocli. When optionalArg=trueargs='+' is equivalent to arity="0..*".
required boolean required If true, this option must be specified on the command line, or an exception is thrown.
type Class type Option parameters are converted to this type. The underlying library has built-in converters for many types. A custom converter can be specified with the convert property.
convert Closure converter A closure that takes a single String parameter and returns an object converted to the type of this option. The picocli equivalent is the [ITypeConverter](http://picocli.info/#_custom_type_converters) interface.
valueSeparator char splitRegex The character used to split a single command line argument into parts.
defaultValue String defaultValue The value the option should have if it did not appear on the command line. The specified String value will be split into parts with the valueSeparator and converted to the option type before it is set.

再详细的使用可以参考这个clibuilder

第二版本

#!/usr/bin/env groovy
package com.hangox.codetest.cli

import groovy.cli.Option
import groovy.cli.commons.CliBuilder
import groovy.json.JsonSlurper

class MyOption {
    @Option(
            shortName = "pid",
            longName = "projectId",
            description = "需要 projectId",
            optionalArg = false
    )
    String pid

    @Option(
            shortName = "pt",
            longName = "privateToken",
            description = "可以访问 gitlab api 的 token",
            optionalArg = false
    )
    String privateToken
}

def cli = new CliBuilder(usage: "运行脚本检查 dev 和 master 有没有同步")
def opt = cli.parseFromInstance(new MyOption(), args)

String projectId = opt.pid
String privateToken = opt.privateToken
String checkBranch = "dev"
String targeBranch = "master"
String notifyGroupId = '1466753'
String baseUrl = "https://git-cc.nie.netease.com/api/v4"
properties = ['requestProperties': [
        'Accept'       : 'application/json',
        'PRIVATE-TOKEN': privateToken
]]

String resultText = "$baseUrl/projects/$projectId/protected_branches/$checkBranch".toURL()
        .getText(properties)

def result = new JsonSlurper().parseText(resultText)
def devAccessLevel = (result['push_access_levels'] as List)[0]['access_level'] as Integer
// 如果是0 表示 dev 已经锁定
if (devAccessLevel != 0) {
    // 不是锁定的 dev 如果有 master 没有包含在 dev 中,就是表示有问题
    boolean isDevContainMaster = false
    resultText = "$baseUrl/projects/$projectId/repository/commits/$targeBranch/refs?type=branch".toURL().getText(properties)
    def containsResult = new JsonSlurper().parseText(resultText) as List
    containsResult.forEach {
        def branchName = it['name']
        println branchName
        if (branchName == checkBranch) {
            // 有些东西有特殊符号在前面
            isDevContainMaster = true
        }
    }
    if (!isDevContainMaster) {
        // dev 没有包含 master 的头部,发送 popo 通知
        println "有东西不在 dev 上开始通知"
        def message = URLEncoder.encode("检查到 master 上还有内容还没合并到 dev 上,请尽快合并", "utf-8")
        def popoResult = "http://192.168.45.143:10024/api/post_popo?uid=$notifyGroupId&msg=$message".toURL().text
        print popoResult
    } else {
        println "master 所有东西都在 dev 上了"
    }
} else {
    println "dev 还在锁定跳过检查"
}

需要注意的点

CliBuilder 有两个,groovy.cli.commons.CliBuilder 这个才是 option 对应的

更复杂的构建

参考这篇文章