Groovy/Jenkins-如何在http请求正文中使用for循环 [英] Groovy/Jenkins - How to use a for loop inside the http request body

查看:322
本文介绍了Groovy/Jenkins-如何在http请求正文中使用for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图动态读取数组(每个元素是一个字符串),并使用这些字符串值替换当前的硬编码用户名.这是用于在Bitbucket中创建拉取请求.

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.

下面的#1和#2都属于同一类BitbucketUtil.groovy

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

    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
    }

我猜想使用功能getGroupUsers(groupName参数是teamName),我可以在createPullRequest函数内部替换"reviewers"中的硬编码字符串.但是我不确定如何在审阅者"下使用for循环,以便可以动态放置值:

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" } }
                                ]
                            }

任何帮助将不胜感激.

推荐答案

如果定义了您的姓名,并且您的最终目标是在其中包含所有名称的地图上创建一个列表列表,则只需collect名称中的地图.例如

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]]]]

如果您的目标是创建JSON正文,请不要连接字符串.使用Groovy提供的功能来创建JSON.例如

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]] }],
    // ...
])

这篇关于Groovy/Jenkins-如何在http请求正文中使用for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆