Home > other >  Safely check if public GitHub repo exists in bash without login?
Safely check if public GitHub repo exists in bash without login?

Time:02-11

Context

While trying out the answer provided in this question on how to check if a GitHub repository exists using bash, I notice that the command asks for credentials and throws an error if the repository is not found:

git ls-remote https://github.com/some_git_user/some_non_existing_repo_name -q
Username for 'https://github.com': some_git_user 
Password for 'https://[email protected]': 
remote: Repository not found.
fatal: repository 'https://github.com/some_git_user/some_non_existing_repo_name/' not found
(base) somename@somepcname:~$ echo $?
128

This answer seems to prevent git from asking credentials.

Issues

  1. Being asked for credentials is fine in other scenarios, so I would prefer to not disable git from asking credentials system-wide. Yet still, I would like the function to run automatically without asking for credentials, as they are not needed for a check to a public repository.
  2. The command yields an error status 128 if it does not find the repository. Instead, I would like to safely check if the repository is found or not, without raising an error. E.g. by producing outputs echo "FOUND" or echo "NOTFOUND".

Question

How can one test if a public GitHub repository exists in bash, without being prompted for credentials, without raising an error?

Details

The user has not provided any ssh-key nor credentials to/in the script.

CodePudding user response:

In order to easily check if a public repository exists on GitHub, you actually need not git nor any credentials: you can make a simple HTTP request to the GitHub REST API.

Proof-of-concept:

#!/usr/bin/env bash
exists_public_github_repo() {
  local user_slash_repo=$1

  if curl -fsS "https://api.github.com/repos/${user_slash_repo}" >/dev/null; then
    printf '%s\n' "The GitHub repo ${user_slash_repo} exists." >&2
    return 0
  else
    printf '%s\n' "Error: no GitHub repo ${user_slash_repo} found." >&2
    return 1
  fi
}


if exists_public_github_repo "ocaml/ocaml"; then
  echo "OK"
fi

For more details on the curl command itself and the flags -f, -s, -S I used, you can browse its man page online.

  • Related