MEM
MEM

Reputation: 31337

Git Branch newbie - How to reverse?

Not sure if this is a proper way to work with branches.

Request:

How can this be done?

Upvotes: 13

Views: 35422

Answers (3)

Dan Breen
Dan Breen

Reputation: 12924

If you created a separate branch that got messed up, all you need to do is switch back to the one you were on before: git checkout A (assuming A is the name of the branch you were on... or maybe it's master).

You can delete the bad branch later, if you want, with git branch -d <branchname> and maybe throw in a -f too, if there are unmerged commits.

Edit: If your repository contains lots of bad changes you want to remove, you can use git reset --hard HEAD to undo them. If there are new files (not tracked by git), git clean -fd will remove them all. Obviously, use with discretion as they will not be recoverable by git.

Upvotes: 15

ralphtheninja
ralphtheninja

Reputation: 133018

I suspect that you only created the branch with:

git branch Z

when you in fact wanted to create it and also switch to it. You can create a branch and switch to it by using the -b flag to git checkout, like this:

git checkout -b Z

What you need to do now is to undo the changes that you have committed to your master branch. This will undo the commit and make the index look just like before you made the commit:

git checkout master
git reset --soft HEAD^

Then switch to Z and commit the changes from the index (already staged):

git checkout Z
git commit -m "blah blah"

Hope this helps.

Oh and yes avoid working directly on master, unless it's a simple bug fix.


Please keep your answer because it contains important notions that I must understand. That didn't work. What I need is to: grab branch Z and place it as a master - is this possible ?

Of course it is. You can do this in a lot of different ways. If there is only one commit you could merge the Z branch into master to get that commit into master. But I'm assuming that you dont want the commit on the Z branch at all. Then you can do the same but switch branches, e.g.:

git checkout Z
git reset --soft HEAD^
git checkout master
git commit -m "blah blah"

Upvotes: 3

Dan Ray
Dan Ray

Reputation: 21893

I need to reverse to structure A "snapshot" on branch Z

$ git checkout A
$ git branch -d Z
$ git branch Z
$ git reset --hard HEAD~3
$ git checkout Z

In English:

Delete your "Z" branch and re-make it from the current state of "A".

Reset your A branch back three commits. That's an EXAMPLE--three is probably not the right depth back in your history to reset to. Change that number to be the right number (and use git log to figure that out the number of commits back that your branches diverged).

Switch to your Z branch and confirm that your changes formerly in "A" are now in "Z".

Upvotes: 6

Related Questions