Home > other >  How to reset a project back to earlier code and overwrite existing changes on the local repo
How to reset a project back to earlier code and overwrite existing changes on the local repo

Time:02-21

Scenario: I have added a block of code, and it has caused all backgrounds for all button elements on my site to turn green. I am not happy with the method used, and wish to remove the code completely so I can start from before this change was applied on this branch, and implement a better way of targeting the buttons, using another approach on the same branch (backtrack).

CodePudding user response:

wish to remove the code completely

To backtrack, you have two choices. First, find (using git log) the SHA of the commit you want to backtrack to, i.e. the last "good" commit before the "bad" commits started. Then either

git reset --hard <SHA>

or

git revert <SHA>..HEAD

The difference is that reset rewrites history and throws away the subsequent commits, while revert keeps the history and introduces new "undo" commits.

CodePudding user response:

Solution: Reset the code to an earlier point

Steps to take:

Identify where you want to revert your code back to - git log

Next, copy the first 7 digits from the SHA commit you wish to jump back to using the branches commit history and SHA numbers - You only have to use the first 7 characters to apply the changes I am about to describe: 9bfc696

Now enter this command to reset the code - git reset 9bfc696

Your code is now at the earlier commit point, and the changes have been un-staged -

Unstaged changes after reset:
M       green-buttons.css

A message similar to the above will appear in your terminal

Next, we want to see the older code reflected in our current working directory/session.

Type in this command to restore your working directory to the HEAD point of the repo - git checkout . HEAD
(Show me the current directory at the main point in the current workflow)

The code will now boot back into the earlier commit, and also remove those unstaged changes. It is important that you are clear you do not want to retain any of the code before carrying out this process.

To take greater precautions, and create a backup of your rogue changes, follow this process instead:

git checkout [working branch - this is the one we will run the deletion on]
git checkout -b [new backup branch name]
git checkout [working branch]
git log 
git reset 9bfc696 
git checkout . HEAD 

Please do let me know if there is anything else that you feel should be added or removed from this Q&A style answer, I would be keen to make those changes.

  • Related