はじめに
powerlevel10kでブランチ名を表示する際、表示箇所が足りない場合にブランチ名の中央が省略されてしまいます。
例
feature/battle/sprint3/backend
↓
feature/.../backend
自分のプロジェクトのブランチ名規則では、ブランチ名のスラッシュ区切りの最後2つの部分が大事なので、最後の2つ以外の部分は2文字に省略する(1文字だと意味がよくわからないため)ようにしたいと思いました。
例
feature/battle/sprint3/backend
↓
fe/ba/sprint3/backend
環境
項目 | バージョン |
---|---|
OS | Mac OS X Ventura 13.4.1 |
zsh | zsh 5.9 (x86_64-apple-darwin22.1.0) |
powerlevel10k | 1.17.0 |
実装
powerlevel10kの設定ファイルである.p10k.zshを編集します。
まず、my_git_formatter
関数の前に以下の関数を定義します
# スラッシュ区切りの最後から2つ目以外の部分を2文字に短縮する
function shorten_branch_name {
# 引数を/で分割
array=("${(s:/:)1}")
result=""
for ((i = 1; i <= ${#array[@]} - 1; i++)); do
# 最後から2つ目以前
if [[ i -le (${#array[@]}-2) ]] then
# 初めの2文字だけ
result="${result}${array[i]:0:2}/"
else
# 最後から2つ目はそのまま
result="${result}${array[i]}/"
fi
done
# 最後の1つもそのまま
result="${result}${array[-1]}"
echo $result
}
my_git_formatter
関数の以下の部分を編集します。
これでローカルブランチの表示が省略されます。
if [[ -n $VCS_STATUS_LOCAL_BRANCH ]]; then
local branch=${(V)VCS_STATUS_LOCAL_BRANCH}
# ここでブランチ名の省略をする
branch=`shorten_branch_name $branch`
# If local branch name is at most 32 characters long, show it in full.
# Otherwise show the first 12 … the last 12.
# Tip: To always show local branch name in full without truncation, delete the next line.
(( $#branch > 32 )) && branch[13,-13]="…" # <-- this line
res+="${clean}${(g::)POWERLEVEL9K_VCS_BRANCH_ICON}${branch//\%/%%}"
fi
タグも省略するようにします。
if [[ -n $VCS_STATUS_TAG
# Show tag only if not on a branch.
# Tip: To always show tag, delete the next line.
&& -z $VCS_STATUS_LOCAL_BRANCH # <-- this line
]]; then
local tag=${(V)VCS_STATUS_TAG}
# ここでタグ名の省略をする
tag=`shorten_branch_name $tag`
# If tag name is at most 32 characters long, show it in full.
# Otherwise show the first 12 … the last 12.
# Tip: To always show tag name in full without truncation, delete the next line.
(( $#tag > 32 )) && tag[13,-13]="…" # <-- this line
res+="${meta}#${clean}${tag//\%/%%}"
fi
リモートブランチも省略します。
# Show tracking branch name if it differs from local branch.
if [[ -n ${VCS_STATUS_REMOTE_BRANCH:#$VCS_STATUS_LOCAL_BRANCH} ]]; then
local remote_branch=${(V)VCS_STATUS_REMOTE_BRANCH}
# ここでブランチ名の省略をする
remote_branch=`shorten_branch_name $remote_branch`
res+="${meta}:${clean}${remote_branch//\%/%%}"
fi
これで読み込み直せば完成です!
source .p10k.zsh
完成図
期待通りの表示になりました!
終わりに
shorten_branch_name
を編集すれば文字数や省略する箇所のカスタマイズもできます。