简体   繁体   中英

How to use GitHub commit message and commit id inside Jenkins pipeline?

I am using DevOps model, where i have built a pipeline for code build and deploy. In the entire process i want to log the Git commit id and commit message for that specific change commits.

@shruthibhaskar
shruthibhaskar committed just now 
1 parent 51132c4 commit aedd3dc56ab253419194762d72f2376aede66a19

and commit message and description as below

test commit 3

test commit desc 3

how do i access these values of commit inside my jenkins pipeline, where i have configured a webhook for SCM polling?

git log --format=format:%s -1 (latest commit)

git log --format=format:%s -1 ${GIT_COMMIT} (specific commit)

git --no-pager show -s --format='%s' ${GIT_COMMIT}

Jenkins git plugin set some environment variables for every build. You can find the list of them in git plugin site . In which it gives the SHA of the current commit in ${GIT_COMMIT} environment variable.

You can use the SHA along with git log to print commit message and any other details you required with --pretty option.

git log --oneline -1 ${GIT_COMMIT} # prints SHA and title line
git log --format="medium" -1 ${GIT_COMMIT} # print commit, author, date, title & commit message

You can make a message based on currentBuild.changeSets , for example:

@NonCPS
def sendChangeLogs() {
    def commitMessages = ""
    def formatter = new SimpleDateFormat('yyyy-MM-dd HH:mm')
    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]
            commitMessages = commitMessages + "${entry.author} ${entry.commitId}:\n${formatter.format(new Date(entry.timestamp))}: *${entry.msg}*\n" 
        }
    }
    slackSend color: "good", message: "Job: `${env.JOB_NAME}`. Starting build with changes:\n${commitMessages}"
}

And call it:

stage('Clone repository') {
    steps {
        checkout scm

        script {
            sendChangeLogs()
        }
    }
}

PS

@NonCPS needs to except serialization error. I've found it here

you can curl the api with personal token for gitlab scm to get the commit message & numerous other information. Here you need create personal token and save it in jenkins via secret text & then use it in pipeline stages.

curl --header "Private-Token: asdfasdfasdf" https://gitlab.com/api/v4/projects/2445653/repository/commits/master

you can check out the documentation for more information. https://docs.gitlab.com/ee/api/commits.html

enter image description here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM