我面临的问题是从共享库函数/类调用git
插件。我有点迷茫,因为我的经验实际上只涉及到Jenkins声明性的东西,而不是Groovy / Java的细节。
以下是Jenkinsfile的代码段(在使用共享库之前):
pipeline {
agent any
stages {
stage('Prep Workspace') {
steps {
script {
if ((env.BRANCH_NAME == 'staging') || (env.BRANCH_NAME == 'production')) {
BRANCH=env.BRANCH_NAME
} else {
BRANCH='master'
}
}
echo "||------ Get ProjectOne Dependency ------||"
dir('deps/ProjectOne') {
git branch: "${BRANCH}",
changelog: false,
credentialsId: 'jenkinsgit',
poll: false,
url: 'git@github.com:myprivateorg/ProjectOne.git'
}
echo "||------ Get ProjectTwo Dependency ------||"
dir('deps/ProjectTwo') {
git branch: "${BRANCH}",
changelog: false,
credentialsId: 'jenkinsgit',
poll: false,
url: 'git@github.com:myprivateorg/ProjectTwo.git'
}
}
}
}
}
请注意重复调用以从git repos下拉项目文件。 此处的目标是将重复的代码移至共享函数调用。
我已经阅读了手册的以下部分,介绍如何在共享库中使用git
:
https://www.jenkins.io/doc/book/pipeline/shared-libraries/#accessing-steps
使用文档中的示例,我创建了共享库文件
在src/org/test/gitHelper.groovy
中:
package org.test;
def checkOutFrom(String repo, String branch='master') {
echo "||------ CLONING $repo ------||"
git branch: branch, changelog: false, credentialsId: 'jenkinsgit', poll: false, url: "git@github.com:myprivateorg/$repo.git"
}
return this
然后在Jenkinsfile
中输入
@Library('jenkins-shared-library') _
pipeline {
agent any
stages {
stage('Prep Workspace') {
steps {
script {
if ((env.BRANCH_NAME == 'staging') || (env.BRANCH_NAME == 'production')) {
BRANCH=env.BRANCH_NAME
} else {
BRANCH='master'
}
def g = new org.test.gitHelper()
g.checkOutFrom('ProjectOne')
g.checkOutFrom('ProjectTwo')
}
}
}
}
}
这将加载类并调用该函数,但是当它遇到git
本身时将失败:
groovy.lang.MissingPropertyException: No such property: git for class: java.lang.String
我使用g.getClass()
来确认它的类型为class org.test.gitHelper
而不是java.lang.String
,所以我不确定它是从哪里得到这种类型的。
请注意,我也尝试过这种方式:
vars/pullRepo.groovy
def call(String repo, String branch) {
echo "||------ CLONING $repo ------||"
dir("deps/$repo") {
git branch: branch, changelog: false, credentialsId: 'jenkinsgit', poll: false, url: "git@github.com:myprivateorg/$repo.git"
}
}
Jenkinsfile:
pullRepo('ProjectOne', 'master')
我得到了完全相同的错误:groovy.lang.MissingPropertyException: No such property: git for class: java.lang.String
答案 0 :(得分:0)
对我来说,它可以将Jenkins上下文传递给共享库,如下所示:
Jenkinsfile:
pullRepo(this, repo, branch)
vars/pullRepo.groovy:
def call(def context, String repo, String branch) {
echo "||------ CLONING $repo ------||"
dir("deps/$repo") {
context.git branch: branch, changelog: false, credentialsId: 'jenkinsgit', poll: false, url: "git@github.com:myprivateorg/$repo.git"
}
}
请注意,我正在将Jenkins上下文传递给上下文变量,并调用git作为上下文的方法。您还应该能够通过将上下文传递给您的类来做到这一点。