Sonia Hamilton
Sonia Hamilton

Reputation: 4419

vimdiff between current and previous git version of a file

Is there a way of using vimdiff to compare the current version of a file and the same file n git versions ago?

For example, I'm working on the file foo.c on the branch master. I'd like to do a vimdiff between foo.c and foo.c from master~10, to copy one or two lines across from the old version.

PS I'm aware of git cherry pick, but that's for whole files, not just a couple of lines.

Upvotes: 22

Views: 9676

Answers (4)

Rock Hupperts
Rock Hupperts

Reputation: 39

expanding on Arron's solution, I made a little bash function for my ~/.bashrc to vimdiff a file against a main branch or a prior commit, while actively editing the file.

alias nvimdiff='nvim -d'
nvimgitdiff() {
    if [[ "$#" == 2 ]]; then
        local ref=${1}
        local gitrelfp=${2}
        gitfullfp=$(git ls-files --full-name $gitrelfp)
        fname=$(basename ${gitrelfp})
        tmpfname=/tmp/$(sed "s/\//-/g" <<< $ref)-$fname
        git show $ref:$gitfullfp > $tmpfname
        nvimdiff $tmpfname $gitrelfp -c "setlocal nomodifiable"  # RO ref buffer
    else
        echo "usage: nvimgitdiff <ref|branch|commit> <relative-file-path>"
    fi
}

example usage:

nvimgitdiff feat-branch file.yaml
nvimgitdiff origin/master file.yaml
nvimgitdiff 91a89847a9 file.yaml
nvimgitdiff HEAD~3 file.yaml

Otherwise, I do like dandavison/delta as a pager for reviews

Upvotes: 0

Sonia Hamilton
Sonia Hamilton

Reputation: 4419

I was adding a PPS about this not being a use case for git difftool, then started wondering "what exactly does git difftool do...".

Solution is:

git difftool master master~10 -- foo.c

That is, presuming difftool is already set up correctly in ~/.gitconfig:

[diff]
  tool = vimdiff
[difftool]
  prompt = false

Upvotes: 20

Aaron
Aaron

Reputation: 341

A solution that works without overriding the git config would be

vimdiff file.tex <( git show master~2:file.tex )

Upvotes: 9

Ingo Karkat
Ingo Karkat

Reputation: 172590

For working with Git under Vim, the fugitive.vim - A Git wrapper so awesome, it should be illegal plugin is very useful. Check it out!

The vimdiff can be made with :Gdiff [revision].

Upvotes: 12

Related Questions