Created
August 31, 2019 13:33
-
-
Save arienkock/02c8d30df27d4cf0073337e5487e49a4 to your computer and use it in GitHub Desktop.
Script to create a private remote on GitHub (using the REST API) and pushing `--all` refs to it from a local repo. Useful if you have many local experimental repos and no remotes for backup.
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 | |
REPO_DIR=$1 | |
if [ -z $GH_USERNAME ] || [ -z $GH_PASSWORD ]; then | |
echo "Env vars GH_USERNAME and GH_PASSWORD are required." | |
exit 1 | |
fi | |
if [ -z $REPO_DIR ]; then | |
echo "You must specify a repo directory as first argument to this command." | |
exit 1 | |
fi | |
CREDENTIALS="$GH_USERNAME:$GH_PASSWORD" | |
cd "$REPO_DIR" | |
if [ ! -d .git ]; then | |
echo Not a git repo | |
exit 1 | |
fi | |
REPO_NAME=`basename $PWD` | |
echo Repo name based on directory name is \"$REPO_NAME\" | |
git remote get-url origin &>/dev/null && echo "Repo $REPO_NAME already has a remote called origin. Exiting..." && exit 1 | |
require_clean_work_tree () { | |
# Update the index | |
git update-index -q --ignore-submodules --refresh | |
err=0 | |
# Disallow unstaged changes in the working tree | |
if ! git diff-files --quiet --ignore-submodules -- | |
then | |
echo >&2 "cannot $1: you have unstaged changes." | |
git diff-files --name-status -r --ignore-submodules -- >&2 | |
err=1 | |
fi | |
# Disallow uncommitted changes in the index | |
if ! git diff-index --cached --quiet HEAD --ignore-submodules -- | |
then | |
echo >&2 "cannot $1: your index contains uncommitted changes." | |
git diff-index --cached --name-status -r --ignore-submodules HEAD -- >&2 | |
err=1 | |
fi | |
if [ $err = 1 ] | |
then | |
echo >&2 "Please commit or stash them." | |
exit 1 | |
fi | |
} | |
EMPTY_TREE_HASH=`git hash-object -t tree /dev/null` | |
if [ $(git write-tree) == "$EMPTY_TREE_HASH" ] || ! (require_clean_work_tree --) | |
then | |
echo Uncommitted changes | |
git checkout -b before-githubbing-the-things | |
git add . | |
git commit -m"Comitting untracked changes before backing up repo" | |
fi | |
curl --fail --silent -u "$CREDENTIALS" -X POST -i https://api.github.com/user/repos -d ' | |
{ | |
"name": "'$REPO_NAME'", | |
"description": "Private GitHub repo generated automatically", | |
"homepage": "https://github.com", | |
"private": true, | |
"has_issues": false, | |
"has_projects": false, | |
"has_wiki": false | |
}' | |
echo Pushing to "https://github.com/$GH_USERNAME/$REPO_NAME.git" | |
git push --all "https://$CREDENTIALS@github.com/$GH_USERNAME/$REPO_NAME.git" | |
git remote add origin "https://github.com/$GH_USERNAME/$REPO_NAME.git" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment