Boldewyn
Boldewyn

Reputation: 82734

"Move" files to their own branch in Git

In master I have some files that should better live in a feature branch. I'd like to create such a branch and have the files there, at the same time removing them from master.

I'm not concerned about history, i.e., the files need not to be removed from previous commits. When I do

$ git ls-files
stay.txt
move.txt

$ git checkout -b feature
Switched to a new branch 'feature'

$ git checkout master
Switched to branch 'master'

$ git rm move.txt

the situation in the HEAD is much like I want it. However I'll run into problems, when I want to merge master to feature. Do I have to deal with it or is there a solution for such a scenario?

Upvotes: 3

Views: 278

Answers (1)

BenC
BenC

Reputation: 8976

Indeed, if you do things that way, when you will merge those two branches (master & feature), the commit in which you deleted your files will be applied to feature, thus deleting the files that you tried to keep safe in feature.

Moreover, if you modify those files in feature after deleting it in master, during the merge, the files will be deleted and then modified, creating a conflict :

CONFLICT (modify/delete): test.txt deleted in HEAD and modified in feature. Version feature of test.txt left in tree. Automatic merge failed; fix conflicts and then commit the result.

If the files are not modified (no conflict), you can solve this after the merge by reverting the deleting commit :

$ git merge feature # in master
$ git revert SHA-of-the-commit-deleting-your-file

You would get all the commits of the feature and master branches without losing your files.

However, if there is a conflict, you might have to solve this manually (unless someone finds the perfect git command for this!) :

$ git merge feature # in master
$ git mergetool # use modified versions of files
$ git commit -m "Merge with deleted files solved"

Upvotes: 2

Related Questions