Last active
November 1, 2021 03:42
-
-
Save justinTM/e638cd88a92b8773948c4fd05713177c to your computer and use it in GitHub Desktop.
gitlab get project id from path with namespace from open merge requests. jq iterate string in array, jq select get matching item in list element in array, jq string split
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
OPEN_MERGE_REQUESTS="[\"my/project!14\", \"my/other/project!2\"]" | |
# parse input args and environment variables | |
if [ -z "$OPEN_MERGE_REQUESTS" ]; then echo "$0: need OPEN_MERGE_REQUESTS"; exit 1; fi | |
if [ -z "$GITLAB_TOKEN" ]; then echo "$0: need GITLAB_TOKEN"; exit 1; fi | |
curl_token="PRIVATE-TOKEN: ${GITLAB_TOKEN}" | |
# get project id from merge request strings like "<path-to-project>!<merge-request-iid" | |
for mr in "$( echo "$OPEN_MERGE_REQUESTS" | jq -c '.[]' )"; do | |
# split MR string on "!" into project path and MR IID | |
project_path="$( echo "$mr" | jq -r 'split("!")[0]' )" | |
mr_iid="$( echo "$mr" | jq -r 'split("!")[1]' )" | |
# get list of projects matching project name, only ones this account (from GITLAB_TOKEN) has membership to | |
project_search="https://gitlab.com/api/v4/projects?search=$(basename "$project_path")&membership=true" | |
curl -sSL -H "$curl_token" "$project_search" > "$projects" | |
# get project id from project matching full project path | |
project_id="$( jq -Rr --arg p "$project_path" 'fromjson? | .[] | select(.path_with_namespace == $p).id' "$projects" )" | |
is_success="$( echo "$project_id" | jq -Rr 'fromjson? | type=="number"' )" | |
if [ "$is_success" != "true" ]; then echo "ERROR: couldn't find \"$project_path\""; cat "$response"; exit 1; fi | |
# # make POST request to GitLab API with comment string, then write response to JSON file | |
# api_url="https://gitlab.com/api/v4/projects/${project_id}/merge_requests/${mr_iid}/notes" | |
# curl -s -X POST -H "$curl_token" "${api_url}" --data-urlencode "body=${MR_COMMENT_BODY}" > "$response" | |
# is_success="$( jq -R 'fromjson? | has("noteable_id")' "$response" )" | |
# if [ "$is_success" != "true" ]; then echo "ERROR"; cat "$response"; exit 1; fi | |
# # append response object as one line to responses file | |
# note_iid="$( jq -Rr 'fromjson? | .noteable_id' "$response" )" | |
# note_url="https://gitlab.com/${project_path}/-/merge_requests/${mr_iid}#note_${note_iid}" | |
# echo "$( jq -cR --arg url "$note_url" 'fromjson? | . + {note_url: $url}' "$response" )" >> "$responses" | |
done | |
# # return filepath to JSON response after joining lines of objects into array using slurp flag | |
# echo "$( jq -s '.' "$responses" )" > "$responses" | |
# cat "$responses" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment