加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Bash完成:在别名完成中荣誉资源库特定的Git别名

发布时间:2020-12-15 09:17:04 所属栏目:安全 来源:网络整理
导读:说bash配置了以下别名: alias up =“git –git-dir /path/to/backup/.git” 而那个特定的仓库 – 只有那个仓库 – 有下面的git别名: [alias]backup = commit --allow-empty-message 如何可以自动完成备份? 这会自动完成备份,但不会完成: cd /a/differen
说bash配置了以下别名:

alias up =“git –git-dir /path/to/backup/.git”

而那个特定的仓库 – 只有那个仓库 – 有下面的git别名:

[alias]
backup = commit --allow-empty-message

如何可以自动完成备份?

这会自动完成备份,但不会完成:

cd /a/different/dir
git --git-dir=/path/to/backup/.git ba

这自动完成与标准git命令,但不备份:

complete -o bashdefault -o default -o nospace -F __git_wrap__git_main up

编辑:Etan是对的,完成函数需要看到展开的别名,所以我创建了以下:

CompletableAlias() {
    if (($#<2)); then
        return 1
    fi
    source_c="$1"
    target_c="$2"
    target_a=( "${@:2}" )
    target_s="${target_a[*]}"
    alias "${source_c}=${target_s}"
    completion_modifier="__${source_c}_completion"
    completion_original="$( complete -p "$target_c" 2>/dev/null |
                            sed 's/.*-FW+(w+).*/1/'
                          )"
    if [[ -n "$completion_original" ]]; then
        read -r -d '' completion_function <<-EOF
        function $completion_modifier() {
            COMP_LINE="${COMP_LINE/#${source_c}/${target_s}}"
            ((COMP_POINT+=${#target_s}-${#source_c}))
            ((COMP_CWORD+=${#target_a[@]}-1))
            COMP_WORDS=( ${target_a[@]} ${COMP_WORDS[@]:1} )
            $completion_original
        }
EOF
        eval "$completion_function"
        completion_command="$( complete -p "$target_c" |
                               sed "s/${completion_original}/${completion_modifier}/;
                                    s/w+$/${source_c}/"
                             )"
        $completion_command
    fi
}


source "/usr/share/bash-completion/completions/git"

CompletableAlias "up" "git" "--git-dir" "/path/to/backup/.git"

但有不可思议的问题:

> up bac< Tab>不工作
> up< Tab>使用默认完成,不列出git子命令
>和更多…

编辑2:更新脚本以修复上述问题使用在Re: Bash completion of aliased commands的建议。显然这是一个很常见的任务。但现在我遇到这个错误消息:

$ cd /a/different/dir
$ up backup<Tab> fatal: Not a git repository (or any of the parent directories): .git
你不应该在这种复杂的情况下真正使用别名,使用 bash functions.别名更像是C中的预处理器(在使用意义上),当函数更像…代码函数。我发现他们也更“自动完成”。

你也可以看看这个问题是如何解决在其他shell,如fish。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读