Search code examples
curljqgithub-apixq

How can I post multiple json objects in a single pull request comment in curl?


I have the following output that I wanted to post to a github pull request as a comment

{
  "@name": "testWalletDeepLinkLoginFlow",
  "@classname": "iphone13pro-15.7-en-portrait#.AppUI-Tests.WalletDeepLinkLoginFlowTest",
  "@time": "30.246",
  "failure": "Failure at /Users/vagrant/git/AppUITests/Extensions/XCUIElement+Additions.swift:30 - Assertion Failure at XCUIElement+Additions.swift:30: Failed to get matching snapshot: No matches found for first query match sequence: `Descendants matching type TextField` -> `Elements matching predicate '\"input_country_search\" IN identifiers'`, given input App element pid: 627 (no attribute values faulted in)",
  "webLink": "https://console.firebase.google.com/project/app-54934/testlab/histories/bh.388190097b1eab25/matrices/9067272573409626190/details"
}
{
  "@name": "testWalletDeepLinkMainFlow",
  "@classname": "iphone13pro-15.7-en-portrait#.AppUI-Tests.WalletDeepLinkMainFlowTest",
  "@time": "50.672",
  "failure": "Failure at /Users/vagrant/git/AppUITests/DeepLinks/Wallet/WalletDeepLinkMainFlowTest.swift:17 - Assertion Failure at WalletDeepLinkMainFlowTest.swift:17: XCTAssertTrue failed",
  "webLink": "https://console.firebase.google.com/project/app-54934/testlab/histories/bh.388190097b1eab25/matrices/7233833673388432629/details"
}

I prepare the github pull request comment with the following method

generate_pull_request_payload()
{
  cat <<EOF
{
  "body": "$FAILED_TESTS"
}
EOF
}

I use xq command line tool to fetch only failed tests and use the output above to post to github with the following curl

curl -X POST "https://api.github.com/repos/owner/repo/issues/3943/comments" \
  -H "Authorization: token $GITHUB_TOKEN" \
  -H "Content-type: text/json; charset=utf-8" \
  --data "$(generate_pull_request_payload)"

I expected to have the output posted to a comment


Solution

  • I suggest to not use shell string interpolation to generate JSON; instead use jq directly to produce your expected output document:

    generate_pull_request_payload()
    {
      xq -r '.testsuites.testsuite.testcase[] | select(.failure)' < JUnitReport.xml \
      | jq -sR '{ body: . }'
    }
    

    There shouldn't be a need for @text if you format JSON directly, without going through plain text and string interpolation in the first place.

    And eventually read the data for the post request directly from stdin:

    generate_pull_request_payload | curl -X POST "https://api.github.com/repos/owner/repo/issues/3943/comments" \
      -H "Authorization: token $GITHUB_TOKEN" \
      -H "Content-type: text/json; charset=utf-8" \
      -d @-