我目前有一个本地Git存储库,我将其推送到Github存储库。

本地存储库有约10个提交,Github存储库是这一点的同步副本。

我想做的是从本地Git存储库中删除所有版本历史记录,这样存储库的当前内容将显示为唯一的提交(因此不会存储存储库中的旧版本文件)。

然后我想将这些更改推送到Github。

我已经研究过Git的rebase,但这似乎更适合删除特定版本。另一个可能的解决方案是删除本地回购,并创建一个新的回购-尽管这可能会产生大量工作!

ETA:有些特定的目录/文件未被跟踪-如果可能的话,我想保持这些文件的未跟踪。


当前回答

为此,请使用浅层克隆命令gitclone--深度1 URL-它将仅克隆存储库的当前HEAD

其他回答

这将删除主分支上的历史记录(您可能需要在运行命令之前进行备份):

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

这是基于@dan_waterworth的回答。

干得好:

#!/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"
}

也在此处托管:https://gist.github.com/Zibri/76614988478a076bbe105545a16ee743

以下是根据@Zeelot的回答改编的脚本。它应该从所有分支中删除历史记录,而不仅仅是主分支:

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

它符合我的目的(我没有使用子模块)。

以下是清除Github存储库历史的步骤

首先,从.git中删除历史记录

rm -rf .git

现在,仅从当前内容重新创建git repo

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

推送到Github远程repo,确保您覆盖历史记录


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

要从git中删除最后一次提交,只需运行

git reset --hard HEAD^ 

如果要从顶部删除多个提交,可以运行

git reset --hard HEAD~2 

删除最后两个提交。你可以增加数量以删除更多提交。

更多信息请点击此处。

Git tutoturial在这里提供了如何清除存储库的帮助:

您希望从历史记录中删除该文件,并将其添加到.gitignore以确保不会意外再次提交。例如,我们将从GitHub gem存储库中删除Rakefile。

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

既然我们已经从历史中删除了该文件,让我们确保不要不小心再犯了。

echo "Rakefile" >> .gitignore

git add .gitignore

git commit -m "Add Rakefile to .gitignore"

如果您对存储库的状态感到满意,您需要强制推送更改以覆盖远程存储库。

git push origin master --force