【问题标题】:Shortened path relative to git repository in terminal prompt with zsh使用 zsh 在终端提示符中缩短相对于 git 存储库的路径
【发布时间】:2022-12-16 04:29:11
【问题描述】:

目标

我正在尝试为我的终端提示创建一个相对于我所在的存储库的缩短路径。类似于我已经拥有的根目录和主目录,如下所示。

以下终端提示路径中显示的最后一个目录始终是当前工作目录。
根:

/ %
/rootDir %
/rootDir/dir1/dir2 %
/rootDir/.../dir2/dir3 %
/rootDir/.../dir3/dir4 %

家:

~ %
~/dir1/dir2 %
~/.../dir2/dir3 %
~/.../dir3/dir4 %

当我在存储库中时,我正试图找到一种方法让它以相同的方式工作。其中存储库是“根”而不是实际的根或主页是路径的“根”。
存储库:

|repo %
|repo/dir1/dir2 %
|repo/.../dir2/dir3 %
|repo/.../dir3/dir4 %

我做了什么

我的 .zshrc 代码:

autoload -Uz vcs_info
zstyle ':vcs_info:git:*' formats '|%r'
zstyle ':vcs_info:git:*' check-for-changes true

setopt PROMPT_SUBST

precmd()
{
    vcs_info
    if [ -d .git ];
    then
        PROMPT='${vcs_info_msg_0_}'
    elif $(git rev-parse > /dev/null 2>&1);
    then
        PROMPT='${vcs_info_msg_0_}/%c'
    else
        PROMPT='%(4~|%-1~/.../%2~|%3~)'
    fi

    PROMPT+=' %# '
}

在根目录或主目录中的路径解决方案非常简单:

PROMPT='%(4~|%-1~/.../%2~|%3~)'

这将检查从工作目录到最近的目录(根目录或主目录)的路径长度,并根据相对路径的目录长度显示两个不同路径之一。

但是,我想不出一种方法来为存储库修改它。正如我现在所拥有的那样,它使用 if..else 检查我的工作目录是否是回购协议的“根目录”,或者我是否在回购协议的内部。并使用这些来显示回购的名称或名称和当前工作目录。为了让它像根目录和主目录一样工作,但是我需要在 repo 和工作目录之间有当前长度或者我可能错过的一些其他更简单的解决方案。

【问题讨论】:

    标签: git path repository zsh prompt


    【解决方案1】:

    终于又绕过了这个。我最终制定了一个符合预期的解决方案:

    autoload -Uz vcs_info
    zstyle ':vcs_info:git:*' formats '|%r'
    zstyle ':vcs_info:git:*' check-for-changes true
    
    setopt PROMPT_SUBST
    
    precmd()
    {
        vcs_info
    
    # in git repo
        if [[ -n $(git rev-parse --git-dir 2> /dev/null) ]]; then
    
        # in root of git repo
            if [ -d .git ];
            then
                PROMPT='${vcs_info_msg_0_}'
    
        # in first subfolder of git repo
            elif [ -d ../.git ];
            then
                PROMPT='${vcs_info_msg_0_}/%c'
    
        # in second subfolder of git repo
            elif [ -d ../../.git ];
            then
                PROMPT='${vcs_info_msg_0_}/%2c'
    
        # in deeper subfolder of git repo
            else
                PROMPT='${vcs_info_msg_0_}/.../%2c'
            fi
    
    # not in git repo
        else
            PROMPT='%(4~|%-1~/.../%2~|%3~)'
        fi
    
        PROMPT+=' %# '
    }
    

    不是最优雅的黑客,但不是很熟悉这就是我想出的语法。

    现在该函数检查工作目录与在每个 git 存储库根目录下找到的 .git 文件的相对位置。为了减少函数完成的检查量,它首先有一个 if 语句来检查当前目录是否在 git 存储库内的任何地方。如果不是,则改用原始帖子中针对主路径和根路径的先前解决方案。

    【讨论】:

      猜你喜欢
      • 2016-09-14
      • 2016-05-30
      • 2013-08-25
      • 2015-07-31
      • 1970-01-01
      • 2021-01-13
      • 2018-05-12
      • 1970-01-01
      • 2014-06-27
      相关资源
      最近更新 更多