Home > Back-end >  How to clean up old commits in git?
How to clean up old commits in git?

Time:01-30

I have a GitHub repo that contains a lot of commits. I would like to remove all commits, so that only the last 20 commits or so are left. But, since I'm quite new to git, I don't know how to do that.

CodePudding user response:

Suppose your main branch is main. And suppose the SHA of the commit that you want to turn into the first commit is 123456. Then

git checkout --orphan temp 123456 
git commit -m 'new initial'
git rebase --onto temp 123455 main
git branch -D temp

For example, suppose I have

* a894910 (HEAD -> main) cc
* 045900f bb
* 35184b3 aa
* 4465ea9 X
* 62155b4 E
* 5a8cc3a A
... thousands more commits ...

And suppose I want to snip this history after the commit whose message is X. Its SHA is 4465ea9. So I say:

% git checkout --orphan temp 4465ea9
% git commit -m "new init"
% git rebase --onto temp 4465ea9 main
% git branch -D temp

The result is:

* 2ca92d4 (HEAD -> main) cc
* fb1904d bb
* 7ebe96e aa
* cba7eb2 new init

The SHA numbers have all changed, but these are copies of the desired commits.

Finally, the easiest and safest way forward is to create a new remote repo at GitHub and push main to it. If you don't know how to do that, GitHub will give you instructions when you create the new remote repo there. If you insist upon the new repo "replacing" the old repo then you can change the names of the repos, but there's really no need; just tell GitHub to delete the old repo once you're satisfied that you've done the right thing, and go right on using the new repo.

CodePudding user response:

You could:

  1. Create a new repo with only the history you want:
    git clone --depth=10
    
  2. Archive the old repo.
  •  Tags:  
  • git
  • Related