Kerem
Kerem

Reputation: 888

Git merge doesn't get files that discarded before

When I tried to merge (5 files) dev to test, I discarded some files (2 files) and commited others (3 files). After a while I needed to merge my discarded two files to test branch but discarded files didn't appear in working tree. Is there a bug here or did i do something wrong?

Thanks in advance!

Upvotes: 3

Views: 295

Answers (1)

hlovdal
hlovdal

Reputation: 28228

Part 1

I have created the following test repo to replicate what I think is your scenario:

mkdir /tmp/test
cd /tmp/test
git init
touch .gitignore
git add .gitignore
git commit -m .gitignore
touch file{1,2,3,4,5}
git add file{1,2,3,4,5}
git commit -m "Create files"
git checkout -b feature1
for i in file{1,2,3,4,5}; do echo "This is $i" >> $i; done
git add .
git commit -m "Update files"
git checkout main 
for i in file{1,2,3,4,5}; do echo "This is line 1" >> $i; done
git add .
git commit -m "Add line 1"
git merge feature1 

So at this point we have merge conflicts on all five files.

I resolving them by keeping "This is line 1" as line 1 and the line "This is file" as line two.

vi file*
git add .

So at this point all conflicts are resolved for all files, however let's discard file1 and file2 back to main content and complete the merge:

git reset file1 file2
git checkout file1 file2
git commit
git tag merge-commit-2-of-5

Part 2

So your wish is to merge feature1 into main once more to merge the two missing files. This can be done as follows:

  1. Create a new branch from right before the merge is done.
git checkout -b before-merge merge-commit-2-of-5^   # the "^" here indicates (first) parent
  1. Bring in all changes from the merge but only the content and no "meta information" like merge parents.
git diff HEAD merge-commit-2-of-5 | git apply -
git commit -am "Existing merge changes" -m "Generated with: git diff HEAD merge-commit-2-of-5 | git apply -"
  1. At this point you have a branch with the merge changes for file{3,4,5} present but without it being recorded as a merge, which is the key to be able to merge feature1 again.
git merge feature1
# file3, file4, and file5 also ends up as being conflicted, but since their content is
# already ok, reset those
git reset file{3,4,5}
git checkout file{3,4,5}
vi file1 file2   # resolve conflicts normally
git add file1 file2
git commit -m "Merge of the last two files"

At this point the last commit is exactly what you asked for, a postponed merge for some files. You can then either cherry-pick that commit or merge the before-merge branch into main.

Upvotes: 1

Related Questions