如何从Jenkins Pipeline中的commit-Message中提取字符串

时间:2018-08-16 13:17:00

标签: jenkins groovy

我是使用jenkins groovy-pipelines的初学者,我想从git-commit-Message中提取一个子字符串(一个Jira-Issue-ID),如果该子字符串存在,我想发送邮件到指定的邮件地址(Jira-Mail-Handler)。目前,我尝试使用以下代码:

    node {
      stage('Checkout') {
        git credentialsId: '74190aae-546c-499d-bec6-2d4fa59ac79c', url: 'https://git.example.com/testrepo'
      }

      stage('Jira') {
          def commit = sh(returnStdout: true, script: 'git log -1 --pretty=%B | cat')
          def matcher = (commit =~ '.*(TEST-[0-9]*).*')

          if (matcher)
          {
            mail bcc: '', body: 'BUILD_URL', cc: '', from: '', replyTo: '', subject: matcher[0][1]+'Build was successfully', to: 'jira@example.com'
          }
      }
    }

但随后出现错误:

Caused: java.io.NotSerializableException: java.util.regex.Matcher

所以我开始搜索并找到this Thread,所以我尝试编写以下代码:

    @NonCPS
    def getCommitMsg() {
          def commit = sh(returnStdout: true, script: 'git log -1 --pretty=%B | cat')
          def matcher = (commit =~ '.*(TEST-[0-9]*).*')
          return matcher ? matcher[0][1] : null
    }

    node {
      stage('Checkout') {
        git credentialsId: '74190aae-546c-499d-bec6-2d4fa59ac79c', url: 'https://git.example/testrepo'
      }

      stage('Jira') {
          if (!getCommitMsg())
          {
            echo "Mail send!!!"
            mail bcc: '', body: 'BUILD_URL', cc: '', from: '', replyTo: '', subject: 'Build was successfully', to: 'john.doe@example.com'
          }
      }
    }

用于我的管道,但是使用此代码,groovy / jenkins并未输入if-Statement,现在我想我需要一点帮助,如果有人可以给我一些提示,我做错了,我将非常感谢? 最好的祝福 丹

1 个答案:

答案 0 :(得分:0)

   node {
      stage('Checkout') {
        git credentialsId: '74190aae-546c-499d-bec6-2d4fa59ac79c', url: 'https://git.example.com/testrepo'
      }

      stage('Jira') {
          def commit = sh(returnStdout: true, script: 'git log -1 --pretty=%B | cat')
          sh "bash -xe path/to/something.sh"
      }
    }

只执行一个shell脚本。

path/to/something.sh 
#!/bin/bash

if [[ $commit =~ '*TEST-[0-9]*' ]]  ; then 
    #do llike sendemail
fi