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

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

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

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

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

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


当前回答

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

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的回答。

其他回答

这是我喜欢的方法:

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

这将创建一个带有一个提交的新分支,该提交将在HEAD中添加所有内容。它不会改变任何其他东西,所以它是完全安全的。

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

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

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

唯一适用于我(并保持子模块工作)的解决方案是

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

当我有子模块时,删除.git/总是会引起巨大的问题。使用gitrebase--root会给我带来一些冲突(因为我有很多历史,所以需要很长时间)。