Cloud & DevOps

Git and GitHub when things go wrong: two questions before you rewrite or delete

Team Nippysoft
• • 16 min read
Git and GitHub when things go wrong: two questions before you rewrite or delete

You reverted a merge that broke the main branch, and now you merge that same branch again. If you added nothing to it, Git answers Already up to date. and your code doesn't show up. If you added a fix, the merge brings only that fix, or stops at a conflict. As far as the history goes, the rest already landed. A list of commands won't get you out of this, because it never tells you what each command did to your history.

We suggest something else: two questions to ask before any command that rewrites or deletes. Who else has these commits? Where is the thing I could lose actually stored? The questions are Nippysoft's opinion. What backs them came from 69 scenarios in throwaway repositories, on Git 2.49.0.windows.1 in Git Bash on Windows 11, and the output you see here is literal.

Keep three limits in mind from the start. The latest published version is 2.56.0, so some messages may differ. We didn't test on Linux or macOS. And we never ran git push: anything that depends on pushing comes from the documentation, and we say so each time.

Commits and pointers

Pro Git gives the definition that explains most of what follows: “A branch in Git is simply a lightweight movable pointer to one of these commits.” A branch holds no work; it points at a commit. That's why moving or deleting a branch destroys nothing at that moment, and why two people can hold different pointers over the same commits.

With divergent histories, a merge creates a commit with two parents and rewrites nothing; if the branch didn't diverge, Git just moves the pointer forward. A rebase creates new commits with the same changes: the hash changes and the patch id, the fingerprint of the change, stayed the same in our run, though it changes if the patch context changes or there was a conflict. Here are both histories from the same starting branch:

# After: git merge feature
$ git log --graph --format=%s
*   Merge branch 'feature'
|\  
| * feature two
| * feature one
* | main one
|/  
* base

# After: git rebase main
$ git log --graph --format=%s
* feature two
* feature one
* main one
* base
What a rebase moves What a rebase moves A B C D C' D' main your teammate's copy stays here same changes, new hash feature

The two questions

Who else has these commits? This decides whether you can rewrite history. Git can't know, so the answer is yours, and it includes anyone who pulled the branch as well as the server.

Where is the thing I could lose actually stored? This decides whether there is a way back. In our runs, Git protected what was committed, partly what was in the staging area, and nothing that existed only on disk. The table further down goes case by case.

Merge or rebase: who has the commits

With commits other people already have, this isn't a matter of taste. Pro Git draws the line at the first question: “Do not rebase commits that exist outside your repository and that people may have based work on.” With your own, the same page leaves it to each team: a rebase gives you a linear history at no cost to anyone else.

If someone already had those commits, the git-rebase documentation doesn't soften it: “Rebasing (or any other form of rewriting) a branch that others have based work on is a bad idea: anyone downstream of it is forced to manually fix their history.” We reproduced it. A teammate who merges the rewritten branch ends up with feature one twice in their history. Another who rebases keeps a single copy, because Git skips the repeated patch. The documentation calls this “the easy case” and warns it only works when the patches are identical.

git pull with no strategy configured forces the same decision. With divergent histories it stops at fatal: Need to specify how to reconcile divergent branches. Merge or rewrite.

Rebase also costs more when resolving conflicts. With three commits touching the same line, merge stopped once and rebase three times. It's a minimal experiment that illustrates the mechanism, not an average from real projects.

Conflicts

The first thing that trips people up is that ours and theirs change meaning. The git-rebase page explains it: “the side reported as ours is the so-far rebased series, starting with <upstream>, and theirs is the working branch.” And it adds: “In other words, the sides are swapped.” On feature:

# On feature, merging main: ours (stage 2) is feature
$ git show :2:f.txt
my feature
$ git show :3:f.txt
main change
# On feature, rebasing onto main: ours (stage 2) is main
$ git show :2:f.txt
main change
$ git show :3:f.txt
my feature

It helps to see the original version. With zdiff3, available since Git 2.35, which the git-config documentation describes as “similar to diff3 but removes matching lines on the two sides from the conflict region when those matching lines appear near either the beginning or end of a conflict region”, the block shows where both sides started:

$ git config merge.conflictStyle zdiff3
$ git merge -q --no-edit feature
$ cat f.txt
<<<<<<< HEAD
main change
||||||| ef47d0d
base
=======
my feature
>>>>>>> feature

To get out, git rebase --abort went back to the original tip even after part of the conflict had been resolved, and what was resolved was lost. git merge --abort has a limit: per the git-merge documentation, it may fail to reconstruct the original state “if there were uncommitted changes when the merge started”. If the merge would touch a modified file, Git refuses before starting.

Two traps at the end. git add doesn't validate anything: it accepted a file with the markers still inside and the commit went through, while git diff --cached --check catches them beforehand. And rerere, “reuse recorded resolution”, once enabled with git config rerere.enabled true, also remembers a wrong resolution. During the conflict, git rerere forget <path> erases that memory, but the file doesn't change: to resolve it again, run git checkout -m <path>.

A clean merge guarantees nothing either, since Git doesn't understand code. In our run, a merge with no conflicts ended in greet: command not found. That's what automated tests before merging are for.

Start every merge or rebase with a clean tree. If you have uncommitted changes, git merge --abort may not put you back where you were.

What can be recovered

This is the second question, answered with one run per row:

Where the work wasWhat happenedDoes it come back?How
Commitreset --hardYesgit reset --hard HEAD@{1}
CommitUnmerged branch deleted with -DYesThe hash -D prints; failing that, git reflog or git fsck --lost-found. Then git branch <name> <hash>
Commitcommit --amendYesHEAD@{1}
CommitA rebase gone wrongYesgit reset --hard ORIG_HEAD
Stashgit stash dropYes, until it is prunedThe hash drop prints, or the WIP on commit listed by git fsck --unreachable; then git stash apply <hash>
Staging areareset --hardThe content yes; the file name nogit fsck --lost-found and git cat-file -p
Only on disk, tracked filereset --hardNofsck finds nothing
Only on disk, tracked filegit restoreNo, and no warningNone
Untrackedgit clean -fNo: Git never stored itLook first with git clean -n
CommitReflog expired and gc --prune=nowNoNone

The most common case, with the real output:

$ git reset -q --hard HEAD~1
$ cat f.txt
base
$ git reflog -2 --format='%gd %gs'
HEAD@{0} reset: moving to HEAD~1
HEAD@{1} commit: second
$ git reset -q --hard HEAD@{1}
$ cat f.txt
two

Check that HEAD@{1} before you copy it. It moves with every operation: after a git switch -c it pointed at another commit, so git reflog comes first. In PowerShell it fails without quotes: write 'HEAD@{1}'. And if you kept working after the mistake, --hard erases that too, while git branch rescue HEAD@{1} recovers the commit without touching your files. ORIG_HEAD, which the revisions reference says “is created by commands that move your HEAD in a drastic way”, gets overwritten by the next command that uses it.

With reset, the option makes the difference. --hard does what the documentation says: “Overwrite all files and directories with the version from <commit>”. --keep stops: “If a file that is different between <commit> and HEAD has local changes, reset is aborted.” In our run it refused and the modified file stayed intact. So look at git status first.

The safety net expires. Per the git-gc documentation, by default the reflog lasts 90 days, entries unreachable from the current tip 30, and unreachable loose objects are pruned after 2 weeks, when gc runs. All of that is configurable. The reflog isn't a backup: neither it nor git fsck can find objects that no longer exist. It also lives in each repository: core.logAllRefUpdates is “false by default in a bare repository”, and moving a branch by hand in a bare repository left no reflog. How long GitHub keeps forced commits isn't documented in what we read; its activity view lists events “such as pushes, merges, force pushes, and branch changes”.

Run git clean -n with the same options you plan to use: git clean -fdx -n listed more files than git clean -n. The real command deletes what Git never stored.

Forcing with care

This section comes from the git-push documentation. We did not run these commands: our bench never executes git push, not even against local repositories.

Plain --force can destroy someone else's work: “blindly pushing with --force will lose their work.” --force-with-lease adds a condition, “requiring their current value to be the same as the remote-tracking branch we have for them.” That reference is your local copy of the remote branch, and there's the catch: “this is trivially defeated if some background process is updating refs in the background.”

The only thing we could observe, since it takes no push, is that a fetch moves that reference: origin/main pointed at a teammate's commit that wasn't in the local history. We did not test the push that would follow. After the fetch:

$ git log -1 --format=%s origin/main
teammate work
$ git merge-base --is-ancestor origin/main main; echo is-ancestor=$?
is-ancestor=1

The documented mitigation is --force-if-includes, which “will verify if updates from the remote-tracking refs that may have been implicitly updated in the background are integrated locally before allowing a forced update.” It has existed since Git 2.30 and is enabled with push.useForceIfIncludes. Without --force-with-lease, or with an expected value, the documentation calls it a “no-op”. The command, which we did not run:

# Not run by us: our bench never executes git push.
git push --force-with-lease --force-if-includes origin <branch>

If anyone else uses your branch, none of this replaces telling the team. We're back at the first question.

GitHub: three buttons and what they do

GitHub's documentation describes three merge methods:

MethodWhat it doesWatch out
Merge commit“Preserves every commit from the pull request branch and adds an explicit merge point.”A more branched history
Squash and merge“Combines all commits in the pull request into a single commit on the base branch.”“Squash merging works best for short-lived branches.”
Rebase and merge“Adds each commit onto the base branch without a merge commit, for a linear history.”“Always updates the committer information and creates new commit SHAs”

After a squash, Git doesn't consider the branch merged, because the original commits aren't on the main branch, and a branch stacked on top collides when rebased. We simulated it locally with git merge --squash, so this is not GitHub's button. With rebase and merge Git doesn't consider it merged either, since it also makes new commits: we simulated it with git cherry-pick, and git branch -d refused too. The error table has the ways out.

On a team, protected branches settle part of the first question: “By default, each branch protection rule disables force pushes to the matching branches and prevents the matching branches from being deleted.” They don't stop administrators by default: “By default, the restrictions of a branch protection rule don't apply to people with admin permissions”. With strict checks, “The branch must be up to date with the base branch before merging.” A merge queue saves you that step: it “does not require a pull request author to update their pull request branch and wait for status checks to finish before trying to merge.”

If you pushed a secret

Deleting the file doesn't take it out of history: in our run, git log -S still found the value in two commits. GitHub's guide says to rotate first: “as a first step you need to revoke and/or rotate that secret.” And it warns: “If you only rewrite your history and force push it, the commits with sensitive data may still be accessible elsewhere”. Rewriting also invalidates commit signatures, according to that guide, which uses git-filter-repo. Of filter-branch, Git's own documentation says “its use is not recommended.” Prevention is cheaper: push protection “blocks pushes that contain secrets”.

If you would rather keep something out of the history, a hook can stop it before the commit: this example blocks a co-author line in Claude Code's own commands.

Errors you will run into

SituationWhat Git saysWay out
Reverting a merge without choosing a sideerror: commit ... is a merge but no -m option was given.git revert -m 1 <merge> if the main branch is the first parent; otherwise -m 2
Reverting with the wrong parentThe main branch's side disappearsSee where each side comes from first with git log --graph --oneline --decorate --all. The column doesn't give the order: with a later commit on the branch, the first parent came out on the right. git show --no-patch --pretty=raw <merge> lists both parents in order: the first is -m 1. If the merge was made from the branch, the main branch is the second parent
Merging again after a revert, with no new commits on the branchAlready up to date.Revert the revert by its hash, then merge, or recreate the branch from where it started: on feature, git rebase --no-ff <hash>, with the hash from git merge-base <merge>^1 <merge>^2. main won't do: Git reports success, the branch ends up identical to main and you stay at Already up to date. It rewrites the branch, so the first question applies
Merging again after a revert, with a fix on the branchCONFLICT (modify/delete): a.txt deleted in HEAD and modified in feature., CONFLICT (content), or only the fix comes inRevert the revert by its hash, then merge
Branch merged by squash or rebase that Git doesn't consider mergederror: the branch 'feature' is not fully mergedCheck the PR and delete with -D
Rebasing a stacked branch after a squashCONFLICT (content): Merge conflict in f.txtgit rebase --abort, then git rebase --onto main feature stacked before deleting feature. If it's gone, use its old hash
Rebasing with uncommitted changeserror: cannot rebase: You have unstaged changes.git rebase --autostash main. If reapplying collides, your changes stay in the stash
A branch named like a file, with git checkout f.txtSwitched to branch 'f.txt', and the file stays modifiedgit restore for files, git switch for branches
HEAD@{1} after another operationIt already points elsewhereSearch git reflog

The case from the opening, in full, with no new commits on the branch:

$ git revert --no-edit HEAD
error: commit 5cb4048c4a22388066f717eb4170ac80d2cd2511 is a merge but no -m option was given.
fatal: revert failed
[exit 128]
$ git revert -m 1 --no-edit HEAD > /dev/null; ls
c.txt
f.txt
$ git merge --no-edit feature
Already up to date.
$ ls
c.txt
f.txt

If the branch already has a fix, Git doesn't say that. With the fix in a new file, the merge brought only that file and a.txt stayed missing. Editing a.txt, it stopped at a modify/delete. What worked for us was reverting the revert and merging afterwards, on a new branch and using the revert's hash:

$ git switch -q -c reland main
$ git log --format="%h %s" --grep=Revert
a17162d Revert "Merge branch 'feature'"
$ git revert --no-edit a17162d > /dev/null; ls
a.txt
c.txt
f.txt
other.txt
$ cat a.txt
feature code
$ git merge --no-edit -q feature; cat a.txt
fixed

Two cautions. With HEAD instead of the hash, git revert undoes the latest commit, whatever it is: in our run it took out a teammate's. And reverting the revert on the main branch brings the bug back until the fix lands, so do both on a new branch and take it to main in a single pull request.

The guide by Torvalds and Hamano gives the reason: a revert “does absolutely nothing to the effects on _history_ that the merge had.” If you fixed it with commits on top, “you would want to first revert the previous revert”. If you rebuilt the branch with rebase, it says the opposite: “re-merging the result without doing anything else fancy would be the right thing to do”. We ran that with git rebase --no-ff <hash> from where the branch started and the code came back without reverting the revert. The guide warns: “So do not do "revert of revert" blindly without thinking.”

On GitHub, the revert button does this: “Reverting a merged pull request creates a new pull request that reverts the original merge commit.” That's why we infer that, if the pull request was merged with a merge commit, the retry trips up the same way, though we didn't test it there. Locally, after reverting a squash, merging again did bring the code back.

Before git revert -m 1, check where each side comes from with git log --graph --oneline --decorate --all. If the merge was made from the branch, the main branch is the second parent and the number is 2. With the wrong number, the side you wanted to keep is the one that disappears.

What this does not cover

  • Work that exists only on disk: no technique here recovers it.
  • --force-with-lease and --force-if-includes: documented, not run.
  • GitHub's squash button and retrying after reverting a pull request: not tested on GitHub.
  • Clean merges with logic errors.
  • Files in Git LFS, submodules and binaries; file name casing and line endings; signed commits: not tested.
  • Your configuration: with pull.rebase or your own aliases, the output may differ. Apart from HEAD@{1}, nothing was tested in PowerShell. The bench isn't published, but every command can be repeated in a test repository.

Frequently asked questions

Can I rebase a branch I already pushed?

If nobody else works on it, yes, and you'll have to force the upload. If others started from those commits, Pro Git says no, and the git-rebase documentation warns that whoever has them will need to fix their history by hand.

How do I recover a commit after reset --hard?

Find the commit in git reflog and go back to it with git branch rescue <hash>, which leaves your files alone. That works while the entry hasn't expired: after a reset the commit is no longer reachable from the current tip, so the default limit is 30 days. Anything never committed won't be there.

What is the difference between --force and --force-with-lease?

Per the documentation, --force overwrites without looking, and --force-with-lease requires the remote branch to still be as your local copy saw it. A background fetch can defeat that guarantee, which is what --force-if-includes is for. We tested none of the three.

Conclusion

Before a command that rewrites or deletes, ask who else has those commits and where the thing you could lose is stored. In our opinion, the rule these runs leave is: commit or run git stash -u before you take a risk. -u saves untracked files but not ignored ones; git stash -a does include them, but it drags along things like node_modules, so don't start there. Next time you hesitate, run git status and git reflog before the command you were about to copy.

References

Subscribe

Get the latest posts delivered right to your inbox.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Comments

No comments yet. Be the first to share your thoughts!

Subscribed!

Registered! A confirmation link has been sent to your email address. If you don't see it, please check your spam folder.

Error

An error occurred. Please try again.

Full code