Home > Software design >  Pass newline in JSON string to a comment in gitlab pipeline
Pass newline in JSON string to a comment in gitlab pipeline

Time:08-26

I have a small bash script that calculate a code size difference and try to create a comment on the merge request when called from a pipeline.

delta=$(python scripts/python/codesizes.py diff build/release/artefacts/build.elf)
echo $delta 
json_data=$(jq -n \
--arg body "$delta" \
'{"body": $body}')
echo $json_data
echo $1 # CI_API_TOKEN
echo $2 # CI_COMMIT_REF_NAME
echo $3 # CI_API_V4_URL
echo $4 # CI_PROJECT_ID
merge_request_iid=$( \
        curl --request GET \
          --header "PRIVATE-TOKEN: $1" \
          "$3/merge_requests?scope=all&state=opened&source_branch=$2" | \
        jq '.[0].iid' \
      )
echo $merge_request_iid
curl --request POST \
        --header "PRIVATE-TOKEN: $1" \
        --header "Content-Type: application/json" \
        --data "$json_data" \
        "$3/projects/$4/merge_requests/${merge_request_iid}/notes"

This is what $delta looks like:

Using `git merge-base` against master branch
Comparing code size of current .elf against: 1234abcd...
 --------- -------- ------- ------- 
| Region  | .text  | .data | .bss  |
 --------- -------- ------- ------- 
| Local   | 206324 | 5012  | 44868 |
| Against | 202692 | 5016  | 44868 |
| Delta   | 3632   | -4    | 0     |
 --------- -------- ------- ------- 

Almost everything works perfectly, except passing this into a json string and then into the comment. This is what the comment on the MR looks like: Comment example

This particular comment was done through command lines to try out different format from the following text:

Using against master
Comparing code size of current .elf
 --------- 
|  Region |
 --------- 

I tried out with jq, without jq, through a text file, by replacing newlines by \\n, by using --data-binary. But I still cannot figure out how to parse it correctly so that the newlines are kept.

CodePudding user response:

After numerous tries, I ended up with using: delta="${delta//$'\n'/'<br />'}" to force a newline on the comment. This is because it is one of the ways to force markdown to have a newline. Using \ or double spaces did not work for me.

  • Related