3

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?

Boldewyn
  • 75,918
  • 43
  • 139
  • 205

1 Answers1

2

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"
BenC
  • 8,089
  • 3
  • 43
  • 64
  • Good answer (+1) but I wonder if there is some kind of merge driver to be put in place in order to "protect" those files and avoid them being deleted during the merge (avoiding the need to revert or to solve conflict) – VonC Nov 15 '11 at 13:27
  • I wonder, if it wouldn't be better to `git rm` them, and re-add them in the feature branch. Of course, it would break their history, but in my scenario the ease of use in the future should outweight that. – Boldewyn Nov 15 '11 at 16:41
  • 1
    If it is just a matter of simplicity and keeping the files, you can use `git rm` on master, `git add` on feature and you should be fine. The only problem that I see could appear if you use big files : instead of having those files stored once in your repository, I believe they will be found twice, and you might have to find a way to permanently delete the initial ones (which involves non-fast forward commit...). This does not really concern you if you only deal with small files (configuration files etc.). I might also be wrong (if the files have the same name and the same content...). – BenC Nov 15 '11 at 19:30