Git and Visual Studio 2017 part 14 : Resetting the changes after sharing code with others
In previous article, I explained how to compare item versions by using Visual Studio 2017. In this article, I share how to reset your change after you already shared your code.
Reset vs. Revert
As we already see in part 3 of this series, we know how to “reset”. But why this is not good after we shared our code? The reason is because others already have all commits locally, thus it creates inconsistency. Then how we can “reset” the change if we made mistake? That where “revert” comes in!. Let’s see how it works.
Revert in Git
1. Run ‘git log --oneline --graph --all’ to see current situation. There are two branches. As I don’t need remote to illustrate revert, I keep using the current setup.
2. Run ‘echo “Wrong info” >> README.md’ and ‘git commit -am “Wrong commit”, then run ‘git log --oneline --graph --all’.
3. Now I aware the last commit was wrong, but I already shared with others. Run ‘git revert --no-edit HEAD’. This reverts the current commit. --no-edit option suppress comment editor opens and use the default message, otherwise you can change the comment. Run 'git log --oneline --graph --all' to see that revert command added new commit on top of current tree. That’s why it is safe to share with others.
4. Run ‘type README.md’ to double check the content.
5. What has been changed in the last commit? We know how to check it, right? Run ‘git diff HEAD~1 HEAD’. It simply removed the wrong line.
6. What if you want to revert multiple commits? You can specify multiple continuous commits like ‘git revert HEAD~3...HEAD’.
Okay, for testing purpose, reset it by ‘git reset --hard 437fa4a’ where I committed wrong commit.
Revert in VS
1. Open History View for master branch. Right click the commit you want to revert and click “Revert”.
2. It reverts the commit by creating new commit.
3. If we select multiple commits and right click them? Revert menu is grayed out…
Force Push after Reset
When I really have to change the tree and use reset rather than revert, as I want to “delete” the history, then I can still do so by running push command with -f option after the reset. It works well if you already tell it to others, but another guy can push back the original commits by push -f from his side, so we better talk first.
I used to “Commit and Sync” from Visual Studio whenever I thought I was ready to share the code. However after working on multiple projects, I do local commits first to see if it looks good, then push to remote. Oh, then we need to know how to “fix” the local commit in addition to 'reset' or 'commit --amend'. I will explain it in the next article. Go to next article.