Rebasing is boring
· 2 min read
The problem
When working in a team, you must ensure you sync code reviews with your default branch. Making sure you are up to date is definitely a chore and will take some time out of your day, but it will be worth it.
For me, the primary time sink is having to run the same commands and wait for the outputs each time.
git checkout <default branch>
git pull
git pull
again because I have not logged in today.git checkout <branch I was working on>
git rebase <default branch>
and hope there are no new merge conflicts.git push -f
- Check that my pipelines still work.
As you can imagine, this is a tedious process and can easily result in you messing up.
Solution
An easy fix is adding a new function to your cli. In my case, I use zsh
, so I will add it to my ~/.zshrc
file.
Code
tip
If you want to understand what is going on I recommend you use Explain Shell
update-branch() {
current_branch="$(git rev-parse --abbrev-ref HEAD)"
remote=$(git remote)
REPLY="Y"
if default_branch="$(git remote show "${remote}" | sed -n '/HEAD branch/s/.*: //p')"; then
vared -p "Rebase branch(${current_branch}) onto branch(${default_branch}) (Y/N)?: " -c REPLY
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
REPLY=""
git checkout "${default_branch}"
if git pull; then
git checkout "${current_branch}"
if git rebase "${default_branch}"; then
echo
else
vared -p "Unable to rebase without errors, abort (Y/N)?: " -c REPLY
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
git rebase --abort
fi
fi
fi
fi
else
echo "Unable to pull latest changes check your auth probably."
fi
}
note
Thanks to making this script I learnt that vared
exists for editing variables
and prompting users.
Bonus code
Here is a quick script to allow quick switching and creation of branches.
checkout-branch() {
branch="$1"
source_branch="${2:-main}"
REPLY="Y"
if git rev-parse --verify "${branch}" > /dev/null 2>&1; then
git checkout "${branch}"
else
vared -p "Can't find Branch(${branch}) new branch (Y/N)?: " -c REPLY
if [[ $REPLY =~ ^[Yy]$ ]]; then
vared -p "What source branch (Y/N)?: " -c source_branch
git checkout "${source_branch}" && git checkout -b "${branch}"
fi
fi
}