Selectively merging files from across branches¶
Estimated time to read: 1 minute
Recently, I've had the need to merge selective files from one branch into another. This isn't something I recommend doing often, but if you're stuck in a position where you need a few files from another branch, here is one way to do it:
The process:¶
Let's say you have a branch named feature-1 and want the file example.py from the feature-2 branch:
- First, from the
feature-1branch, merge thefeature-2branch with squash option (git merge --squash feature-2) to avoid creating a merge commit. - Reset the files (or entire folders) that you don't want in
feature-1(git reset origin/feature-1 tests/orgit reset origin/feature-1 tests/test.py) or remove them completely (git rm tests/test.py). - Add and commit the file(s) you want in your branch with a new commit message (
git add example.py && git commit -m "merge example.py from feature-2"). - Clean the branch to remove untracked changes (
git clean -xfd), -f for force, -d to remove the untracked directories, and -x to remove the ignored files. - Restore the tracked changes (
git restore .) - Push the changes to the remote branch (
git push).