如何让Git switch自动补全按LRU(最近最少使用)顺序显示分支?
实现Git自动补全按LRU(最近最少使用)顺序排序
Git默认的分支补全是按字母排序,要改成按最近使用顺序排列,需要修改Git的bash补全脚本,具体步骤如下:
1. 定位Git补全脚本位置
执行以下命令找到脚本路径:
echo "${BASH_COMPLETION_COMPAT_DIR:-/usr/share/bash-completion/completions}/git"
通常路径为/usr/share/bash-completion/completions/git(Linux系统)或/usr/local/etc/bash_completion.d/git(macOS用brew安装的情况)。
2. 备份原脚本
先备份避免修改出错:
cp /usr/share/bash-completion/completions/git ~/git-completion.bak
3. 修改分支补全逻辑
打开补全脚本,找到__git_complete_refs函数,找到其中获取分支列表并排序的代码段:
local refs refs=$(git for-each-ref --format='%(refname:short)' "$arg" | sort)
将其替换为以下LRU排序逻辑:
# 获取最近使用的分支(取最近20个,可按需调整) local recent_branches recent_branches=$(git reflog show --format='%gs' | grep -E 'checkout: moving from|checkout: to' | awk '{print $NF}' | head -20 | uniq) # 获取所有分支列表 local all_branches all_branches=$(git for-each-ref --format='%(refname:short)' "$arg") # 合并列表,去重并保留LRU顺序 local refs refs=$(echo -e "$recent_branches\n$all_branches" | awk '!seen[$0]++')
4. 生效修改
执行以下命令重新加载补全脚本,或直接重启终端:
source /usr/share/bash-completion/completions/git
针对zsh用户的补充
如果用zsh,找到git补全脚本路径(通常为/usr/share/zsh/functions/Completion/Unix/_git),找到处理分支补全的部分,替换分支列表的排序逻辑为上述的LRU逻辑即可。
内容的提问来源于stack exchange,提问作者guettli
相关产品推荐
相关产品推荐

