Short Tip: git magic (copy changed files from branch A to B)

Let us consider the following case: I’ve got a huge project which you want to refactor. You checkout master, create a branch called cleanup and commit every change. Most of the refactoring is only style guide related so no change involves two or more files. After a time your branch has 30 commits. Reviewing this might cause a lot of pain because there are many changed files and all in one Branch. A solution would be: extract the changed files, create new Branches + Pull Requests for each file, get them reviewed separately. How do we do this nicely?

Go to master, create a new branch:

git checkout master
git checkout -b myrefactoringpart1

Now we tell git to give us a list of changed files between our new branch and the cleanup branch in our most loved editor. We can remove all files from the list except for the one that we want to place in our new branch, than save + quit the editor. Git will checkout the file from the cleanup branch:

git checkout cleanup -- $(git diff --name-status cleanup | cut -f 2- | vipe)

(thanks to i7c from #virtapi on freenode for this awesome snippet)

Now we can commit + push the changes and create a Pullrequest. You can redo these steps for all files you want to put in new branches. You can also automate this to create a new branch for each file, but this method here allows you to edit the files before the commit, in case you missed important stuff.

git commit -am 'refactoring $cooltexthere'
git push --set-upstream origin myrefactoringpart1
This entry was posted in General, Linux, Short Tips. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.