3

在 svn 中,我经常删除包含我不再感兴趣的工作的分支,我知道如果我真的需要,我可以在以后的任何时间恢复它们。

在 git 中,这似乎是不可能的。这意味着我现在在 'git branch -a' 中有大约 50 个分支,我不希望再次使用它们,但不想永远失去它们。

git 中真的没有办法以版本控制的方式删除分支吗?在没有听起来反git的情况下,为什么git设计成几乎需要(在我看来)以无法恢复的方式丢弃旧分支?这不违背版本控制的想法。

4

6 回答 6

3

一种可能性是为要归档的分支创建一个标签,然后您可以删除该分支。

git tag -a <tagname> <branchname>

然后,如果您想恢复分支,您可以从标签创建一个新分支。

git checkout -b <branchname> <tagname>

它还可能有助于为标签开发命名方案,以便所有存档的分支标签在一起并位于标签列表的顶部或底部。

于 2012-11-20T17:55:59.557 回答
3

我有时做的一件事是用前缀重命名分支:

git branch -m foo old/foo

您可以做的另一件事是将要保存的分支推送到另一个裸 Git 存储库以进行保管,然后在本地存储库中删除它们:

git remote add archive /path/to/archive/repo.git
git push archive foo
git branch -D foo
于 2012-11-20T17:57:40.290 回答
3

您可以为 git 使用的正常命名空间之外的分支头创建一个 ref。这将阻止git branch列出分支,但会确保该分支的提交不会被垃圾收集,并且如果您稍后决定您确实需要它,仍然会提供一个名称来取回该分支。

git update-ref refs/attic/old_topic_branch old_topic_branch
git branch -D old_topic_branch

这个阁楼空间中的分支可以列出:

git for-each-ref refs/attic

并且可以通过以下方式恢复分支:

git checkout -b old_topic_branch refs/attic/old_topic_branch

但是,如果您打算在任何时候放弃旧的存储库(例如移动到新计算机),您仍然需要小心地将这些引用移动到新的存储库,因为在克隆存储库时这些引用不会被复制。

于 2012-11-20T20:11:51.200 回答
1

另一种可能性是简单地重命名“死”分支,可能与“命名空间”它们一起使用。例如,如果我不再需要该分支topicbranch42,但将来可能需要它以供参考,请执行以下操作:

git checkout master # or any other branch that isn't topicbranch42
git branch -m topicbranch42 deprecated/topicbranch42

这样,您可以保留所有分支,但它们的名称提供了一个非常清晰的指示,它们没有处于积极的开发/使用中

于 2012-11-20T18:37:43.110 回答
0

我今天早上才意识到这个问题的正确答案:

.git/refs 下的所有内容都是参考,因此不会被修剪,但只有 refs/heads 是分支,refs/tags 是标签等。所以只需将分支分流到“归档”参考目录。真正的蛮力方法是mkdir -p .git/refs/archive/heads; mv .git/refs{,/archive}/heads/master踩踏该分支的任何先前存档的版本;这是一个更彻底的版本:

#!/bin/sh
# archive a branch, by committing it to .git/refs/archive/heads/
# to unarchive the branch, say 'git branch mybranch archive/heads/mybranch~'
# ---- NOIICE the parent link in the branch command above ----------------/
# any second parent of the archive ref is the previous archive header commit

getopts x x && set -x -v && shift

while test $# -ne 0; do
    branch="refs/heads/$1"
    archive="refs/archive/heads/$1"
    git rev-parse -q --verify "$branch" >&- \
    || { echo >&2 archive-branch ignored nonexistent branch: $1; shift; continue; }
    previously=`git rev-parse -q --verify "$archive"`
    git mktree </dev/null | xargs git commit-tree \
        -p "`git rev-parse "$branch"`" \
        ${previously:+ -p $previously} \
        -m "Parent is the archived tip of branch '$1'" \
        ${previously:+ -m 'Second parent is the previous commit like this one.'} \
    > "`git rev-parse --git-dir`/$archive"
    rm "`git rev-parse --git-dir`/$branch"
    shift
done
于 2013-01-08T18:11:26.743 回答
-1

删除 git 分支只会删除引用提交的标签。
您可以运行git checkout <commit-hash>以恢复已删除的分支,只要您在某处写下哈希即可。

运行git gc将永久删除这些孤立的提交。

于 2012-11-20T17:50:21.673 回答