Petersnow2
Petersnow2

Reputation: 69

Best way to remove commits from history?

I would like to remove 7/8 commits from around two years ago from my GitHub repository. Only 2/3 of the commits touch any code, the rest were just adding and removing the config files.

Some previous developers uploaded and removed literally > 650 duplicate config files, and it is messing up our github stat page. Stat Graph

We've tried removing them with git rebase -i, but it took 6 hours and most parts of the code were gone.

How do we remove these ancient commits without messing up other commit history? We're currently recoding all code on the repository, so it is not a big deal if the changes from those individual commits aren't kept, but we'd like to keep all the statistics that went along with the old code besides this.

Upvotes: 2

Views: 207

Answers (2)

Tom Lord
Tom Lord

Reputation: 28285

Obligatory DANGER: Re-writing the project history is very risky! Make sure you have a backup before attempting this, and proceed with extreme caution!

To delete one specific commit in a project (e.g. from years ago), you can:

git rebase -p --onto SHA^ SHA

Where SHA is the commit you want to delete.

The documentation for these options is:

-p, --preserve-merges
  Recreate merge commits instead of flattening the history by replaying
  commits a merge commit introduces. Merge conflict resolutions or
  manual amendments to merge commits are not preserved.

--onto <newbase>
  Starting point at which to create the new commits. If the --onto
  option is not specified, the starting point is <upstream>. May
  be any valid commit, and not just an existing branch name.

After making this change, you'll need to:

git push --force origin master
#        ^^^^^^^
#          !!!

Upvotes: 1

Gonzalo Matheu
Gonzalo Matheu

Reputation: 10064

Two steps are needed:

  1. Rewrite git history, with one of:
    • Rebase from the last good commit, discarding all messy commits:

git rebase --interactive good-commit-sha

  • or filter-branch

git filter-branch --tree-filter 'rm -f config-files' HEAD

  1. Force push to the master:

git push --force origin master

Note that push force is strongly discouraged, since it will make all current clones of your repo inconsistent. Any conflict will have to be fixed manually.

Upvotes: 0

Related Questions