I just made a perfectly good commit to the wrong branch. How do I undo the last commit in my master branch and then take those same changes and get them into my upgrade bran
I recently did the same thing, where I accidentally committed a change to master, when I should have committed to other-branch. But I didn't push anything.
If you just committed to the wrong branch, and have not changed anything since, and have not pushed to the repo, then you can do the following:
// rewind master to point to the commit just before your most recent commit.
// this takes all changes in your most recent commit, and turns them into unstaged changes.
git reset HEAD~1
// temporarily save your unstaged changes as a commit that's not attached to any branch using git stash
// all temporary commits created with git stash are put into a stack of temporary commits.
git stash
// create other-branch (if the other branch doesn't already exist)
git branch other-branch
// checkout the other branch you should have committed to.
git checkout other-branch
// take the temporary commit you created, and apply all of those changes to the new branch.
//This also deletes the temporary commit from the stack of temp commits.
git stash pop
// add the changes you want with git add...
// re-commit your changes onto other-branch
git commit -m "some message..."
NOTE: in the above example, I was rewinding 1 commit with git reset HEAD~1. But if you wanted to rewind n commits, then you can do git reset HEAD~n.
Also, if you ended up committing to the wrong branch, and also ended up write some more code before realizing that you committed to the wrong branch, then you could use git stash to save your in-progress work:
// save the not-ready-to-commit work you're in the middle of
git stash
// rewind n commits
git reset HEAD~n
// stash the committed changes as a single temp commit onto the stack.
git stash
// create other-branch (if it doesn't already exist)
git branch other-branch
// checkout the other branch you should have committed to.
git checkout other-branch
// apply all the committed changes to the new branch
git stash pop
// add the changes you want with git add...
// re-commit your changes onto the new branch as a single commit.
git commit -m "some message..."
// pop the changes you were in the middle of and continue coding
git stash pop
NOTE: I used this website as a reference https://www.clearvision-cm.com/blog/what-to-do-when-you-commit-to-the-wrong-git-branch/