Home > Mobile >  how to fetch all GitLab comments of an MR in a Jenkins job
how to fetch all GitLab comments of an MR in a Jenkins job

Time:11-09

IN GitLab MRs we can add comments and we can also add feature to send automated comments in different stages of our Jenkins pipeline.

If I have the MR-ID of a particular MR, and I want to fetch all the MR comments done on that particular MR, then how can I do it in a Jenkins-Groovy environment? Is there are environment variable that can help me in this?

CodePudding user response:

In general, you would need to use the GitLab API.

Considering Comments on merge requests are done through notes, you would use List all merge request notes

GET /projects/:id/merge_requests/:merge_request_iid/notes
GET /projects/:id/merge_requests/:merge_request_iid/notes?sort=asc&order_by=updated_at

There are no dedicated environment variables provided by Jenkins, beside the parameters you would pass to your Job, like the project ID and MR ID.

You can see Groovy examples like this Jenkinsfile:

stage ("Merge Pull Request") {
    // GET PULL REQUEST ID
    sh "curl -H \"PRIVATE-TOKEN: ${approval_token}\" \"https://gitlab.com/api/v4/projects/${projectID}/merge_requests\" --output resultMerge.json"
    def jsonMerge = readJSON file: "resultMerge.json"                    
    echo "Request from: ${jsonMerge[0].author.name}"
    // STATUS VALIDATION
    if (jsonMerge[0].state == "opened") {
        // GET ALL COMMENTS ON PULL REQUEST
        sh "curl -H \"PRIVATE-TOKEN: ${approval_token}\" \"https://gitlab.com/api/v4/projects/${projectID}/merge_requests/${jsonMerge[0].iid}/notes\" --output comment.json"
        def commentJson = readJSON file: "comment.json"
        def checking = false
        // LOOP ALL COMMENT TO GET APPROVAL
        commentJson.each { res ->
            // CHECK IF CURRENT INDEX HAS SYSTEM FALSE 
            if (!res.system && !checking) {
                // IF COMMENT HAS VALUE: APPROVED AND AUTHOR IS VALID
                if (res.body == "Approved" && approval.contains(res.author.username)) {
                    addGitLabMRComment(comment: "Pull Request Approved by Jenkins")
                    acceptGitLabMR(useMRDescription: true, removeSourceBranch: false)
                } else {
                    currentBuild.result = 'ABORTED'
                    error("Sorry, your approval is not valid")
                }
                checking = true
            }
        }
    } else {
        error("Pull Request ${jsonMerge[0].title} ${jsonMerge[0].iid} is already ${jsonMerge[0].state}. Please Create a new Pull Request")
    }
    ...
}
  • Related