Saturday, October 29, 2022

[SOLVED] How to delete and create a GitLab repository in Bash and ensure the action is completed?

Issue

Context

I've written a Bash script that automatically deletes a repo from a GitLab server, and that creates a new GitLab repo.

Code

The code that deletes the repository is:

delete_existing_repository() {
  local repo_name="$1"
  local repo_username="$2"

  # load personal_access_token
  local personal_access_token
  personal_access_token=$(echo "$GITLAB_PERSONAL_ACCESS_TOKEN_GLOBAL" | tr -d '\r')

  local output
  output=$(curl --silent -H 'Content-Type: application/json' -H "Private-Token: $personal_access_token" -X DELETE "$GITLAB_SERVER_HTTP_URL"/api/v4/projects/"$repo_username"%2F"$repo_name")

  if [  "$(lines_contain_string '{"message":"404 Project Not Found"}' "${output}")" == "FOUND" ]; then
    echo "ERROR, you tried to delete a GitLab repository that does not exist."
    exit 183
  fi
}

and the function that checks whether GitLab processed the repo push succesfully, is:

# Create repository.
  curl --silent -H "Content-Type:application/json" "$GITLAB_SERVER_HTTP_URL/api/v4/projects?private_token=$personal_access_token" -d "{ \"name\": \"$gitlab_repo_name\" }"  > /dev/null 2>&1 &
  sleep 30
  printf "\n Waiting 30 secs untill repo is (re)created in GitLab server."

Question

The issue is that I am experiencing some difficulties in determining when the GitLab repository is deleted successfully, and when it is created and processed successfully. Right now, I just "brute-force" wait 30 seconds, because so far, my system has been fast enough to do it within that time. However, that is inefficient, and unreliable because it should also work on slower systems. Hence I would like to ask:

How can I delete and create a GitLab repository in Bash, such that at the end of the command, the repo is completely deleted and (re)created successfully?


Solution

Partial answer: a fully created GitLab repo will be clonable. To test whether creation has completed, try to clone the repo. This can only succeed if the repo is fully created, and it will be fast since you're trying to clone an empty repo.

I don't have a suggestion for validating the deletion, though, because failure to clone would not confirm deletion is complete, although failure to create might indicate it's not.

However, if at the end of your bash script the clone yields an empty repo as expected, you know for sure that the delete + recreate operation was successful as a whole.



Answered By - joanis
Answer Checked By - Katrina (WPSolving Volunteer)