Git tips and tricks 2

This is an archive of blog post I wrote during my third venture (PullReview).

Since the last time I've shared a set of tips and tricks about Git, I've learned new ones that I regularly use. Again, hope they could help you as they helped me. Enjoy!

How to show the difference between two branches for a same file?πŸ”—

While you're coding into a <file> on a feature branch feature/mybranch, it is often useful to see exactly what you've changed. It's time to get a diff with the master branch:

git diff master HEAD -- <file>

or simply

git diff master -- <file>

You suddenly remember that one colleague told you he is also working on the same file in his own branch feature/hisbranch. You're curious to see the changes he made compared with the yours:

git diff feature/hisbranch HEAD -- <file>

How to stop tracking a file?πŸ”—

An output <file> is tracked when it shouldn't be. You put it into .gitignore, but it's still there. It's because you need to remove it from the index with

git rm --cached <file>

Then, you just need to commit that change

git commit

How to show the diff with the staged changes?πŸ”—

You've staged several changes at different moments, so you're not sure anymore what were your changes exactly. You would like to inspect them before committing. Just type

git diff --cached

How to pick only a part of a given commit?πŸ”—

Someone has just merged a branch containing an important security fix that you would like to apply in your feature branch. But the fix wasn't committed alone. There are other changes that don't interest you. You only want a part of the commit. First of all, you need to cherry pick it and put in stage

git cherry-pick -n <commit>

Then, unstage all the changes

git reset

Stage only the changes containing the security fix

git add <file>

Finally commit them.

How to dry run merge?πŸ”—

You don't like surprises. Before merging master into a feature branch, you would like to dryly run the merge. First you need to retrieve the common ancestor

git merge-base HEAD master

Then, you can run the merge in memory with git merge-tree

git merge-tree <sha-obtained-with-merge-base> master HEAD

That will give you the result of a merge without changing the working copy.

How to prune all your local branches that track an already-deleted remote branch?πŸ”—

You're tracking some remote branches, but you don't know that some of them have been remotely deleted. Git pull won't remove those ones when you pull, you need to delete them with a specific command:

git remote prune origin --dry-run

will give you a list of staled remote branches. If you're ok with that list, you can effectively prune them without the parameter --dry-run

git remote prune origin

That's it for today.

Do you have you a git command that you use daily? Don’t hesitate - please share it!


If you have any comment, question, or feedback, please share them with me.


Atom feed icon Subscribe to the blog!