Recover Local Code After Overwriting It using Git

Posted on

How to recover the Local Code?

Recently, I encountered a common yet frustrating situation while working on a project using Git and GitHub. I had just pushed a working version of my code to the main branch on GitHub. However, after making some accidental local changes that broke the code, I wanted to restore the version I had previously pushed. Please, how to recover Local Code?

My instinct was to run:

git pull origin main

Expecting it to restore the code from GitHub.
But Git replied:

Already up to date.

Even though my local code was clearly broken and different from the GitHub version.

The Problem: Git Pull Doesn’t Overwrite Local Changes Unless Committed

Git pull only brings in changes from the remote if:

  • The remote has new commits that the local branch does not have.
  • OR the local branch has diverged (commits in both directions).

In my case, I had made manual changes to the files, but I had not committed them. Therefore, from Git’s point of view, everything was already “up to date”.

The Solution: Force-Reset Local Code to Match GitHub

To fix this, I used a Git command that overwrites all local files with the version from the remote repository:

git fetch origin
git reset --hard origin/main

Let’s break it down:

  • git fetch origin: Downloads the latest commits from GitHub without modifying local files.
  • git reset --hard origin/main: Resets the local branch to exactly match the remote’s main branch — all files included.

Warning: This deletes any uncommitted local changes. Use with caution!

Optional: Back Up Before Resetting

If you’re unsure about losing local changes, you can create a backup first:

mkdir ../local-backup
cp -r . ../local-backup

Takeaways:

  • git pull does not restore overwritten files if the changes are uncommitted.
  • Use git reset --hard origin/main if you want to completely revert to the latest remote version.
  • Always commit or stash changes before testing something risky.
  • Backing up the working directory is a safe habit before running destructive Git commands.

This lesson reminded me to be more cautious with local changes — and reinforced the importance of version control not just for collaboration, but also for personal recovery. Hopefully, this helps someone avoid the same confusion.