Groovy/Jenkins - How to use a for loop inside the http request body

Deadly 提交于 2019-12-25 03:24:08

问题


I am trying to dynamically read in an array (each element is a string) and use those string values to replace the current hardcoded user names. This is for creating pull request in Bitbucket.

Both #1 and #2 below belongs to the same class BitbucketUtil.groovy

1:

    def createPullRequest(projectSlug, repoSlug, title, description, sourceBranch, targetBranch) {
    //this is reading in the array with the user names
    def names = BitbutkcetUtil.getGroupUsers(teamName, activeOnly)

            def prResponse = this.steps.httpRequest(
                    acceptType: 'APPLICATION_JSON',
                    authentication: this.userId,
                    contentType: 'APPLICATION_JSON',
                    httpMode: 'POST',
                    ignoreSslErrors: true,
                    quiet: true,
                    requestBody: """
                                {
                                    "title": "${title}",
                                    "description": "${description}",
                                    "state": "OPEN",
                                    "open": true,
                                    "closed": false,
                                    "fromRef": { "id": "${sourceBranch}" },
                                    "toRef": { "id": "${targetBranch}" },
                                    "locked": false,
                                    "reviewers": [
                                        //I want to replace this hardcoded names with the string values inside the array `names`
                                        { "user": { "name": "HardCoded1" } },
                                        { "user": { "name": "HardCoded2" } },
                                        { "user": { "name": "HardCoded3" } },
                                        { "user": { "name": "HardCoded4" } }
                                    ]
                                }
                            """,
                    responseHandle: 'STRING',
                    url: "https://bitbucket.absolute.com/rest/api/latest/projects/${projectSlug}/repos/${repoSlug}/pull-requests",
                    validResponseCodes: '200:299')
            def pullRequest = this.steps.readJSON(text: prResponse.content)
            prResponse.close()
            return pullRequest['id']
        }

2:

   def getGroupUsers(groupName, activeOnly) {
        def getUsersResponse = this.steps.httpRequest(
                acceptType: 'APPLICATION_JSON',
                authentication: this.userId,
                ignoreSslErrors: true,
                quiet: true,
                responseHandle: 'STRING',
                url: "https://bitbucket.absolute.com/rest/api/latest/admin/groups/more-members?context=pd-teamthunderbird",
                validResponseCodes: '200:299')
        def usersPayload = this.steps.readJSON(text: getUsersResponse.content)['values']
        getUsersResponse.close()
        def users = []
        usersPayload.each { user ->
            if (!activeOnly || (activeOnly && user['active'])) {
                users.add(user['name'])
            }
        }
        return users
        //this is returning an array with string elements inside
    }

I am guessing using the function getGroupUsers (groupName parameter is teamName), I can replace the hard-coded strings in "reviewers" inside the createPullRequest function. But I'm not sure how I can use a for loop under the 'reviewers' so that I can dynamically put the values:

 "reviewers": [
                                    //I want to replace this hardcoded names with the string values inside the array `names`
                                    { "user": { "name": "HardCoded1" } },
                                    { "user": { "name": "HardCoded2" } },
                                    { "user": { "name": "HardCoded3" } },
                                    { "user": { "name": "HardCoded4" } }
                                ]
                            }

Any help would be greatly appreciated.


回答1:


If your names is defined and your ultimate goal here is to create a list of maps somewhere in them containing all the names, then you can just collect the the maps from the names. E.g.

def names = ["HardCoded1", "HardCoded2"]
println([reviewers: names.collect{ [user: [name: it]] }])
// => [reviewers:[[user:[name:HardCoded1]], [user:[name:HardCoded2]]]]

And if your goal is to create a JSON body, please dont concat strings. Use the facilities Groovy offers to create JSON. E.g.

groovy.json.JsonOutput.toJson([
    title: title,
    state: "OPEN",
    reviewers: names.collect{ [user: [name: it]] }],
    // ...
])


来源:https://stackoverflow.com/questions/53891589/groovy-jenkins-how-to-use-a-for-loop-inside-the-http-request-body

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!