Is a git commit required if I rollback using 1) git hard reset or 2) git revert?

96 views Asked by At

I understand there are two ways of rolling back a git commit in remote repository.

Method 1:

git reset --hard <old-commit-id>
git commit -m "rolling back"
git push -f

Method 2:

   git revert <old-commit-id>
   git commit -m "reverting the changes"
   git push -f

In various posts that I have seen, there is no mention of git commit to be done. But my colleague is convincing me that git commit should be issued and that git push with -f. otherwise, the push will fail. Is my colleague correct? I am still doubtful about it

1

There are 1 answers

3
jub0bs On BEST ANSWER

Method 1 (not safe!)

Running

git reset --hard <old-commit-id>

will discard all local changes and make the current branch point to <old-commit-id>. Be careful with it, because it's a potentially dangerous command.

In particular, you should not follow this command by a force push in order to undo changes that have already been pushed to a shared remote repository. It would be crossing-the-streams bad. It would be analogous to sawing the branch your collaborators are sitting on!

So this method is a big no-no, at least in case other people than you have access to the remote repo.

Should git commit be used after git reset, here?

If you decided to go ahead anyway (don't!), you wouldn't need to run

git commit -m "rolling back"

unless you're making additional changes right after the git reset command (in which case you would also need to stage those changes before committing).

Would I need to use -f (force push)?

Yes, you would need to use -f, in general, because the push be a non-fast-forward one.

Method 2 (safe)

This method is nondestructive, and considered good practice for reverting changes on a remote repo.

Should git commit be used after git revert, here?

Running

 git revert <old-commit-id>

creates a commit that undoes the changes introduced in <old-commit-id>. Therefore, there is no need for

git commit -m "reverting the changes"

unless you're making additional changes right after the git revert command (in which case you would also need to stage those changes before committing).

Would I need to use -f (force push)?

No, you don't need to force push (no -f needed) here, because the push will simply be a fast-forward one, in this case.