ChatGPT解决这个技术问题 Extra ChatGPT

Make the current commit the only (initial) commit in a Git repository?

I currently have a local Git repository, which I push to a Github repository.

The local repository has ~10 commits, and the Github repository is a synchronised duplicate of this.

What I'd like to do is remove ALL the version history from the local Git repository, so the current contents of the repository appear as the only commit (and therefore older versions of files within the repository are not stored).

I'd then like to push these changes to Github.

I have investigated Git rebase, but this appears to be more suited to removing specific versions. Another potential solution is to delete the local repo, and create a new one - though this would probably create a lot of work!

ETA: There are specific directories / files that are untracked - if possible I would like to maintain the untracking of these files.

See also stackoverflow.com/questions/435646/… ("How do I combine the first two commits of a Git repository?")

8
8 revs, 5 users 51%

Here's the brute-force approach. It also removes the configuration of the repository.

Note: This does NOT work if the repository has submodules! If you are using submodules, you should use e.g. interactive rebase

Step 1: remove all history (Make sure you have backup, this cannot be reverted)

cat .git/config  # note <github-uri>
rm -rf .git

Step 2: reconstruct the Git repo with only the current content

git init
git add .
git commit -m "Initial commit"

Step 3: push to GitHub.

git remote add origin <github-uri>
git push -u --force origin main

Thanks larsmans - I have opted to use this as my solution. Though initialising the Git repo loses record of untracked files in the old repo, this is probably a simpler solution for my problem.
@kaese: I think your .gitignore should handle those, right?
Save your .git/config before, and restore it after.
Be careful with this if you are trying to remove sensitive data: the presence of only a single commit in the newly pushed master branch is misleading - the history will still exist it just won't be accessible from that branch. If you have tags, for example, which point to older commits, these commits will be accessible. In fact, for anyone with a bit of git foo, I'm sure that after this git push, they will still be able to recover all history from the GitHub repository - and if you have other branches or tags, then they don't even need much git foo.
So many bad answers in the world and after an hour I finally got this to do my bidding!
M
MatthewG

The only solution that works for me (and keeps submodules working) is

git checkout --orphan newBranch
git add -A  # Add all files and commit them
git commit
git branch -D master  # Deletes the master branch
git branch -m master  # Rename the current branch to master
git push -f origin master  # Force push master branch to github
git gc --aggressive --prune=all     # remove the old files

Deleting .git/ always causes huge issues when I have submodules. Using git rebase --root would somehow cause conflicts for me (and take long since I had a lot of history).


this should be the correct answer! just add a git push -f origin master as the last op and sun will shine again on your fresh repo! :)
@JonePolvora git fetch; git reset --hard origin/master stackoverflow.com/questions/4785107/…
after doing this, will the repo free space?
Git will keep the old files around for a while, to get rid of them run git gc --aggressive --prune=all. In addition, git will continue to store history for any commits that are referenced with branches or tags. To check, run git tag -l and git branch -v, then delete any you find. Also double check your remote with git ls-remote, you may need to delete remote tags/branches as well or when you fetch you will get all the linked files again.
I believe you should add @JasonGoemaat 's suggestion as the last line to your answer. Without git gc --aggressive --prune all the whole point of losing history would be missed.
d
dan_waterworth

This is my favoured approach:

git branch new_branch_name $(echo "commit message" | git commit-tree HEAD^{tree})

This will create a new branch with one commit that adds everything in HEAD. It doesn't alter anything else, so it's completely safe.


Best approach! Clear, and do the work. Additionally, i rename the branch with a lot of changes from "master" to "local-work" and "new_branch_name" to "master". In master, do following: git -m local-changes git branch -m local-changes git checkout new_branch_name git branch -m master<
This looks really short and sleek, the only thing I don't understand or haven't seen yet is HEAD^{tree}, could somebody explain? Apart from that I'd read this as "create new branch from given commit, created by creating a new commit-object with given commit-message from ___"
The definitive place to look for answers to questions about git reference syntax is in the git-rev-parse docs. What's happening here is git-commit-tree requires a reference to a tree (a snapshot of the repo), but HEAD is a revision. To find the tree associated with a commit we use the <rev>^{<type>} form.
Nice answer. Works well. Finally say git push --force <remote> new_branch_name:<remote-branch>
And everything in one line: git branch newbranch $(echo "commit message" | git commit-tree HEAD^{tree}) | git push --force origin newbranch:master
C
Carl

The other option, which could turn out to be a lot of work if you have a lot of commits, is an interactive rebase (assuming your git version is >=1.7.12):git rebase --root -i

When presented with a list of commits in your editor:

Change "pick" to "reword" for the first commit

Change "pick" to "fixup" every other commit

Save and close. Git will start rebasing.

At the end you would have a new root commit that is a combination of all the ones that came after it.

The advantage is that you don't have to delete your repository and if you have second thoughts you always have a fallback.

If you really do want to nuke your history, reset master to this commit and delete all other branches.


After rebase completed, I can not push: error: failed to push some refs to
@Begueradj if you've already pushed the branch you rebased, then you will need to force push git push --force-with-lease. force-with-lease is used because it is less destructive than --force.
e
emotality

Variant of larsmans's proposed method:

Save your untrackfiles list:

git ls-files --others --exclude-standard > /tmp/my_untracked_files

Save your git configuration:

mv .git/config /tmp/

Then perform larsmans's first steps:

rm -rf .git
git init
git add .

Restore your config:

mv /tmp/config .git/

Untrack you untracked files:

cat /tmp/my_untracked_files | xargs -0 git rm --cached

Then commit:

git commit -m "Initial commit"

And finally push to your repository:

git push -u --force origin master

S
Shafique Jamal

Below is a script adapted from @Zeelot 's answer. It should remove the history from all branches, not just the master branch:

for BR in $(git branch); do   
  git checkout $BR
  git checkout --orphan ${BR}_temp
  git commit -m "Initial commit"
  git branch -D $BR
  git branch -m $BR
done;
git gc --aggressive --prune=all

It worked for my purposes (I am not using submodules).


I think you forgot to force push master to complete the procedure.
I had to make a slight modification. git branch will include an asterisk next to your checked out branch, which will then be globbed, causing it to resolve to all files or folders as if those were branch names too. Instead, I used git branch --format="%(refname:lstrip=2)" which gave me just the branch names.
@not2qubit: Thanks for this. What would be the exact command? git push --force origin master, or git push --force-with-lease? Apparently the latter is safer (see stackoverflow.com/questions/5509543/…)
@BenRichards. Interesting. I'll try this again at some point with a folder that matches a branch name to test it, then update the answer. Thanks.
M
Matthias M

You could use shallow clones (git > 1.9):

git clone --depth depth remote-url

Further reading: http://blogs.atlassian.com/2014/05/handle-big-repositories-git/


Such clone can not be pushed to a new repository.
It would be useful to know how to circumvent that limitation. Can someone explain why this can't be force pushed?
The answer to your question: stackoverflow.com/questions/6900103/…
A
AnoE

What I'd like to do is remove ALL the version history from the local Git repository, so the current contents of the repository appear as the only commit (and therefore older versions of files within the repository are not stored).

A more conceptual answer:

git automatically garbage collects old commits if no tags/branches/refs point to them. So you simply have to remove all tags/branches and create a new orphan commit, associated with any branch - by convention you would let the branch master point to that commit.

The old, unreachable commits will then never again be seen by anyone unless they go digging with low-level git commands. If that is enough for you, I would just stop there and let the automatic GC do it's job whenever it wishes to. If you want to get rid of them right away, you can use git gc (possibly with --aggressive --prune=all). For the remote git repository, there's no way for you to force that though, unless you have shell access to their file system.


Nice addition, when seen in context of @Zeelot 's answer.
Yup, Zeelot's has the commands which basically do this (just differently, by starting completely over, which might just be fine for OP). @MogensTrasherDK
J
Johann

Just delete the Github repo and create a new one. By far the fastest, easiest and safest approach. After all, what do you have to gain carrying out all those commands in the accepted solution when all you want is the master branch with a single commit?


One of the main points is to be able to see where it was forked from.
I just did this and it is fine
j
jthill

git filter-branch is the major-surgery tool.

git filter-branch --parent-filter true -- @^!

--parent-filter gets the parents on stdin and should print the rewritten parents on stdout; unix true exits successfully and prints nothing, so: no parents. @^! is Git shorthand for "the head commit but not any of its parents". Then delete all the other refs and push at leisure.


S
Sam Watkins

The method below is exactly reproducible, so there's no need to run clone again if both sides were consistent, just run the script on the other side too.

git log -n1 --format=%H >.git/info/grafts
git filter-branch -f
rm .git/info/grafts

If you then want to clean it up, try this script:

http://sam.nipl.net/b/git-gc-all-ferocious

I wrote a script which "kills history" for each branch in the repository:

http://sam.nipl.net/b/git-kill-history

see also: http://sam.nipl.net/b/confirm


Thanks for this. Just FYI: your script to kill the history for each branch could use some updating - it gives the following errors: git-hash: not found and Support for <GIT_DIR>/info/grafts is deprecated
@ShafiqueJamal, thanks, the little "git-hash" script is git log HEAD~${1:-0} -n1 --format=%H, here, sam.aiki.info/b/git-hash It would be better to put it all in one script for public consumption. If I ever use it again, I might figure out how to do it with the new feature that replaces "grafts".
Z
Zibri

Here you go:

#!/bin/bash
#
# By Zibri (2019)
#
# Usage: gitclean username password giturl
#
gitclean () 
{ 
    odir=$PWD;
    if [ "$#" -ne 3 ]; then
        echo "Usage: gitclean username password giturl";
        return 1;
    fi;
    temp=$(mktemp -d 2>/dev/null /dev/shm/git.XXX || mktemp -d 2>/dev/null /tmp/git.XXX);
    cd "$temp";
    url=$(echo "$3" |sed -e "s/[^/]*\/\/\([^@]*@\)\?\.*/\1/");
    git clone "https://$1:$2@$url" && { 
        cd *;
        for BR in "$(git branch|tr " " "\n"|grep -v '*')";
        do
            echo working on branch $BR;
            git checkout $BR;
            git checkout --orphan $(basename "$temp"|tr -d .);
            git add -A;
            git commit -m "Initial Commit" && { 
                git branch -D $BR;
                git branch -m $BR;
                git push -f origin $BR;
                git gc --aggressive --prune=all
            };
        done
    };
    cd $odir;
    rm -rf "$temp"
}

Also hosted here: https://gist.github.com/Zibri/76614988478a076bbe105545a16ee743


Gah! Dont make me provide my unhidden, unprotected password at the command line! Also, the output of git branch is typically poorly suited for scripting. You may want to look at the plumbing tools.
T
Tom Dörr

This deletes the history on the master branch (you might want to make a backup before running the commands):

git branch tmp_branch $(echo "commit message" | git commit-tree HEAD^{tree})
git checkout tmp_branch
git branch -D master
git branch -m master
git push -f --set-upstream origin master

This is based on the answer from @dan_waterworth.


K
Kapilrc

Here are the steps to clear out the history of a Github repository

First, remove the history from .git

rm -rf .git

Now, recreate the git repos from the current content only

git init
git add .
git commit -m "Initial commit"

Push to the Github remote repos ensuring you overwrite history


git remote add origin git@github.com:<YOUR ACCOUNT>/<YOUR REPOS>.git
git push -u --force origin master

How does this answer differ from the community wiki answer, or otherwise add value?
J
JB Lovell

I solved a similar issue by just deleting the .git folder from my project and reintegrating with version control through IntelliJ. Note: The .git folder is hidden. You can view it in the terminal with ls -a , and then remove it using rm -rf .git .


thats what he's doing in step 1: rm -rf .git ?
k
kkarki

For that use Shallow Clone command git clone --depth 1 URL - It will clones only the current HEAD of the repository


k
kiriloff

To remove the last commit from git, you can simply run

git reset --hard HEAD^ 

If you are removing multiple commits from the top, you can run

git reset --hard HEAD~2 

to remove the last two commits. You can increase the number to remove even more commits.

More info here.

Git tutoturial here provides help on how to purge repository:

you want to remove the file from history and add it to the .gitignore to ensure it is not accidentally re-committed. For our examples, we're going to remove Rakefile from the GitHub gem repository.

git clone https://github.com/defunkt/github-gem.git

cd github-gem

git filter-branch --force --index-filter \
  'git rm --cached --ignore-unmatch Rakefile' \
  --prune-empty --tag-name-filter cat -- --all

Now that we've erased the file from history, let's ensure that we don't accidentally commit it again.

echo "Rakefile" >> .gitignore

git add .gitignore

git commit -m "Add Rakefile to .gitignore"

If you're happy with the state of the repository, you need to force-push the changes to overwrite the remote repository.

git push origin master --force

Remove files or commits from the repository has absolutely no relation with the question (which asks to remove history, a completely different thing). The OP wants a clean history but wants to preserve current state of the repository.
this does not produce the result asked in the question. you are discarding all changes after the commit you keep last and losing all changes since then, but the question asks to keep current files and drop history.