skip to Main Content

Let’s say at a previous commit some feature was working and I altered the code related to that feature after the commit. I want to compare the code from the working commit with the current code. What is the best way to do this?
`
I can run git checkout commithash but it means I have to switch back and forth between the current branch and old commit.

Update

It turns out there is a git command designed for this exact use case:

  1. Get the of the working code.
  2. Checkout the branch where your bug is.
  3. Run git diff <commit-hash>

If it’s hard to pinpoint the code differences due e.g. the volume of code, try running git diff <commit-hash> -- file-path. This will show the differences in a VIM editor.

If the Vim editor isn’t helping try:

  1. git checkout <commit-hash>
  2. Copy the file
  3. git checkout og_branch
  4. Create a new file e.g. settings_old.py and paste the old working code in it.
  5. Open up each file side by side to compare.

2

Answers


  1. Git does not work like that.

    You can either use VS Code external Plugins (such as GitLens), or use git tooling (gitk for example) to inspect old changes.

    gitk <COMMIT-HASH>

    I would go with the first option and install GitLens – it’s a great plugin that allows you to do exactly what you’re after.

    Login or Signup to reply.
  2. If you want to compare a lot of files or even directories with an external tool, another solution is to use git worktree feature.

    You could checkout code at a given commit inside another ‘wortree’ directory with the command:

    git worktree add --detach <path-to-new-folder-outside-current-repo> <commit-hash>
    

    Then you have your current branch and the checked out commit folders side by side and you could open 2 instances of Vscode or use an external tool able to compare directories.

    See git worktree doc for more details: https://git-scm.com/docs/git-worktree

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search