Search code examples
gitgit-branch

Move committed changes from one file into new branch in git


I have a feature branch checked out from main with a few commits that edit various files in the codebase. However, I realize that in an upcoming PR, I don't want to incorporate changes to a specific file, say file.java. How can I restore file.java to its former state (from main) while creating a new branch with the updates to the file for future use?


Solution

  • Let us suppose in your feature branch, where you are now, file.java has been edited. You want to save those edits, but right now, you would like file.java to look the way it did before your feature branch got started. Then you could say:

    git branch holdmyplace
    git restore --source main -- file.java
    

    Now file.java in your current branch (when you add and commit) is the same as back in main, before you checked out and worked on your feature branch. At the same time, you've got this secret branch, holdmyplace, whose state of file.java is the edited state. Later, you can use the same technique to copy file.java from holdmyplace while working on some other branch.