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

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

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

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

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

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


当前回答

gitfilter分支是主要的手术工具。

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

--父过滤器获取stdin上的父对象,并应在stdout上打印重写的父对象;unix true成功退出,但不打印任何内容,因此:没有父级。@^!Git是“头部提交,而不是其任何父级”的简写。然后删除所有其他参考并在空闲时推送。

其他回答

下面的方法是完全可复制的,因此如果双方一致,则无需再次运行clone,只需在另一侧运行脚本即可。

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

如果您想清理它,请尝试以下脚本:

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

我为存储库中的每个分支编写了一个脚本“杀死历史”:

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

另请参见:http://sam.nipl.net/b/confirm

干得好:

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

这是暴力方法。它还删除了存储库的配置。

注意:如果存储库具有子模块,则此操作无效!如果您使用子模块,则应使用例如交互式rebase

步骤1:删除所有历史记录(确保您有备份,这无法恢复)

cat .git/config  # save your <github-uri> somewhere
rm -rf .git

步骤2:仅使用当前内容重建Git repo

在步骤2之前,如果您尚未设置init.defaultBranch配置,请通过git-config--globalinit.defaultBranch<branch-name>进行设置。在当前示例中,您可以选择main作为<branchname>

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

第三步:推送到GitHub。

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

以下是根据@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

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

larsmans建议方法的变体:

保存未跟踪文件列表:

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

保存git配置:

mv .git/config /tmp/

然后执行larsmans的第一步:

rm -rf .git
git init
git add .

还原配置:

mv /tmp/config .git/

取消跟踪未跟踪的文件:

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

然后提交:

git commit -m "Initial commit"

最后推送到您的存储库:

git push -u --force origin master