CohortX
Блог

Fixing mistakes in your history without breaking things

2 августа 2026 г. · 2 мин чтения · Читать по-русски · Антон Молотило

The general rule

Before changes are pushed, rewriting history is safe. After pushing it's dangerous, because other people's copies diverge from yours.

Hence a simple division: locally almost anything, on a shared branch almost nothing.

Forgot to include a file

Add it and redo the commit:

git add forgotten_file
git commit --amend --no-edit

The flag means "keep the message". The previous commit is replaced by one including the file.

Wrote a bad message

git commit --amend -m "a new, clearer message"

Works only for the last commit and only if it hasn't been pushed.

Committed the wrong thing

Undo the last commit, keeping the changes in your files:

git reset --soft HEAD~1

Undo and unstage, leaving files untouched:

git reset HEAD~1

Undo and discard the changes entirely:

git reset --hard HEAD~1

That last command destroys your work with no easy return. Use it deliberately.

Already pushed

Don't rewrite history — make a compensating commit:

git revert commit_hash

A new commit is created that undoes the old one. The history stays honest and everyone's copies agree.

That's the correct approach on a shared branch.

Accidentally pushed a password or key

First and foremost: treat it as exposed and rotate it immediately. Removing it from history doesn't undo the fact that it may have been fetched.

Only after rotating should you clean the history. Specialised tools exist for that; for a small learning repository it's sometimes simpler to create a new one.

The order matters: rotate first, clean afterwards.

Messed up your working directory

Discard changes to one file:

git checkout -- filename

Discard all uncommitted changes:

git reset --hard

Set changes aside for later:

git stash

Bring them back:

git stash pop

That last pair rescues you when you must switch branches urgently and your work isn't finished.

Finding what seems lost

If work appears to have vanished, look at the reference log:

git reflog

It shows every state you've been in, including ones no longer in the history. From the identifier you find there, you can go back.

It's a lifebelt: losing work permanently is harder than it feels.

The main advice

Before a risky operation, branch a copy:

git branch backup

A second's work for complete peace of mind: if anything goes wrong, everything is still there.

Хватит читать — пора делать

На CohortX можно найти команду под пет-проект и получить тот самый опыт, о котором спрашивают на собеседовании.

Похожие статьи