我正在为 CNB(构建包)开发 Jenkins 管道插件。需要用Java获取pipeline脚本中的变量但是还是不能成功
这是我的管道脚本。
buildpacks {
builder = "some/builder"
}
并且我可以在 buildpacks.groovy 中使用 Groovy 语言访问这些变量(如构建器变量)
package dsl
// The call(body) method in any file in workflowLibs.git/vars is exposed as a
// method with the same name as the file.
def call(body) {
def config = [:]
body.resolveStrategy = Closure.DELEGATE_FIRST
body.delegate = config
body()
try {
echo "${config.builder}"
} catch (Exception rethrow) {
throw rethrow
}
}
但正如我所说,我需要在 Java 中获取这些变量。 下面是我从 GlobalVariable 类继承的类。
public abstract class PipelineDSLGlobal extends GlobalVariable {
public abstract String getFunctionName();
@Override
public String getName() {
return getFunctionName();
}
@Override
public Object getValue(CpsScript script) throws Exception {
Binding binding = script.getBinding();
CpsThread c = CpsThread.current();
if (c == null)
throw new IllegalStateException("Expected to be called from CpsThread");
ClassLoader cl = getClass().getClassLoader();
String scriptPath = "dsl/" + getFunctionName() + ".groovy";
Reader r = new InputStreamReader(cl.getResourceAsStream(scriptPath), "UTF-8");
GroovyCodeSource gsc = new GroovyCodeSource(r, getFunctionName() + ".groovy", cl.getResource(scriptPath).getFile());
gsc.setCachable(true);
System.out.println(gsc.toString());
Object pipelineDSL = c.getExecution()
.getShell()
.getClassLoader()
.parseClass(gsc)
.getDeclaredConstructor()
.newInstance();
binding.setVariable(getName(), pipelineDSL);
r.close();
System.out.println("test");
return pipelineDSL;
}
}
下面是我为 buildpacksdsl 创建的类。
package io.jenkins.plugins.buildpacks;
import hudson.Extension;
import io.jenkins.plugins.pipelinedsl.PipelineDSLGlobal;
import org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.ProxyWhitelist;
import org.jenkinsci.plugins.scriptsecurity.sandbox.whitelists.StaticWhitelist;
import java.io.IOException;
@Extension
public class BuildpacksDSL extends PipelineDSLGlobal {
@Override
public String getFunctionName() {
return "buildpacks";
}
@Extension
public static class MiscWhitelist extends ProxyWhitelist {
public MiscWhitelist() throws IOException {
super(new StaticWhitelist(
"method java.util.Map$Entry getKey",
"method java.util.Map$Entry getValue"
));
}
}
}
如果您想更详细地查看结构,可以查看repository。
有人可以帮我吗?谢谢。