I've accidentally been working on master, how can I transfer all the changes I made onto a branch reset master to the last commit?

Viewed 1321

I haven't committed my changes yet as I realised that I was working on master just as I was about to commit. I want to move all the uncommitted changes onto a new branch and then reset master to the last commit. I'm sure there must be a way to do this, but I'm unfamiliar with git (every time I use it it gives me anxiety that I'm going to mess something up and ruin the app). I use sourcetree if that helps.

4 Answers

If your changes are not yet staged or committed and your local master branch is already up to date, you can simply create a new branch.

git checkout -b newbranch

If you need to sync with the upstream master first, there is a chance that your commits will conflict with the upstream changes. First, simply try

git pull origin master

(or upstream instead of origin if that's what you are using). If you don't get any warnings, your master is now up to date. If you do get a warning, git will refuse to pull, and you need to make arrangements to reconcile the differences between the origin/upstream and your uncommitted changes. As a first step, stash your changes, then proceed;

git stash save -m "put a useful comment so you know what this is"
git pull origin master
git checkout -b newbranch
git stash pop

There will probably be some conflicts to sort out at this point, before you proceed and commit.

Though often it will feel safer to just create a new local branch and commit what you have, then switch back to master and see what needs to be done to sort out any conflicts with upstream.

If you haven't committed your changes yet, that's the easiest situation; you can create a new branch where you are and commit your changes.

git checkout -b name_of_branch

Then add and commit as usual.

I want to move all the uncommitted changes onto a new branch

checkout -b new_branch will create and checkout a new branch without loosing your changes

and then reset master to the last commit

git branch -f master origin/master will reset master to the location of origin/master on your repository.

1 . make new branch from master (git checkout -b branch_name) 
2 . pull newest from master (git pull origin master) 
3 . checkout into master branch (git checkout master) 
4 . check the log (git log) 
5 . reset into the last log (git reset --hard #log number#) ex: git reset --hard oij349efnj43t8 
6 . push the last commit (git push --force origin #log number#:master) ex: git push --force origin oij349efnj43t8:master
Related