Search code examples
gitgit-rebase

Flatten old history in Git


I have a git project that has run for a while and now I want to throw away the old history, say from start to two years back from now. With throw away I mean replace the many commits within this time with one single commit doing the same.

I checked git rebase -i but this does not remove the other (full) history containing all commits from git.

Here a graphical representation (d being the changesets):

(base) -> d1 -> d2 -> d3 -> (HEAD)

What I want is:

(base) -> d1,d2 -> d3 -> (HEAD)

How could this be done?


Solution

  • If you do not really care about the whole history, another simple way to do this would be to take the current branch and create an orphan branch based on this. Then add all files to this branch and make one initial commit (which would lose all history). This can then be pushed to the remote repository.

    Assuming you are in the branch that you want to flatten. First check if it is clean:

    git status -s
    

    The above command should not output anything.

    Now create a orphan branch:

    git checkout --orphan flattened
    

    Add all files

    git add .
    

    Create single commit

    git commit -m "Initial flattened commit"
    

    Check if everything is as wanted and push to remote (ex):

    git status -s
    
    # (original_branch being the branch with the full history)
    git diff original_branch..flattened  
    
    # (assuming your remote is origin and the branch to overide is master) 
    # Think twice before doing this!
    git push origin +flattened:master