Some git tricks

Posted by Fabrice on Monday, April 22, 2019 Updated on Sunday, May 14, 2023 Translation: fr

Some git tricks I use from time to time and that I forgot everytime…

Disclaimer: I'm not the perfect git user, and my way of using it is especially crude. Recently, most of my git commits are due to pass, therefore most of those commands are here to fix my own mistakes.

Reset master to origin/master:

git checkout origin/master -B master

Jump back and forth from a commit to another (same behaviour as :

git checkout -

Find back lost commits, especially useful when you are doing dirty things and want to cherry-pick an orphan commit (for instance):

git log --graph --reflog

Some explanations: --graph show the commit tree, which is useful to notice the orphan leafs, and --reflog shows the world all the dirtiness you've done.

If you noticed that your folder grows, you can manually cast the garbage collector on it. It should do it automatically, but not often enough according to my standards.

git gc --aggressive

To add changes in an atomic fashion on a file (in an interactive way):

git add -p <file>

Unsafe: to remove a file from the past (for instance when you commit some sensitive file):

git filter-branch --prune-empty --tree-filter "rm -f '<file name>'" HEAD
git push --force

Another useful trick is git commit -v, it allows reviewing your changes before committing.

Use of git commit -v

A ncurse-based interface for git: tig

tig

To make diffs more readable, I highly recommend to use delta as a diff filter: https://github.com/dandavison/delta. It makes the display of git diff close to what you can get in a browser repository, highlighting the places where diffs actually happen and is highly reconfigurable.

Once it is installed in your package manager, you can for instance configure it as follows (mostly the same as in the GitHub page):

[core]
  pager = delta
[interactive]
  diffFilter = delta --color-only
[delta]
  navigate = true    # use n and N to move between diff sections
  light = true      # set to true if you're in a terminal w/ a light background
  theme=Monokai Extended Light
[merge]
  conflictstyle = diff3
[diff]
  colorMoved = default

tags: git, termtosvg, cli