从Jenkinsfile获取源存储库的详细信息

时间:2018-05-01 00:25:43

标签: git jenkins continuous-integration jenkins-pipeline

Jenkinsfile使用checkout scm命令从链接的Bitbucket存储库中检索最近的提交。

  

需要向Jenkinsfile添加哪些特定语法才能使Jenkinsfile能够从源存储库中提取repositorySlugprojectKey作为变量,然后将这些变量打印为控制台输出?**


示例Jenkinsfile:

我尝试在以下示例Jenkinsfile中合并来自Jenkins Pipeline SCM Step Documentation的想法,其结果日志将在下面进一步显示:

node {
    // Clean workspace before doing anything
    deleteDir()

    try {
        stage ('Clone') {
            def commitHash = checkout(scm).GIT_COMMIT
            sh "echo 'Commit hash is: ${commitHash}'"
            println commitHash

            def repName = checkout(scm).repoName
            sh "echo 'Repository Name is: ${repName}'"
            println repName

            def rep = checkout(scm).repo
            sh "echo 'Repository is: ${rep}'"
            println rep

            def nm = checkout(scm).name
            sh "echo 'Name is: ${nm}'"
            println nm
        }
    } catch (err) {
        currentBuild.result = 'FAILED'
        throw err
    }
}  


当前输出:

以下是Jenkins在运行前面的Jenkinsfile时生成的控制台输出:

General SCM<1s
echo 'Commit hash is: bd279b90ad9f78ee8abb4d4fbf2a621d42150dd3'— Shell Script<1s
bd279b90ad9f78ee8abb4d4fbf2a621d42150dd3— Print Message<1s
General SCM<1s
    > git rev-parse --is-inside-work-tree # timeout=10
    Fetching changes from the remote Git repository
     > git config remote.origin.url http://<bitbucket-ip-on-lan>:7990/scm/JSP/jenkinsfile-simple-repo.git # timeout=10
    Fetching without tags
    Fetching upstream changes from http://<bitbucket-ip-on-lan>:7990/scm/JSP/jenkinsfile-simple-repo.git
     > git --version # timeout=10
    using GIT_ASKPASS to set credentials 
     > git fetch --no-tags --progress http://<bitbucket-ip-on-lan>:7990/scm/JSP/jenkinsfile-simple-repo.git +refs/heads/sample-issue-branch:refs/remotes/origin/sample-issue-branch
    Checking out Revision bd279b90ad9f78ee8abb4d4fbf2a621d42150dd3 (sample-issue-branch)
     > git config core.sparsecheckout # timeout=10
     > git checkout -f bd279b90ad9f78ee8abb4d4fbf2a621d42150dd3
    Commit message: "name"
    [Bitbucket] Notifying commit build result
echo 'Repository Name is: null'— Shell Script<1s
null— Print Message<1s
General SCM<1s
echo 'Repository is: null'— Shell Script<1s
null— Print Message<1s
General SCM<1s
echo 'Name is: null'— Shell Script<1s
null— Print Message<1s

请注意,projectKeyrepositorySlug在以上日志中可用,形式为:

http://<bitbucket-ip-on-lan>:7990/scm/JSP/jenkinsfile-simple-repo.git


重申问题:

  

对于上面的数据,需要将哪些特定语法添加到Jenkins文件中,以便生成的Jenkins日志打印出以下内容:

The projectKey is: JSP
The repositorySlug is: jenkinsfile-simple-repo

1 个答案:

答案 0 :(得分:1)

这应该有效,但可能有一种我目前不知道的简单方法。

基本上,它会检索SCM插件返回的完整网址,将其拆分为/并提取您需要的部分。

def repoUrl = checkout(scm).GIT_URL
def key = repoUrl.tokenize('/')[3]
def slug = repoUrl.tokenize('/')[4]
slug = slug.substring(0, slug.lastIndexOf('.')) //Remove .git
echo "The projectKey is: ${key}"
echo "The repositorySlug is: ${slug}"