Created
January 24, 2019 09:24
-
-
Save deka108/bb3b3ae83cd953d3ea681d42b7a75c2c to your computer and use it in GitHub Desktop.
Create New GitHub Repo from CLI
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
#!/usr/bin/env bash | |
# Read usr inputs | |
read -p "Enter repo name (eg: USERNAME/REPO_NAME or ORG_NAME/REPO_NAME): " GITHUB_REPO && [[ -n $GITHUB_REPO ]] || { | |
echo "Error: REPO_NAME must exist!" >&2; exit 1; | |
} | |
read -p "Is the new repo an organization repo (y/N)?: " IS_ORG && [[ $IS_ORG == [yYNn] ]] || { | |
echo "IS_ORG must be either y (yes) or n (no)!" >&2; exit 1; | |
} | |
REPO_NAME=${GITHUB_REPO##*/} | |
USER_OR_ORGNAME=`echo $GITHUB_REPO | cut -d '/' -f1` | |
# Secrets | |
[[ -f secrets/github_token.json ]] || { echo "Error: github token is unavailable!" >&2; exit 1; } | |
GITHUB_API_TOKEN=`cat secrets/github_token.json | jq -r '.token'` | |
AUTH="Authorization: token $GITHUB_API_TOKEN" | |
# Github related APIs | |
GITHUB_API="https://api.github.com" | |
GITHUB_REPO_API="$GITHUB_API/repos/$GITHUB_REPO" | |
if [[ $IS_ORG == [yY] ]]; then | |
GITHUB_NEW_REPO_API="$GITHUB_API/orgs/$USER_OR_ORGNAME/repos" | |
else | |
GITHUB_NEW_REPO_API="$GITHUB_API/user/repos" | |
fi | |
# Check auth and github repo | |
status_code=`curl -o /dev/null -I -w "%{http_code}" -sH "$AUTH" "$GITHUB_REPO_API" || { | |
echo "Error: Invalid repo, token or network issue!" >&2; exit 1; }` | |
case "$status_code" in | |
"401") | |
echo "Error: Invalid token or authentication!" >&2; | |
exit 1; | |
;; | |
"404") | |
echo "Repo ${GITHUB_REPO} does not exist."; | |
read -p "Create new GitHub Repo (y/N): " operation && [[ $operation == [yYNn] ]] || { | |
echo "Operation must be either y (yes) or n (no)!" >&2 | |
exit 1 | |
}; | |
if [[ $operation == [yY] ]]; then | |
curl -i -H "$AUTH" -H "Content-Type: application/json" \ | |
-d "{ | |
\"name\": \"${REPO_NAME}\", \ | |
\"auto_init\": false, \ | |
\"private\": true | |
}" \ | |
${GITHUB_NEW_REPO_API}; | |
fi | |
;; | |
esac |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment