I use git for various projects (personal repositories only), and I want to do some housekeeping.
I have a downloaded git project tree that has a large history of commits. After downloading I made a few more myself. However, I do not need anything apart from the latest commit at the time I downloaded it, and the subsequent commits that I made. All the prior commits take up a lot of space, and I'd like to get rid of them.
What I should have done is delete the .git folder after download and create a new personal repository going forward - but I didn't.
Can I clean up the repository so that everything prior to commit X is removed, as if it had never existed, but so that subsequent commits are maintained? If so, how? Also, if possible, if there were multiple branches at that time, can I remove other branches also?
(Not sure if this is possible as I think one of git's claims is how hard it is to lose old data by mistake.)
I have a downloaded git project tree that has a large history of commits. After downloading I made a few more myself.
Since you've only a made "a few more" that you wish to keep, I'm going to assume your "new" history is linear. If that's the case, then this is extremely easy to do. For this example we'll assume the branch you want to keep is called main:
# make sure your status is clean
git status # verify it's "nothing to commit, working tree clean"
# Figure out your first commit ID
git log --reverse # let's call the first result ID <repo-root-commit-id>
# Figure out the commit you started from (parent of your first new commit)
git log # let's call the starting commit X, as stated in the question
# Make a new temp branch from the commit you started from (commit X)
git switch -c temp-branch X
# soft reset to the repo root commit
git reset --soft <repo-root-commit-id>
# Now the entire history from initial commit through X will be staged
# Make all of this a single commit and squash into initial commit
git commit --amend -m "Squash repo history into a single commit"
# Now rebase all of your new commits onto the temp branch
git rebase X main --onto temp-branch
# Now your rewritten main branch is as desired, delete the temp branch
git branch -d temp-branch
Since your goal is to recover space used by the old history, you can remove your remote, delete all local branches except main, and either garbage collect now or re-clone your new repo to another place. For example, those links are summarized here:
# Remove the remote:
git remote remove origin
# Delete all local branches except main
git branch | grep -v main | xargs git branch -D
# Garbage Collect everything now
git reflog expire --expire=now --all
git gc --aggressive --prune=now
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With