Git is an awesome tool. Git is also a very confusing tool.

I have compiled some golden snippets that I have encountered in my Git adventures, and this is probably a good place to keep them all in one place.

This post will be updated with new git snippets as I find new and useful ones over time.

Merging two repositories together (keeping histories)

I got this from here

Perfect for when you have a smaller project that you want to merge into a larger project! 💥

To merge project-a into project-b

cd path/to/project-b
git remote add project-a path/to/project-a
git fetch project-a
git merge --allow-unrelated-histories project-a/master
# or whichever branch you want to merge
git remote remove project-a

Beautiful little snippet, took me so much time and tries to find one that works exactly the way I wanted.

Adding one repository to another (keeping histories)

Got this from here

Sometimes you want to add a repository to another, and have the added repository reside in its own folder. For me, I wanted to add all my university repositories into one big repository, so that my repo count will be lower and be less cluttered.

I do this by:

git subtree add --prefix=foo git://github.com/fobar/bar.git master

This merge will appear as a single new commit where all of bar’s files are put into foo/. You can still git blame using the reference in the commit.

Add ‘foo/’ from commit

git log <rev>
git blame <rev> -- README.md

The difference between this and the previous one is that you can put the repository under its own folder.


Making small changes to committed commits

I hate micro-commits (still am guilty of it sometimes though, but I’m improving!) and sometimes I commit code and then realize I need to make a small correction. This will help!

git add file
git commit --amend

There are so many flags in git that can save the day, but because there are so many, the super helpful ones tend to become hard to find, under all the noise of the other flags (that I don’t use or isn’t smart enough to use 🤷‍)

In fact, git commit --amend can be used to change the commit message as well!


Undoing wrong branch commits

I don’t do this often, but still helpful to put here. It gave me a little headache the last time I did it. Who knew that a small mistake could waste you so much time 🤦‍

# soft flag leaves changes still available
git reset HEAD~ --soft
git stash
git checkout correct-branch
git stash pop
git add file
git commit -m 'message'

Amazing. Thanks Linus Torvalds.