【问题标题】:Groovy/Jenkins - How to use a for loop inside the http request bodyGroovy/Jenkins - 如何在 http 请求正文中使用 for 循环
【发布时间】:2019-05-22 07:51:52
【问题描述】:

我正在尝试动态读取一个数组(每个元素都是一个字符串)并使用这些字符串值来替换当前的硬编码用户名。这是为了在 Bitbucket 中创建拉取请求。

下面的#1 和#2 都属于同一个类 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
    }

我猜测使用函数getGroupUsersgroupName 参数为teamName),我可以在createPullRequest 函数内替换"reviewers" 中的硬编码字符串。但我不确定如何在“审阅者”下使用 for 循环,以便动态放置值:

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

任何帮助将不胜感激。

【问题讨论】:

    标签: java jenkins groovy scripting jenkins-pipeline


    【解决方案1】:

    如果您的名称已定义,并且您的最终目标是在其中某处创建包含所有名称的地图列表,那么您只需 collect 名称中的地图即可。例如

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

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

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

    【讨论】:

    • 感谢@cfrick 的帮助。我的目标是使用函数prResponse 中的信息创建一个拉取请求。所以我相信这是第二种情况(创建 JSON 正文),但我不确定这里的 myMap 指的是什么。目前,修补程序 GM 脚本会在无法将更改合并到其他修补程序和开发时创建 PR。不幸的是,该脚本有一个硬编码的成员列表要添加到 PR。我应该让它查询 bitbucket API,获取成员列表,然后将它们添加到 PR。
    • 我已经编辑了答案以显示从转换为 json 的地图构建身体
    • 我明天会尝试,如果需要,我会提出更多问题。非常感谢!
    猜你喜欢
    • 2016-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-07
    • 1970-01-01
    相关资源
    最近更新 更多