如何在成员函数中使用内置管道函数?

时间:2018-10-08 15:38:19

标签: jenkins-pipeline

目标是在类的成员函数中的groovy-function中使用buil。 在ubuntu18.04中使用默认jenkins运行以下代码会导致以下错误。

jenkins似乎在类本身中定义的名为“ dir”的函数中搜索。

如果重要,我将在稍后检查管道版本和詹金斯迷信。

复制和粘贴管道脚本:

class notworkingClass {

    notworkingClass(){}
    public MyFunction(){
        dir('/my/local/folder'){
            dosomething() // never reached
        }    
    }
}

def x = new notworkingClass()
x.MyFunction()

这是堆栈跟踪:

hudson.remoting.ProxyException: groovy.lang.MissingMethodException: No signature of method: notworkingClass.dir() is applicable for argument types: (java.lang.String, org.jenkinsci.plugins.workflow.cps.CpsClosure2) values: [/my/local/folder, org.jenkinsci.plugins.workflow.cps.CpsClosure2@372fc690]
Possible solutions: wait(), dump(), find(), any(), is(java.lang.Object), every()
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:58)
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:64)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:54)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
at org.kohsuke.groovy.sandbox.impl.Checker$1.call(Checker.java:157)
at org.kohsuke.groovy.sandbox.GroovyInterceptor.onMethodCall(GroovyInterceptor.java:23)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onMethodCall(SandboxInterceptor.java:155)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onMethodCall(SandboxInterceptor.java:142)
at org.kohsuke.groovy.sandbox.impl.Checker$1.call(Checker.java:155)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:159)
at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.methodCall(SandboxInvoker.java:17)
at notworkingClass.MyFunction(WorkflowScript:5)
at WorkflowScript.run(WorkflowScript:12)
at ___cps.transform___(Native Method)

2 个答案:

答案 0 :(得分:1)

找到了解决方案……只是不想说,这并不明显,我也不知道为什么这一切都奏效。如果有人可以向我解释这一点,那么我会很高兴! from here

魔术线是示例类中的Script script

class A {
    Script script;
    public void a() {
        script.echo("Hello")
        script.sh('pwd')
    }
}

node('master'){
  def a = new A(script:this)
  echo "Calling A.a()"
  a.a()
}

就像将此上下文作为类并将其引用到变量或其他内容一样。

但是我仍然在寻找一种不欺骗构造函数的方法,该构造函数是这样的成员函数:

public testFunction(MyArg){
  hudson.jenkins.hidding.function.entry.echo(MyArg)
  // from my understanding, there must be something like this
}

println(WorkflowScript.metaClass.methods*.name.sort().unique())

它表明它至少不是WorkflowScript的一部分:

[$build, $buildNoException, blubb, equals, evaluate, #
 getBinding, getClass, getMetaClass, getProperty, hashCode,
 invokeMethod, main, notify, notifyAll, print, printf, println,
 run, setBinding, setMetaClass, setProperty, sleep, toString, wait]

答案 1 :(得分:1)

@Cutton Eye,我从here找到了一些消息,我认为原因是:库类不能直接调用诸如sh或git之类的步骤,但是我们可以通过脚本管道来调用它