如何在Jenkins流水线中获取Git提交者信息

10

我在groovy中设置了一个管道,需要获取在git中提交了一些代码的人,以便我可以发布这个破坏构建的人的名字。我在网上搜索了很久,但似乎找不到解决方案。我已经通过使用jenkins的slack插件找到了如何在slack中发布内容的方法。例如:

slackSend color: 'warning', message: "${git.user_name} broke the build."
7个回答

7

您需要使用shell并执行git命令来检索数据,将其存储在文件中,然后将文件读入变量中,就像这样:

sh 'git log --format="%ae" | head -1 > commit-author.txt'                 
readFile('commit-author.txt').trim()                               

以上代码将为您提供最后一次提交的作者。

2
无需将其存储在文件中,参见@AlinSoare的答案。 - this

4
我使用以下方法。 首先,在 JenkinsFile 中添加一个阶段,从 git 日志中检索提交作者(及其消息)到一个 env. 变量中:
stage('get_commit_details') {
        steps {
            script {
                env.GIT_COMMIT_MSG = sh (script: 'git log -1 --pretty=%B ${GIT_COMMIT}', returnStdout: true).trim()
                env.GIT_AUTHOR = sh (script: 'git log -1 --pretty=%cn ${GIT_COMMIT}', returnStdout: true).trim()
            }
        }
    }

然后在构建后操作中发送Slack消息: (顺便说一句,我会发送到两个不同的频道(成功/失败),这样成功频道就可以被静音。)

post {
    failure {
        slackSend (channel: 'xyz-build-failure', color: '#FF0000', message: """FAILED:
Job: ${env.JOB_NAME}
Build #${env.BUILD_NUMBER}
Build: ${env.BUILD_URL})
Comitted by: ${env.GIT_AUTHOR}
Last commit message: '${env.GIT_COMMIT_MSG}'""")
    }
    success {
        slackSend (channel: 'xyz-build-success', color: '#00FF00', message: """SUCCESS:
Job: ${env.JOB_NAME}
Build #${env.BUILD_NUMBER}
Build: ${env.BUILD_URL})
Comitted by: ${env.GIT_AUTHOR}
Last commit message: '${env.GIT_COMMIT_MSG}'""")
    }
  }

3

有另一种方法可以获取这些信息。

Jenkins 中每个作业运行都有一个名为 ${env.BUILD_URL} 的变量。

如果你在 ${env.BUILD_URL} 后添加 "api/json",并使用 curl 命令访问该 URL,您将获取 Jenkins 关于该构建的所有信息。

提交者名称也会在那里显示:

  "commitId": "d2212180afc238fb423981d91f39d680dfd06c67",
  "timestamp": 1499117423000,
  "author": {
    "absoluteUrl": "https://jenkins.company.com/user/camelel",
    "fullName": "itai ganot"

以下命令将获取最后一位提交者的完整名称:
itai@Itais-MacBook-Pro ~/src/scripts -  (master) $ curl -s --insecure  https://jenkins.company.com/job/geek-kb/job/scripts/job/master/5/api/json | python -mjson.tool | grep fullName
                        "fullName": "itai ganot"

例子:

itai@Itais-MacBook-Pro ~/src/scripts -  (master) $ curl -s --insecure  https://jenkins.company.com/job/geek-kb/job/scripts/job/master/5/api/json
    {"_class":"org.jenkinsci.plugins.workflow.job.WorkflowRun","actions":[{"_class":"hudson.model.CauseAction","causes":[{"_class":"jenkins.branch.BranchIndexingCause","shortDescription":"Branch indexing"}]},{},{},{},{},{},{"_class":"hudson.plugins.git.util.BuildData","buildsByBranchName":{"master":{"_class":"hudson.plugins.git.util.Build","buildNumber":5,"buildResult":null,"marked":{"SHA1":"d2212180afc238fb423981d91f39d680dfd06c67","branch":[{"SHA1":"d2212180afc238fb423981d91f39d680dfd06c67","name":"master"}]},"revision":{"SHA1":"d2212180afc238fb423981d91f39d680dfd06c67","branch":[{"SHA1":"d2212180afc238fb423981d91f39d680dfd06c67","name":"master"}]}}},"lastBuiltRevision":{"SHA1":"d2212180afc238fb423981d91f39d680dfd06c67","branch":[{"SHA1":"d2212180afc238fb423981d91f39d680dfd06c67","name":"master"}]},"remoteUrls":["https://github.com/geek-kb/scripts.git"],"scmName":""},{"_class":"hudson.plugins.git.GitTagAction"},{},{"_class":"org.jenkinsci.plugins.workflow.cps.EnvActionImpl"},{},{},{},{"_class":"org.jenkinsci.plugins.workflow.job.views.FlowGraphAction"},{},{}],"artifacts":[],"building":false,"description":null,"displayName":"# 5 | master","duration":17807,"estimatedDuration":14531,"executor":null,"fullDisplayName":"Itai Ganot » scripts » master # 5 | master","id":"5","keepLog":false,"number":5,"queueId":4894,"result":"SUCCESS","timestamp":1499117462714,"url":"https://jenkins.company.com/job/geek-kb/job/scripts/job/master/5/","changeSets":[{"_class":"hudson.plugins.git.GitChangeSetList","items":[{"_class":"hudson.plugins.git.GitChangeSet","affectedPaths":["Jenkinsfile"],"commitId":"d2212180afc238fb423981d91f39d680dfd06c67","timestamp":1499117423000,"author":{"absoluteUrl":"https://lel.doesntexist.com/user/camelel","fullName":"itai ganot"},"authorEmail":"camelel@gmail.com","comment":"Test\n","date":"2017-07-04 00:30:23 +0300","id":"d2212180afc238fb423981d91f39d680dfd06c67","msg":"Test","paths":[{"editType":"edit","file":"Jenkinsfile"}]}],"kind":"git"}],"nextBuild":null,"previousBuild":{"number":4,"url":"https://lel.doesntexist.com/job/geek-kb/job/scripts/job/master/4/"}}itai@Itais-MacBook-Pro ~/src/scripts -  (master) $ curl -s --insecure  https://lel.doesntexist.com/job/geek-kb/job/scripts/job/master/5/api/json

为了更好的可读性,您可以使用Python的jsonTool或工具jq,它会将输出排序为JSON格式。

curl ${env.BUILD_URL}api/json | python -mjson.tool

或者

curl ${env.BUILD_URL}api/json | jq

2

一行代码:

def lastCommiterEmail = sh(returnStdout: true, script: 'git log --format="%ae" | head -1').trim()

0

提取用户电子邮件的方法。

script{
def COMMITTER_EMAIL = bat (
                script: "git --no-pager show -s --format=%%ae",
                  returnStdout: true
              ).split('\r\n')[2].trim()

    echo "The last commit was written by ${COMMITTER_EMAIL}"
}

0

如果您安装了Email Ext插件,另一种获取提交者的方法是:

def emailTo = emailextrecipients([culprits()])

0
对于Windows系统,您可以使用
script
{
   def committerDetails = bat ( 
      script: 'git log -n 1 --format="%%ae"',
      returnStdout: true
   )

   env.COMMITTER_EMAIL = committerDetails.tokenize('\n')[2]
}

并像这样使用它

mail to: "${env.COMMITTER_EMAIL}",
 from: 'someEmailAddress@email.com',
 subject: 'Buld Failures Detected', 
 body: "Job Failed - \"${env.JOB_NAME}\" build: ${env.BUILD_NUMBER}\n\nView the log at:\n ${env.BUILD_URL}\n\nBlue Ocean:\n${env.RUN_DISPLAY_URL}"

如果你想要分支上所有提交的所有电子邮件地址,你可以使用

def allCommitterDetails = bat ( 
 script: 'git log --format="%%ae"',
 returnStdout: true
)

def committersEmails = allCommitterDetails.tokenize('\n')
committersEmails .unique()
env.COMITTERS_EMAILS = committersEmails 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接