3

I have moved some code from a file to another file, and applied little changes in it. I would like to have a diff to see those changes.

The problem seems pretty common to me, but I have never needed to do such a thing. I only know how to compare the same file with himself in a previous revision, or 2 different files in the same revision.

Are there git diff options to compare one file in the current revision to another file in another commit? Or any other way?

Joffrey
  • 32,348
  • 6
  • 68
  • 100
  • Possible duplicate http://stackoverflow.com/questions/17563726/git-diff-for-one-commit – kravasb Apr 16 '15 at 11:40
  • @kravasb I don't think it is a duplicate, I don't want to compare the whole commit to another commit, I just want the difference for that piece of code, so the new file compared to the other would be great – Joffrey Apr 16 '15 at 11:45

2 Answers2

3

I think this is what you are looking for. HEAD~3 can be replaced with the commit id.

git diff HEAD~3:oldfile.xml file/in/another/path/newfile.xml
crea1
  • 11,077
  • 3
  • 36
  • 46
1

A dirty but working solution

Use git ls-tree to get the SHA1 identifier of the files on the commits you want to compare then use git diff [options] <blob> <blob> and provide the two SHA1 identifiers as arguments.

$ git ls-tree commit1 dir1/dir2/file1.txt
100644 blob 7d252b754d46a8fcd0613a96710c9326942d7a92   dir1/dir2/file1.txt

$ git ls-tree commit2 dirA/fileB.txt
100644 blob 4d000ed739c880a26686a2843dae6eeeb4109a37   dirA/fileB.txt

$ git diff 7d252b754d46a8fcd0613a96710c9326942d7a92 4d000ed739c880a26686a2843dae6eeeb4109a37

If you need to do this frequently you can even pack everything in a small shell script:

#!/bin/bash

# This script does not validate its command line arguments!

COMMIT1=$1
FILE1=$2
COMMIT2=$3
FILE2=$4

BLOB1=$(git ls-tree $COMMIT1 $FILE1 | cut -f3 -d' ' | cut -f1)
BLOB2=$(git ls-tree $COMMIT2 $FILE2 | cut -f3 -d' ' | cut -f1)

git diff $BLOB1 $BLOB2

Run it as:

$ script.sh commit1 dir1/dir2/file1.txt commit2 dirA/fileB.txt
Community
  • 1
  • 1
axiac
  • 68,258
  • 9
  • 99
  • 134