How do I restore a previous version as a new commit in Git?
Edit: I see that you want to keep the history, so my answer below is nullified. However, it is still useful. You can reorder the lines in the editor, then proceed.
Now, back to the original answer.
You could try the rebase command.
git rebase -i HEAD~n
Where n
is about one more than the number of commits between current and the one you want to revert to. So let's say, deleting the last 3 commits:
git rebase -i HEAD~4
Once you're there, it will open in VIM or Nano (or other editor). Simply delete the lines of the commits to remove, and exit the editor.
In VIM that would be esc
and type :exit
enter
.
Now, simply push it. That will result in an error, so do a force push.
git push -f
You might have to specify branch name and upstream too. That should do it!
This method completely deletes the bad commits, so it won't just add a new commit with the revert changes.
Here's the docs: https://git-scm.com/docs/rebase
Simply "checkout
the commit". This will overwrite your current working directory with the specified snapshot (commit) of your repo from history and make that your new working-set which you can stage and commit as you wish. If you commit
immediately afterwards then your repo will have the same filesystem contents as the commit you performed the checkout
to (assuming you have no other unstaged or staged changes)
This will not rewrite history nor edit or delete any previous commits - so it works similar to a "rollback" on Mediawiki:
cd ~/git/your-repo-root
git log
# find the commit id you want
git checkout <commitId> .
# IMPORTANT NOTE: the trailing `.` in the previous line is important!
git commit -m "Restoring old source code"
See also: Rollback to an old Git commit in a public repo
Regarding the .
(dot)
The .
(dot) character means "current directory" - it is not anything special or unique to git, it's a standard command-line filesystem convention that's the same on Windows, Linux, macOS, and even MS-DOS. It works similar to how ..
means "parent directory". I recommend reading these:
- https://askubuntu.com/questions/54900/what-do-and-mean-when-in-a-folder
- https://superuser.com/questions/37449/what-are-and-in-a-directory
- What is double dot(..) and single dot(.) in Linux?
- https://unix.stackexchange.com/questions/118175/what-are-some-uses-of-single-period-double-period-in-the-shell-command
Regarding checkout
Be aware: checkout
is an overloaded command in git - it can mean to switch branches (a la svn switch
) or to get a specific file or commit from history and put into your workspace (a la svn update -r <id>
). It can mean other things too: https://git-scm.com/docs/git-checkout - I appreciate it can confuse people, especially myself when I started using git after using TFS for years (where "Checkout" means something else entirely).