Force Pushing vs. Reverting: Rules of Thumb
Deciding how to undo a remote push depends primarily on whether others share the branch:
- Personal Feature Branch (Solo): You can safely reset locally and run
git push origin <branch> --force-with-lease. This keeps your PR clean with linear commit history. - Main or Team Branches: Never rewrite shared history. Use
git revert HEADand push a new reversal commit. - Leaked Passwords or API Tokens: Always rotate credentials first! Automated bots scrape public GitHub commits within seconds. Even rewriting history won't protect already-compromised keys.
Frequently Asked Questions
What is the safest command to roll back a pushed commit?
If working on a shared branch (like main), use 'git revert HEAD && git push origin main'. This rolls back changes forward without force-pushing or rewriting history.
Why should I use --force-with-lease instead of --force?
'--force-with-lease' checks that the remote branch has not been updated by someone else since your last pull. If a teammate pushed new work, it aborts, preventing accidental code destruction.
What should I do if I pushed an API key or .env file?
1. Revoke/rotate the secret immediately in your service provider dashboard. 2. Remove the secret from Git with 'git reset --soft HEAD~1'. 3. Add the file to .gitignore. 4. Commit and push.
Does force-pushing delete commit history from GitHub completely?
No. GitHub still caches orphaned commits by their SHA for a period of time. If you leaked high-security secrets, consider using tools like BFG Repo-Cleaner or git-filter-repo, and contact GitHub support if necessary to clear the cache.