Ryan1729
Ryan1729

Reputation: 1010

get diff between files in two different git repos and apply to first repo

I have two different local git repos, which we'll call a and b. They are both in a projects folder in my home directory. I want to get a diff between a particular file in both repos, let's call it foo, and apply that diff to a.

if I run git diff ./foo ../b/foo > diff.diff from inside a I can look at the diff and confirm that it contains the changes I want to apply, but when I run git apply diff.diff then I get this error:

fatal: invalid path './foo' 

If I try running git diff ~/projects/a/foo ~/projects/b/foo > diff.diff, then when I try to apply the diff I get this error:

error: home/ryan/projects/a/foo: No such file or directory

Now, I can just copy the file to get the same effect as applying the diff, but is there a good reason why this isn't working?

Upvotes: 0

Views: 359

Answers (2)

Lawrence D'Oliveiro
Lawrence D'Oliveiro

Reputation: 2804

First of all, git diff isn’t buying you anything here—you might as well use plain diff -u. The reason why the patch won’t apply is because git-apply is being confused by the inconsistent file paths in the diff. To fix this, you need to set your working directory so that the diff has relative paths in it of the same depth for both versions of the file. Here I change directory to the common parent of both project directories:

cd ~/projects
diff -u a/foo b/foo >a/diff.patch
cd a
patch -p1 <diff.patch
git add ... commit ... etc ...

Upvotes: 0

Marina Liu
Marina Liu

Reputation: 38136

To compare foo file between repo a and repo b and apply the changes to repo a, you just need to use below commands:

# In ~/projects/a (local repo a)
git remote add repob  ~/projects/b -f
git diff master repob/master -- foo > diff.patch
git apply diff.patch

Now the foo in repo a change to the version of repo b. Then you can commit and push:

git add foo
git commit -m 'change foo as the version in repo b'
git push

Upvotes: 1

Related Questions