我正在为Jenkins创建自己的全局库,我拥有hosted on github,并且为了简化一些常规任务,我想添加一个返回GIT标签的函数。
因此,我创建了这样的内容:
class Myclass{
static String getGitTag() {
return "${sh(returnStdout: true, script: 'git tag --sort version:refname | tail -1').trim()}"
}
}
...导致此错误:
没有方法签名:静态com.stevnsvig.jenkins.release.ReleaseUtil.sh()
所以我有两个问题:
sh()
库的解决方案吗? (如果可以的话)GIT_TAG
全局变量,而这样的事情(在我看来)应该像馅饼一样容易。 static String getGitTag() {
stdout = script.sh(script: "git tag --sort version:refname | tail -1", returnStdout: true)
return stdout.trim()
}
产生类似的错误:
没有方法签名:静态com.stevnsvig.jenkins.release.ReleaseUtil.sh()适用于参数类型:(java.util.LinkedHashMap)值:[[returnStdout:true,script:git tag --sort版本:refname |尾巴-1]]
static String getGitTag() {
def stdout = "git tag --sort version:refname | tail -1".execute()
return stdout.in.text
}
完成,但是输出为空白。使用pwd
运行相同的命令将返回/
,这表明未设置环境,这是有道理的,因为在Jenkins下运行的所有命令都旨在在管道下运行
我去寻找进口。在github上偶然发现了Jenkins CI项目,并开始搜索许多存储库。 Found a promising one ...并将名为pwd.groovy
的文件放在/vars
中,内容如下:
import org.jenkinsci.plugins.workflow.steps.durable_task.ShellStep
static String getPWD() {
def ret = ShellStep.sh(returnStdout: true, script: "git tag --sort version:refname | tail -1").trim()
echo "currently in ${ret}"
}
我得到的错误是相同的变化。我猜因为它的插件,定义是不同的...
hudson.remoting.ProxyException:groovy.lang.MissingMethodException:无方法签名:静态org.jenkinsci.plugins.workflow.steps.durable_task.ShellStep.sh()适用...
答案 0 :(得分:1)
选项1)使用Groovy execute
运行cmd并获得如下输出
tag = "git tag --sort version:refname | tail -1".execute().text
选项2)使用Jenkins管道步骤sh
。
需要弄清楚一个概念:sh is global function
的上下文是sh
在Jenkinsfile中直接直接使用时。
在您的情况下,sh
在Jenkins文件外部使用。为了更好地理解,我举一个Jenkinsfile示例。
pipeline {
stages('foo') {
steps {
sh 'pwd'
// In above sh step, there is an implicit `this` which represents the
// global object for Jenkinsfile, you can image sh 'pwd' to this.sh 'pwd'
//
// Thus if you want to use `sh` outside Jenkinsfile, you must pass down the
// implicit `this` into the file where you used `sh`
}
}
}
解决您的问题
// ReleaseUtil.groovy
static String getGitTag(steps) {
// here `steps` is the global object for Jenkinsfile
// you can use other pipeline step here by `steps`
steps.echo 'test use pipeline echo outside Jenkinsfile'
steps.withCredentials([steps.string(credentialsId: 'git_hub_auth', variable: 'GIT_AUTH_TOKEN')]) {
steps.echo '....'
steps.sh '....'
}
return steps.sh(returnStdout: true, script:"git tag --sort version:refname | tail -1").trim()
}
// Jenkinsfile
import com.stevnsvig.jenkins.release.ReleaseUtil
pipeline {
stages('foo') {
steps {
ReleaseUtil.getGitTag(this)
}
}
}