Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete the old git history?

I have git repository with many, many (2000+) commits, for example:

                 l-- m -- n                    / a -- b -- c -- d -- e -- f -- g -- h -- i -- j -- k                      \                       x -- y -- z 

and I want to truncate old log history - delete all commits from log history starting from (for example) commit "f" but as the beginning of repository.

How to do it?

like image 371
Nips Avatar asked Jan 31 '17 08:01

Nips


People also ask

How do I completely delete a file from git history?

The easiest way to delete a file in your Git repository is to execute the “git rm” command and to specify the file to be deleted. Note that by using the “git rm” command, the file will also be deleted from the filesystem.

Does git rm remove history?

No, git rm will only remove the file from the working directory and add that removal into the index. So only future commits are affected. All previous commits stay the same and the history will actually show when you removed the file from the repository.

Can git history be rewritten?

There are many ways to rewrite history with git. Use git commit --amend to change your latest log message. Use git commit --amend to make modifications to the most recent commit. Use git rebase to combine commits and modify history of a branch.


Video Answer


1 Answers

In order not to lose some history; better first take a copy of your repository :). Here we go: (<f> is the sha of the commit f that you want to be the new root commit)

git checkout --orphan temp <f>      # checkout to the status of the git repo at commit f; creating a branch named "temp" git commit -m "new root commit"     # create a new commit that is to be the new root commit git rebase --onto temp <f> master   # now rebase the part of history from <f> to master onthe temp branch git branch -D temp                  # we don't need the temp branch anymore 

If you have a remote where you want to have the same truncated history; you can use git push -f. Warning this is a dangerous command; don't use this lightly! If you want to be sure that your last version of the code is still the same; you can run git diff origin/master. That should show no changes (since only the history changed; not the content of your files).

git push -f   

The following 2 commands are optional - they keep your git repo in good shape.

git prune --progress                 # delete all the objects w/o references git gc --aggressive                  # aggressively collect garbage; may take a lot of time on large repos 
like image 177
Chris Maes Avatar answered Sep 20 '22 20:09

Chris Maes