Skip to content

Helpful git tricks

Mike Boyle edited this page Oct 18, 2023 · 4 revisions

Splitting a commit

Here is a nice trick for splitting commits buried in history into multiple commits.

Advanced merge/rebase conflict examination

Sometimes the git 'diff3' output doesn't make it obvious what to do with a conflict, especially when one of the conflicting commits changes many lines and another changes very few. Try the following commands to see specific diffs:

git diff :1:Filename :2:Filename   # Compare current branch with common ancestor
git diff :1:Filename :3:Filename   # Compare merged-in branch with common ancestor
git log --merge -p Filename        # Show both simultaneously to avoid running two separate commands

Rebasing with --onto

Sometimes you have multiple branches that depend on each other, and you need to rebase them onto each other or onto a main branch that has changed. One way to avoid git conflicts in this situation is to use git rebase --onto, which allows you to specify exactly which commits to include in a rebase and where in the commit chain to put them.

Here is a quick guide for using git rebase --onto.

Seeing and removing your old branches

As you create new branches, add some fanciness to the code, and then get a PR merged, you'll be left with lots of stale branches in your copy of the repo that you don't really need to hang onto. So you want a way to look through your branches and see which ones are old (and presumably unwanted).

In ~/.gitconfig add an alias, something like the following:

[alias]
        branches = for-each-ref --sort='-committerdate:iso8601' --format=' %(committerdate:short)%09%(refname)' refs/heads

Then, you should be able to run the command git branches and see a list of all branches in your repo, and the last time you made a commit on that branch.

For example, here's what I see on a repo I haven't cleaned up in a while:

> git branches
 2023-10-12     refs/heads/main
 2023-10-12     refs/heads/simpler_API
 2023-08-03     refs/heads/docs_references
 2022-05-09     refs/heads/out_of_place

Now, I happen know that I've already merged simpler_API, and I don't have any older branches that haven't been merged already, so I can go through and run git branch -D simpler_API and so on for each of these.

Clone this wiki locally