Fixing an Accidental Push to the main Branch Instead of develop
While working on a feature, I accidentally pushed my changes directly to the main branch instead of the develop branch. To maintain the correct Git workflow, I moved the commit to develop and restored the main Branch to its previous state.
Step 1: Identify the Commit
First, I checked the recent commit history to identify the commit hash that was accidentally pushed.
git log --oneline -n 5
Example:
- Incorrect commit:
0b46238 - Previous correct commit:
db5d750
Step 2: Move the Changes to the develop Branch
I switched to the develop branch:
git checkout develop
Then, I applied the accidental commit using git cherry-pick:
git cherry-pick 0b46238
If any merge conflicts occurred, I resolved them, staged the changes, and continued the cherry-pick process:
git add <file-paths>
git cherry-pick --continue
After successfully applying the commit, I pushed the updated develop branch:
git push origin develop
Step 3: Restore the main Branch
Next, I switched back to the main branch:
git checkout main
I reset the branch to the last correct commit:
git reset --hard db5d750
Finally, I force-pushed the corrected main branch to the remote repository:
git push origin main --force
Result
- The accidentally pushed changes were successfully moved to the
developbranch. - The
mainbranch was restored to its previous stable state. - The repository structure now follows the intended Git branching strategy.
Important Note
Using git push --force Rewrites the remote branch history. Before performing a force push, ensure that no other team members have based their work on the commits being removed. If the main branch is shared, consider using git revert instead of git reset --hard to avoid disrupting other developers.
