You can restore a Git commit from a deleted branch by using the reflog
command to see the commit, and then cherry-pick
(not the only option) to bring it to your current branch.
In my case, the commit showed in the log with its hash identifier, which I was able to use to cherry-pick it right away. Here's what my console looks like (some details changed for privacy):
$ git reflog
78c06e74 (HEAD -> mybranch, origin/otherbranch, otherbranch) HEAD@{0}: checkout: moving from otherbranch to mybranch
78c06e74 (HEAD -> mybranch, origin/otherbranch, otherbranch) HEAD@{1}: merge origin/otherbranch: Merge made by the 'recursive' strategy.
7895185c HEAD@{2}: checkout: moving from master to otherbranch
fcacde67 (origin/master, origin/HEAD, master) HEAD@{3}: checkout: moving from otherbranch to master
7895185c HEAD@{4}: commit: some random commit
5bfa43e4 HEAD@{5}: commit (merge): Merge remote-tracking branch 'origin/master' into otherbranch
5f597f23 HEAD@{6}: checkout: moving from mybranch to otherbranch
24e2fee9 HEAD@{7}: commit: my important commit that I accidentally deleted!!!
dace6a89 HEAD@{8}: merge yetanotherbranch: Merge made by the 'recursive' strategy.
$ git cherry-pick 24e2fee9
Auto-merging src/myfile.php
warning: inexact rename detection was skipped due to too many files.
warning: you may want to set your merge.renamelimit variable to at least 3300 and retry the command.
[mybranch 3d1bc484] my important commit that I accidentally deleted!!!
Date: Tue Apr 19 15:41:37 2022 -0500
1 file changed, 46 insertions(+)
78c06e74 (HEAD -> mybranch, origin/otherbranch, otherbranch) HEAD@{0}: checkout: moving from otherbranch to mybranch
78c06e74 (HEAD -> mybranch, origin/otherbranch, otherbranch) HEAD@{1}: merge origin/otherbranch: Merge made by the 'recursive' strategy.
7895185c HEAD@{2}: checkout: moving from master to otherbranch
fcacde67 (origin/master, origin/HEAD, master) HEAD@{3}: checkout: moving from otherbranch to master
7895185c HEAD@{4}: commit: some random commit
5bfa43e4 HEAD@{5}: commit (merge): Merge remote-tracking branch 'origin/master' into otherbranch
5f597f23 HEAD@{6}: checkout: moving from mybranch to otherbranch
24e2fee9 HEAD@{7}: commit: my important commit that I accidentally deleted!!!
dace6a89 HEAD@{8}: merge yetanotherbranch: Merge made by the 'recursive' strategy.
$ git cherry-pick 24e2fee9
Auto-merging src/myfile.php
warning: inexact rename detection was skipped due to too many files.
warning: you may want to set your merge.renamelimit variable to at least 3300 and retry the command.
[mybranch 3d1bc484] my important commit that I accidentally deleted!!!
Date: Tue Apr 19 15:41:37 2022 -0500
1 file changed, 46 insertions(+)
Final thoughts
Thank you, Git, you saved my day.
Also, even if reflog
isn't helping, there are other options.