JoS*_*Ste 1 groovy jenkins jenkins-pipeline jenkins-shared-libraries
我正在为 Jenkins 创建自己的全局库,并将其托管在 github 上,为了简化一些常规任务,我想添加一个返回 GIT 标签的函数。
因此我创建了这样的东西:
class Myclass{
static String getGitTag() {
return "${sh(returnStdout: true, script: 'git tag --sort version:refname | tail -1').trim()}"
}
}
Run Code Online (Sandbox Code Playgroud)
...这会导致此错误:
没有方法签名:static com.stevnsvig.jenkins.release.ReleaseUtil.sh()
所以我留下两个问题:
sh()导入Jenkins 的常规风味显然已经导入的库的解决方案是导入吗?(如果是的话如何)GIT_TAG全局变量,而这样的事情(在我看来)应该很简单。 static String getGitTag() {
stdout = script.sh(script: "git tag --sort version:refname | tail -1", returnStdout: true)
return stdout.trim()
}
Run Code Online (Sandbox Code Playgroud)
产生类似的错误:
无方法签名:static com.stevnsvig.jenkins.release.ReleaseUtil.sh() 适用于参数类型:(java.util.LinkedHashMap) 值:[[returnStdout:true, script:git tag --sort version:refname | 尾巴-1]]
static String getGitTag() {
def stdout = "git tag --sort version:refname | tail -1".execute()
return stdout.in.text
}
Run Code Online (Sandbox Code Playgroud)
完成,但输出为空。运行相同的命令并pwd返回/,这表明环境尚未设置,这是有道理的,因为 Jenkins 下运行的所有命令都设计为在管道下运行
我去寻找进口货。在 github 上偶然发现了 Jenkins CI 项目,并开始搜索许多存储库。找到了一个有前途的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}"
}
Run Code Online (Sandbox Code Playgroud)
我得到的错误是相同的错误。我想自从它是插件以来,定义就不同了......
hudson.remoting.ProxyException:groovy.lang.MissingMethodException:没有方法签名:静态org.jenkinsci.plugins.workflow.steps.durable_task.ShellStep.sh()适用...
选项 1)使用 Groovyexecute运行 cmd 并获取其输出,如下所示
tag = "git tag --sort version:refname | tail -1".execute().text
Run Code Online (Sandbox Code Playgroud)
选项 2) 使用 Jenkins 管道步骤sh。
需要明确一个概念:上下文sh is global function是直接sh在 Jenkinsfile 中使用时的上下文。
在您的情况下,sh在 Jenkinsfile 之外使用。为了更好地理解,我举了一个 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`
}
}
}
Run Code Online (Sandbox Code Playgroud)
解决您的问题
// 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()
}
Run Code Online (Sandbox Code Playgroud)
// Jenkinsfile
import com.stevnsvig.jenkins.release.ReleaseUtil
pipeline {
stages('foo') {
steps {
ReleaseUtil.getGitTag(this)
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4317 次 |
| 最近记录: |