Last active
October 29, 2020 19:03
-
-
Save othercodes/d4260674f72b8c0944cb7e809a04986b to your computer and use it in GitHub Desktop.
Restore git bracnh after git force push.
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 | |
# | |
# Git Branch checkout after force push | |
# | |
# Execution: | |
# $ bash checkout.sh [branch] | |
sudo chown -R www-data ./ | |
echo "Fetching changes from origin..." | |
sudo -Hu www-data git fetch -p | |
CURRENT=$(sudo -Hu www-data git name-rev --name-only HEAD) | |
echo -e "Current branch is \e[1m\e[32m$CURRENT\e[0m." | |
if [[ -n "$1" ]]; then | |
BRANCH="$1" | |
else | |
echo "Which branch you want to restore?" | |
read -r BRANCH | |
fi | |
if printf '%s\n' "$(sudo -Hu www-data git branch -r | cut -c 3-)" | grep -x -q "origin/${BRANCH}"; then | |
echo -e "Branch \e[1m\e[32m$BRANCH\e[0m selected to be restored, please confirm: y/n:" | |
read -r CONFIRMATION | |
if [[ ! $CONFIRMATION =~ ^[Yy]$ ]]; then | |
echo "Restoration aborted!" | |
exit 0 | |
fi | |
else | |
echo "Invalid branch, $BRANCH does not exist." | |
exit 1 | |
fi | |
echo "Resetting all changes in the current branch..." | |
sudo -Hu www-data git reset HEAD --hard >/dev/null 2>&1 | |
if [[ "$CURRENT" != "master" ]]; then | |
sudo -Hu www-data git checkout master | |
fi | |
echo "Checking untracked files..." | |
if [[ $(sudo -Hu www-data git status --porcelain | cut -d " " -f 2 | wc -l) -gt 0 ]]; then | |
sudo -Hu www-data git reset HEAD --hard >/dev/null 2>&1 | |
echo "Founded $(sudo -Hu www-data git status --porcelain | cut -d " " -f 2 | wc -l) changes:" | |
sudo -Hu www-data git status --porcelain | cut -d " " -f 2 | |
echo "Cleaning untracked files..." | |
sudo -Hu www-data git add . && sudo -Hu www-data git stash && sudo -Hu www-data git stash clear >/dev/null 2>&1 | |
echo "Checking untracked files after cleanup..." | |
echo "Founded $(sudo -Hu www-data git status --porcelain | cut -d " " -f 2 | wc -l) changes." | |
if [[ $(sudo -Hu www-data git status --porcelain | cut -d " " -f 2 | wc -l) -gt 0 ]]; then | |
echo "Please fix the remaining files manually." | |
exit 1 | |
fi | |
fi | |
if printf '%s\n' "$(sudo -Hu www-data git branch | cut -c 3-)" | grep -x -q "${BRANCH}"; then | |
sudo -Hu www-data git branch -D $BRANCH | |
fi | |
echo -e "Restoring \e[1m\e[32m$BRANCH\e[0m branch from origin..." | |
sudo -Hu www-data git checkout "$BRANCH" | |
echo "Done, have a nice day :D" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
bash <(curl -s https://gist.githubusercontent.com/othercodes/d4260674f72b8c0944cb7e809a04986b/raw/checkout.sh)