Search code examples
gitgithubgithub-desktop

Move Specific Files from One Branch to Another Branch in Github


I made changes to some files on a branch feature/branch-30 and then realized that some of these changes should be on feature/branch-31. I know we can use stash and pop commands to move all the files from one branch to another branch but my requirement is that I need to move only specific files from feature/branch-30 to feature/branch-31. How do I do that? I would really appreciate any help. Thank you!


Solution

  • git stash only works with the staging area to build up a commit. Once the changes are committed, it has no place. If you want to move committed changes to certain files, you need to make new commits with only those changes.

    From now on I'll call branch-30 "source" and branch-31 "dest".

    I'll assume that by "move" you want to remove the changes from source and add them to dest. There's many ways to do this. The important thing to account for is because dest may have also changed the files, if we tried to just move the changes in source to dest there might be conflicts. Git has a tool to handle this, merging!

    First, we'll obtain the changes from source to dest by faking a merge. git merge -n will perform a merge without committing them.

    git checkout dest
    git merge -n source
    

    Now you have the uncommitted merge of everything. Use git restore to remove any changes you do not want, and fix any conflicts as normal. Then stash that change and, since we don't actually want to merge, abort the merge: git merge --abort.

    Now apply and commit your stash to dest.

    git stash pop
    git commit
    

    That's adding the changes to dest sorted, now we need to remove them from source. This is a similar approach, but instead of merging to get the changes, we'll use git restore to bring all the files back to their original master versions, but not commit them.

    git checkout source
    git restore --source master .
    

    Once again, you have a staging area full of changes. Again, remove all the changes you do not want. Then commit them.

    And you're done.