94713efc968d0b12c86f2abc1626c7a0e43ec4bb
[it/test.git] / XTesting / kubespray / scripts / premoderator.sh
1 #!/bin/bash
2 # A naive premoderation script to allow Gitlab CI pipeline on a specific PRs' comment
3 # Exits with 0, if the pipeline is good to go
4 # Exits with 1, if the user is not allowed to start pipeline
5 # Exits with 2, if script is unable to get issue id from CI_BUILD_REF_NAME variable
6 # Exits with 3, if missing the magic comment in the pipeline to start the pipeline
7
8 CURL_ARGS="-fs --retry 4 --retry-delay 5"
9 MAGIC="${MAGIC:-ci check this}"
10 exit_code=0
11
12 # Get PR number from CI_BUILD_REF_NAME
13 issue=$(echo ${CI_BUILD_REF_NAME} | perl -ne '/^pr-(\d+)-\S+$/ && print $1')
14
15 if [ "$issue" = "" ]; then
16   echo "Unable to get issue id from: $CI_BUILD_REF_NAME"
17   exit 2
18 fi
19
20 echo "Fetching labels from PR $issue"
21 labels=$(curl ${CURL_ARGS} "https://api.github.com/repos/kubernetes-sigs/kubespray/issues/${issue}?access_token=${GITHUB_TOKEN}" | jq '{labels: .labels}' | jq '.labels[].name' | jq -s '')
22 labels_to_patch=$(echo -n $labels | jq '. + ["needs-ci-auth"]' | tr -d "\n")
23
24 echo "Checking for '$MAGIC' comment in PR $issue"
25
26 # Get the user name from the PR comments with the wanted magic incantation casted
27 user=$(curl ${CURL_ARGS} "https://api.github.com/repos/kubernetes-sigs/kubespray/issues/${issue}/comments" | jq -M "map(select(.body | contains (\"$MAGIC\"))) | .[0] .user.login" | tr -d '"')
28
29 # Check for the required user group membership to allow (exit 0) or decline (exit >0) the pipeline
30 if [ "$user" = "" ] || [ "$user" = "null" ]; then
31   echo "Missing '$MAGIC' comment from one of the OWNERS"
32   exit_code=3
33 else
34   echo "Found comment from user: $user"
35
36   curl ${CURL_ARGS} "https://api.github.com/orgs/kubernetes-sigs/members/${user}"
37
38   if [ $? -ne 0 ]; then
39     echo "User does not have permissions to start CI run"
40     exit_code=1
41   else
42     labels_to_patch=$(echo -n $labels | jq '. - ["needs-ci-auth"]' | tr -d "\n")
43     exit_code=0
44     echo "$user has allowed CI to start"
45   fi
46 fi
47
48 # Patch labels on PR
49 curl ${CURL_ARGS} --request PATCH "https://api.github.com/repos/kubernetes-sigs/kubespray/issues/${issue}?access_token=${GITHUB_TOKEN}" -H "Content-Type: application/json" -d "{\"labels\": ${labels_to_patch}}"
50
51 exit $exit_code