从远程Git存储库中删除所有文件和历史记录,而不删除存储库本身

60

如果有人能告诉我如何在不删除git仓库本身的情况下删除git仓库中的每个文件/文件夹,我将不胜感激。我想删除与这些文件相关的所有历史记录。


1
你的标题说你正在讨论清理“远程git存储库”,并且你已经标记了这个问题为“github”,所以你是想减少在github上使用的空间吗?还是你在谈论另一个远程存储库?这里需要更多的细节。 - Mark Longair
我想要“删除我的git仓库中的每一个文件/文件夹,但并不实际删除仓库本身”。我说的是我的github仓库。 - max_
1
删除历史记录还是保留历史记录? - knittl
2
然后,ceilingfish的答案是正确的(删除分支和标签)。为什么你想要这么做? - knittl
4个回答

80

如我在此答案中解释删除或删除远程Git存储库的所有历史记录,提交和分支?,你也可以通过以下方法实现与Ceilingfish的答案相同的目标(即删除远程存储库中的所有引用/分支/标记):

  1. Create new empty repo with initial commit:

    mkdir new
    cd new
    echo "This is the README" > README.md
    git init
    git add .
    git commit -m "Add README.md (initial commit)"
    
  2. Add remote repo as origin:

    git remote add origin <url-to-remote>
    
  3. Mirror push to remote:

    git push origin --mirror
    

这将会删除远程代码仓库中的所有引用、分支和标签,同时任何悬空提交可能最终会被垃圾回收。以下是来自 官方 Linux Kernel Git文档关于 git push 的说明(重点是我的):

--mirror

Instead of naming each ref to push, specifies that all refs under refs/ (which includes but is not limited to refs/heads/, refs/remotes/, and refs/tags/) be mirrored to the remote repository. Newly created local refs will be pushed to the remote end, locally updated refs will be force updated on the remote end, and deleted refs will be removed from the remote end.


11
您可以像这样从存储库远程删除分支。
git push origin :branchname

如果你有任何标签需要删除,可以像这样操作:

git push origin :refs/tags/tagname

这里假设您已经设置了一个名为origin的github远程仓库。

但是这将保留计算机上本地的标签/分支。


1
我无法删除主分支。有没有一种方法只删除其中的所有文件? - max_
1
你可以在本地创建一个空的分支(git branch cleanerbranch),删除其中所有的文件,然后提交更改(commit)。接着将该分支推送到远程仓库(git push origin cleanerbranch:master)。 - Ceilingfish
7
或者创建一个新的代码仓库,进行初始提交,可以是任何你想要的内容(如果需要的话,甚至可以不提交任何内容),然后将该仓库的主分支推送上去即可。完成。 - Cascabel
@Jefromi:是的,容易得多 :) - Mark Longair
@Jefromi git push origin --mirror也特别有效,正如这个答案中所解释的那样。 - user456814
显示剩余3条评论

4

这是我所做的:

git rm -r -f -q

git commit

git push

然后你需要手动删除文件,git rm 从仓库中删除文件但不从文件系统中删除。


这不会删除 Git 历史记录! - wolfd

1

简单的解决方案

  1. 在一个新目录中使用git init创建一个空仓库。
  2. git remote add origin <远程地址>
  3. 如果远程服务器是GitHubgit checkout -b main
  4. git push origin --mirror

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接