user4981459
user4981459

Reputation:

Git how to keep latest N commits on feature branch and delete everything

I have total 44 commits on my feature branch. Among those latest 24 commits are mine. Remaining old commits I need to delete. Those appeared on branch due to wrong rebase operation perform by me. I am sure that my commits are latest on the git log list and appear on top.

Kindly help.

Upvotes: 2

Views: 300

Answers (1)

Romain Valeri
Romain Valeri

Reputation: 22057

First of all, it might be easier to check your reflog for the state before the wrong rebase rather than trying to fix the resulting mess.

git reflog
# spot the commit you want to go back to, then 
git reset --hard <goodCommit>
# or the more cautious alternative, creating a new branch from the state to recover
git checkout -b <recovery-branch> <goodCommit>

However, to answer the question if for any reason the reflog solution can't be used, if you have already clearly identified the commits you want to keep from your branch, just recreate a branch from the intended base, and cherry-pick your commits back on it :

git checkout -b <new-branch> <base-branch>

# with the oldest good commit you spotted on the failed branch
git cherry-pick <oldestGoodCommit>^..<failed-branch>

(mind the ^ here, its role is to refer to the commit's parent)
(also, the .. is not a placeholder or anything, it's literally the sign for range selection. A..B means "everything from B except everything on A" )

But prepare for potential conflicts along the road if you choose this solution (which is not inherently a bad thing, but could be a lot of effort compared to the alternative).

Upvotes: 2

Related Questions