Git Rebase

Today I learned about Git Rebase while making a code contribution (commit) to the Jetpack project on Github.

I had some issues setting up the Jetpack dev environment. The yarn build command wasn’t working as expected.

I tried fixing this by installing command line tools and XCode on Mac but that didn’t help. Digging things further, I realised yarn build worked fine on the master branch but was returning errors on the custom branch (the branch that I was currently working on).

To fix this, I thought it’d be nice if there was a way to reset my custom branch to the master branch and re-apply all the changes I had done so far. This would give me a branch that’s updated with the master branch along with the changes I had done so far on the custom branch.

Turns out, this can be achieved by running git rebase master command. I learned this from this StackOverflow post, which says:

git rebase master does what you’re asking for — takes the changes on the current branch (since its divergence from master) and replays them on top of master, then sets the head of the current branch to be the head of that new history. It doesn’t replay the changes from master on top of the current branch.

That fixed the issue. The command yarn rebuild worked just fine after I rebased my current branch with master 🙂

10 Common Git Commands

Here are some common git commands that I use on a regular basis to create pull requests on GitHub –

1. Shows all remotes
git remote

2. Shows remotes with their url
git remote -v

3. Gets remote data into local repo but doesn’t add to your working files
git fetch <remote>

4. Merge fetched data
git merge <remote>/master

5. Fetch and merge remote data with our working files
git pull
OR
git fetch <remote>
git checkout master
git merge <remote>/master

6. Add a remote
git add remote <name> <url>

7. Add remote branch as a local branch
git checkout --track <remote>/<branch_name>

8. Delete a branch locally
git branch -d <branch_name>
git branch -D <branch_name> force delete

9. Delete remote branch
git push <remote_name> --delete <branch_name>

10. Create and checkout a branch
git checkout -b <branch_name>

Bonus

I know I said 10 in the title but here are some more –

11. Rebase current branch with another branch.
git rebase <branch_name>

This will “port” another branch (Branch A) into the branch where you are currently working (Branch B), by applying all of your unique commits from Branch B on top of Branch A and replacing Branch B with this revised version. That way, you can “catch up” to other branches by re-writing git history in your local git. [Source]

12. See commits in current branch that aren’t cherry picked to master
git cherry -v master

13. Push a branch to remote
git push <remote> <branch>
git push <remote> <branch> -f force push

That’s all for now. If you’d like, go ahead and bookmark this page as I may add more to it in the future.