且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

jenkins 扩展参数插件 groovy 脚本

更新时间:2023-12-05 13:34:16

我不得不深入研究源代码才能找到这些问题的答案,所以我希望这对其他人有所帮助.

I had to dig into the source code to find the answer to these questions so i hope this helps everyone else.

1.脚本在什么上下文中运行?

脚本在 groovy.lang.GroovyShell 中运行.这个类目前来自 Groovy 1.8.5 库.这是代码的摘录:

The script is run inside a groovy.lang.GroovyShell. This class is currently from the Groovy 1.8.5 library. here is an excerpt from the code:

// line 419 - 443 of the ExtendedChoiceParamaterDefinition
else if(!StringUtils.isBlank(groovyScript)) {
    try {
        GroovyShell groovyShell = new GroovyShell();
        setBindings(groovyShell, bindings);
        Object groovyValue = groovyShell.evaluate(groovyScript);
        String processedGroovyValue = processGroovyValue(isDefault, groovyValue);
        return processedGroovyValue;
    }
    catch(Exception e) {

    }
}
else if(!StringUtils.isBlank(groovyScriptFile)) {
    try {
        GroovyShell groovyShell = new GroovyShell();
        setBindings(groovyShell, bindings);
        groovyScript = Util.loadFile(new File(groovyScriptFile));
        Object groovyValue = groovyShell.evaluate(groovyScript);
        String processedGroovyValue = processGroovyValue(isDefault, groovyValue);
        return processedGroovyValue;
    }
    catch(Exception e) {

    }
}

2.我应该从脚本返回什么?

如上面的代码所示,脚本应该返回一个带有您在参数或 String[] 数组中指定的任何分隔符的字符串.这是处理从脚本返回的值的函数片段:

As the above code demonstrates, the script should return a string with whatever delimiter you have specified in the paramater or a String[] array. here is a snippet of the function that processes the value returned from the script:

// line 450 - 465 of ExtendedChoiceParameterDefinition
private String processGroovyValue(boolean isDefault, Object groovyValue) {
    String value = null;
    if(groovyValue instanceof String[]) {
        String[] groovyValues = (String[])groovyValue;
        if(!isDefault) {
            value = StringUtils.join((String[])groovyValue, multiSelectDelimiter);
        }
        else if(groovyValues.length > 0) {
            value = groovyValues[0];
        }
    }
    else if(groovyValue instanceof String) {
        value = (String)groovyValue;
    }
    return value;
}

3.脚本的 cwd 是什么目录?是环境变量WORKSPACE吗?

有关系吗?您可以使用

Map<String, String> props = System.getenv();
def currentDir = props.get('WORKSPACE');

4.有一个称为变量绑定的额外字段.这是如何使用的?

这是一个属性文件,格式为 key=value 文件.然后可以在 groovy 脚本中解析这些名称.

This is a property file formatted key=value file. these names are then resolvable in the groovy script.

    e.g.
    key1=foo
    prop2=bar