Answer the question
In order to leave comments, you need to log in
How do you roll back to a stable commit and still keep the useful code you made after the mistake?
I recently started getting familiar with GIT and I had a question.
Let's imagine such a situation.
Day 1. I created a script.js file. Wrote some code. Checked that everything was without errors. Made a commit.
I now have a stable script.js file. If something happens in the future, then I can roll back to this commit.
Day 2: So I started coding script.js again, and I made a subtle mistake that could cause serious problems in the future and can't just be fixed. Because of this error, in any case, you will have to roll back the project again to " Day 1 ". But now I don’t know about it, so I’m happy to make a commit.
Day 3. The next day, I started working on the script.js file again. Posted byUSEFUL code, made a commit.
And so I worked for several days. After " Day 2 ", when I made a fatal mistake, I wrote a lot of USEFUL code on " Day 3 ", " Day 4 ", etc. Added many different features, etc.
At a certain point, I discover that it turns out that once I made a mistake. And now we have to roll back to a stable commit. But because of this error, a lot of useful code is lost. How to be in such a situation?
Day 1, 2, 3 is just an example to simplify the situation. A similar problem can arise at any stage of development.
How do you roll back to a stable commit and still keep the useful code you made after the mistake?
Answer the question
In order to leave comments, you need to log in
In practice, errors are rarely corrected by "pulling out" one commit from the history, but such an operation is quite possible.
Option number one is an interactive rebase, where you specify which commits to drop. If there are a lot of commits, then you can get sick of resolving conflicts
Option number two - just make a new commit with the reverse of changes from the commit that led to problems
Option three - make a new branch, roll back to the problematic commit, then roll the rest of the changes from the full branch.
All scenarios are approximate, because each problem requires a comprehensive approach and knowledge of the capabilities of the tool, so do not be lazy, but read this carefully and completely
https://git-scm.com/book/en/v2
Temporarily switch to another commit:
You can temporarily switch to another commit:
git checkout <your_commit_sha>
If you want to make commits while you're temporarily on a different branch:
git checkout -b old-state <your_commit_sha>
To get back to where you were, just go back to checkout
the branch you were on. (If you've made changes when you switch branches, you'll have to handle them accordingly.
Revert previously published commits with new commits:
If you've published changes, you probably don't want to reset the branch, as this will actually rewrite the commit history. Create a commit with back patch to undo it.This way you don't rewrite the commit history.You can do this:
# Это создаст три отдельных коммита возврата:
git revert <your_commit_sha1> < your_commit_sha2> <your_commit_sha3>
# Это вернет последние два коммита. Также принимает диапазоны:
git revert HEAD~2..HEAD
# Точно так же вы можете отменить ряд коммитов, используя хэши коммитов (не включая первый хеш):
git revert <your_commite_sha>
# Отмена мердж коммита:
git revert -m 1 <merge_commit_sha>
# Чтобы получить только один коммит, вы можете использовать 'rebase -i',
# Или вы можете сделать это вручную (обязательно сделайте это на верхнем уровне вашего репозитория)
# Привести ваш индекс и дерево в нужное состояние, не меняя HEAD:
git checkout <your_target_commit_sha>
# После чего обязательно зафиксируйте коммит. Будьте уверены в том, что вы сделали на 150% и напишите хорошее сообщение с описанием того, что вы только что сделали:
git commit
There are many ways to undo changes in the git, their options were voiced in the answers.
In my opinion, to undo the changes of one commit, it is ideologically correct to execute git revert for this commit. Revert will create a new commit that undoes the actions of the reverted commit. In this way, you can record the fact of cancellation in the history of the repository and, for example, mark the reason for the cancellation.
Also, if you suddenly need to undo not the entire commit, but only part of its changes, you can perform a partial revert:
git revert <плохой_коммит> --no-commit # Revert будет подготовлен, но не закомичен
git reset # Выполнить unstage всех файлов
git add ... список плохих файлов # Добавляем в индекс те файлы, что требуется отревертить. Используя ключ -p можно добавить часть изменений в файле, а не файл целиком.
git checkout . # Сбрасываем все прочие файлы, что не в индексе, до оригинального состояния
git commit # Коммитим revert
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question