Home > Enterprise >  How can I remove files from one Git branch and add them to a new branch
How can I remove files from one Git branch and add them to a new branch

Time:09-02

For context, I am using a repo to manage my dotfiles and want to move OS-specific configuration from main to a new branch so that main is more portable. I will then periodically rebase the new, OS-specific branch on main.

I think I want the history to look something like this

main:       old commit - old commit - remove some files
                                                       \
new branch:                                             add those same files

I don't care about the history all that much, I realise the blames will probably be destroyed by this.

CodePudding user response:

I would do it like this:

git checkout main
git rm the-file
git commit -m "Removing some file"
git checkout the-other-branch
git rebase main
git checkout main~ -- the-file # get the file back from a revision where it existed
# no metadata is brought for that file
git commit -m "Getting back the-file"

Keeping history is trickier:

git checkout main
git rm the-file
git commit -m "Removing the file"
git checkout main~
git merge --no-ff -m "merging removal, but keeping the file" main
# here is where we _really_ get the file back:
git checkout main~ -- the-file
git commit --amend --no-edit
# this merge revision keeps the file _and_ it is already a child of main _without_ the file
# this revision is where the feature branch should be now
git branch temp
git checkout the-feature
git rebase temp
# now..... you have the-feture, which is a descendant of main and _has_ the file.... and history of the file is kept

And best of all? You can merge stuff from master and the file won't be deleted.

CodePudding user response:

You can push these commit files to a new repository in GitHub and remove the files/commits you don't need and just download it.

  • Related