Jenkins流水線獲取提交日誌

  • 2019 年 11 月 6 日
  • 筆記

寫在前

之前使用Jenkins pipeline的時候發現拿不到日誌,使用multiple scms插件對應是日誌變數獲取日誌的方式失效了,

但是查看流水線Pipeline Syntax發現checkout竟然有包含提交日誌的選項,這裡一定有辦法獲取到日誌,苦於之前時間緊任務重,就先當它不能獲取日誌?

最近在搞點東西,順便想到了點關鍵詞終於google到了,沒看到其它部落格里有寫,就記錄一下

實現原理

在pipeline塊外部聲名一個使用@NonCPS修飾的方法,從構建時變數currentBuild.changeSets中獲取日誌對象,遍歷對象得到更新日誌

Groovy程式碼

在pipeline的stages/stage/script塊中調用這個方法就能得到日誌了,寫個最簡單的demo示意

#!groovy  // Declarative //  pipeline {      agent any      stages {          stage('拉程式碼') {              steps {                  //這裡就不寫了,用pipeline syntax生成一份checkout命令              }          }          stage('輸出日誌') {              steps {                  script{                      //調用方法得到日誌 並 輸出                      def changeString = getChangeString()                      echo "$changeString"                  }              }          }      }  }    @NonCPS  def getChangeString() {      MAX_MSG_LEN = 100      def changeString = ""        echo "Gathering SCM changes"      def changeLogSets = currentBuild.changeSets      for (int i = 0; i < changeLogSets.size(); i++) {          def entries = changeLogSets[i].items          for (int j = 0; j < entries.length; j++) {              def entry = entries[j]              truncated_msg = entry.msg.take(MAX_MSG_LEN)              changeString += " - ${truncated_msg} [${entry.author}]n"          }      }      if (!changeString) {          changeString = " - No new changes"      }      return changeString  }

currentBuild.changeSets數據結構偽程式碼

另外這裡輸出的部分不是changeSets的全部,下列偽程式碼參考了一些,又查API文檔寫了些,差不多夠用了,不夠的請參考api猜結構 :happy:

currentBuild.changeSets{      items[{          msg //提交注釋          commitId //提交hash值          author{ //提交用戶相關資訊              id              fullName          }          timestamp          affectedFiles[{ //受影響的文件列表              editType{                  name              }              path: "path"          }]          affectedPaths[// 受影響的目錄,是個Collection<String>              "path-a","path-b"          ]      }]  }

參考文章:

https://javadoc.jenkins.io/hudson/scm/ChangeLogSet.Entry.html#Entry–

https://support.cloudbees.com/hc/en-us/articles/217630098-How-to-access-Changelogs-in-a-Pipeline-Job-

https://issues.jenkins-ci.org/browse/JENKINS-30412?page=com.atlassian.jira.plugin.system.issuetabpanels%3Aall-tabpanel