归档 Git 分支为标签
Archiving Git branches as tags

原始链接: https://etc.octavore.com/2025/12/archiving-git-branches-as-tags/

这个git别名`archive-branch`简化了归档旧分支的过程,将其转换为标签。它有效地“隐藏”了分支,使其不出现在常规工具中,同时保留了其历史记录。 该别名的工作原理是切换到`main`,将指定分支(或如果没有指定则为当前分支)标记为`archive/`,然后删除原始分支。重要的是,它利用了一个bash函数和一个`git switch`“提示”来实现shell补全——允许在别名中直接补全分支名称。 然而,此补全功能*需要*官方git补全脚本,而不是默认的zsh补全。使用Xcode的git的macOS用户可能需要创建补全脚本的符号链接,并调整他们的`.zshrc`以正确加载它,确保同时加载`git-completion.zsh`和`git-completion.bash`。最初的想法源自一个Reddit帖子。

## 将 Git 分支归档为标签 最近的 Hacker News 讨论集中在一个将 Git 分支转换为标签以进行归档的方法上。核心思想是,对于已归档的代码,分支的更新机制是不必要的——标签指向提交的静态指针就足够了。 虽然标签*可以*被修改(尽管 UI 提示相反),但有些人提倡使用不可变标签,尤其是在协作环境中,并指出流行的代码托管平台提供的功能。另一些人质疑归档的实用性,认为删除就足够了,或者更喜欢使用提交哈希作为不可变引用。 这次讨论突出了不同的工作流程:有些人合并后删除分支,而另一些人为了更容易地进行 bisect 而保留它们(尽管合并时压缩提交是一种常见做法)。将分支归档为标签的一个主要好处是保留废弃的分支以供将来参考,而不会使分支列表混乱,有些人通过第二次克隆仓库来解决这个问题。有人对官方 Git 补全脚本在大型仓库中的性能表示担忧。
相关文章

原文

I have a spicy git alias that allows me to "archive" old git branches by converting them to tags, making them less visible across git tooling.

# ~/.gitconfig
[alias]
archive-branch = "!f() { \
    : git switch; \
    local git_branch=${1:-$(git branch --show-current)}; \
    git co main && \
      git tag archive/$git_branch $git_branch && \
      git branch -D $git_branch; \
  }; f"

The magic of this alias is that aside from tagging and deleting the branch as desired, it also adds support for shell completion so I can tab complete the branch I want to archive (if not the current branch I'm on).

This is accomplished by the strange magic of wrapping the alias in an immediately executed bash function (!f() { ... }; f) and having the first line be : git switch. git switch isn't actually run; it's a hint to git to use the same completion for this alias as git switch (via and source).

Important note: the strange magic requires the official git completion script. zsh comes with its own git completion which does not support specifying the completion style, so you'll also have to make sure zsh loads the official completion. On macOS, if using the Xcode Developer Tools version of git, you can link it into /usr/local/share/zsh/site-functions like so:

sudo mkdir -p /usr/local/share/zsh/site-functions
sudo ln -s /Applications/Xcode.app/Contents/Developer/usr/share/git-core/git-completion.zsh \
  /usr/local/share/zsh/site-functions/_git

And then adding the following to .zshrc, because git-completion.zsh relies on git-completion.bash.

# ~/.zshrc
# you may already have this line
autoload -Uz compinit && compinit

zstyle ':completion:*:*:git:*' script /Applications/Xcode.app/Contents/Developer/usr/share/git-core/git-completion.bash

Credit for original idea goes to this reddit thread.

联系我们 contact @ memedata.com