ANDREA IGNAZIO RUSSO
ANDREA IGNAZIO RUSSO

Reputation: 23

Merge a specific file from different branch/directory

I have two GIT branches: A with Pluto/test.txt B with Pippo/test.txt

I want to merge only the file (test.txt) in the branch B into A.

I tried to use:

git checkout A
git checkout B Pippo/test.txt

but this creates a folder with the file in it like: A with Pluto/test.txt and Pippo/test.txt. However I would like to get a merge of the files

Upvotes: 1

Views: 74

Answers (2)

ElpieKay
ElpieKay

Reputation: 30868

Try git merge-file. It merges two files in three-way merge.

git merge-file <current-file> <base-file> <other-file>

In your case, current-file is A's Pluto/test.txt, other-file is B's Pippo/test.txt. As for base-file, you could find out which commit of A introduced Pluto/test.txt for the first time, by git log A --reverse -- Pluto/test.txt. The first commit in the output is what we want and suppose it's abc123.

Checkout the branch A, so that we have current-file.

git checkout A

Retrieve base-file.

git cat-file -p abc123:Pluto/test.txt > base.txt

Retrieve other-file.

git cat-file -p B:Pippo/test.txt > other.txt

Run the three-way file merge.

git merge-file Pluto/test.txt base.txt other.txt

Open Pluto/test.txt. If there are any conflicts, solve them. Save and exit. Add and commit the changes.

git add Pluto/test.txt
git commit

Clean base.txt and other.txt.

rm base.txt other.txt

Upvotes: 2

Romain Valeri
Romain Valeri

Reputation: 21938

git won't merge files which have a different path.

A file merge could occur if both files were on the same exact path, but different on your branches.

However, even if you had, let's say, Pluto/test.txt in each branch, merging B into A would not necessarily result in a merge. It would only if they both differed from their merge base in the same places (chunks of code).

Maybe consider doing a manual merge with any merge tool, then commiting these changes on the branch you need?

Upvotes: 1

Related Questions