I am working on source code and want to review the code of a previous commit. Usually I would do this with git difftool --dir-diff
and meld as the difftool. However, when I want to look at a farther back commit, or a commit that was prior to a refactor, meld makes it hard to read because the code is altered too much.
The other solution I can think of is to git stash
the changes, checkout the other commit and view the code. But then I can't view my current code and it also takes quite long.
I am looking for (maybe) a tool, that opens the source code of a previous commit for me to view parallel to the current code. Basically like the dirdiff
solution without the diff part. I am using the git cli. Thanks and best regards.
For a situation like this, I prefer to use git worktree add
. This creates a separate git checkout
(or git switch
in Git 2.23 or later), in a separate work-tree that has its own private index / staging-area and other private items, so that the separate work-tree does not interfere with your ongoing work in your main work-tree.
The independent work-tree can be used as much as you like, or left alone as much as you like. It is a full checkout. The main constraint on an added work-tree is that it must be on a different branch from any existing work-tree (including other added work-trees), but if you intend to look at one specific commit, you can just use the "detached HEAD" mode in the added work-tree to view the one specific commit. All detached-HEAD added work-trees are by definition not on any branch at all and therefore are OK.
There are two minor caveats—things to be aware of—when using git worktree
:
It was first added in Git 2.5, so if your Git is older than that, you don't have it.
It had a pretty gnarly bug in it until Git 2.15. This bug only affects an addded work-tree where you make changes to it and then let them sit around for two weeks or more, so if all you are doing is inspecting an old commit, it won't bite you at all. If you start making heavy use of git worktree add
, though, I recommend being sure your Git version is at least 2.15.