Jenkins流水線獲取提交日志


寫在前

之前使用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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM