0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【zsh】ターミナルでgitのブランチ補完方法

Posted at

最終的なゴール(ターミナル)

通常時

~ %

ghqモード時

github.com/ユーザー名 %

例)github.com/ユーザー名/ディレクトリ/アプリ(main *)
→ * が付いている時は差分がある状態

手順

ghqのインストール

brew install ghq

ghqで管理するrootディレクトリを~/srcに設定

ここはお好みで命名などをつけてください。今回はsrcとします。

git config --global ghq.root '~/src'

zshを作る

mkdir ~/.zsh

zshディレクトリに移動

cd ~/.zsh

zshディレクトリ内で以下3つのコマンドを実行

curl -o git-prompt.sh https://raw.githubusercontent.com/git/git/master/contrib/completion/git-prompt.sh
curl -o git-completion.bash https://raw.githubusercontent.com/git/git/master/contrib/completion/git-completion.bash
curl -o _git https://raw.githubusercontent.com/git/git/master/contrib/completion/git-completion.zsh

.zshrc に以下の設定を追記

.zshrc
# git-promptの読み込み
source ~/.zsh/git-prompt.sh


# git-completionの読み込み
fpath=(~/.zsh $fpath)
zstyle ':completion:*:*:git:*' script ~/.zsh/git-completion.bash
autoload -Uz compinit && compinit


# プロンプトのオプション表示設定
GIT_PS1_SHOWDIRTYSTATE=true
GIT_PS1_SHOWUNTRACKEDFILES=true
GIT_PS1_SHOWSTASHSTATE=true
GIT_PS1_SHOWUPSTREAM=auto

# プロンプトの表示設定(1行表示・ユーザー名/ホスト名なし)
setopt PROMPT_SUBST

# プロンプト設定関数
function set_prompt() {
  if [[ -n "$IN_GHQ" ]]; then
    # github.com 以降のパスだけを取り出す
    local rel_path="${PWD##*/src/}"
    PS1="%F{cyan}${rel_path}%f %F{red}$(__git_ps1 '(%s)')%f %% "
  else
    PS1='%F{cyan}%~%f %F{red}$(__git_ps1 "(%s)")%f %% '
  fi
}

# 毎回プロンプト更新
autoload -Uz add-zsh-hook
add-zsh-hook precmd set_prompt

# peco + ghq ウィジェット
function peco-src () {
  local selected_dir="$(ghq list -p | peco --prompt='repositories >' --query "$LBUFFER")"
  if [ -n "$selected_dir" ]; then
    cd "$selected_dir"
    export IN_GHQ=1
  else
    unset IN_GHQ
  fi
  zle reset-prompt
}
zle -N peco-src
bindkey '^G' peco-src

# Git 情報取得(vcs_infoは未使用)
autoload -Uz vcs_info
zstyle ':vcs_info:*' enable git
zstyle ':vcs_info:git:*' check-for-changes true
zstyle ':vcs_info:git:*' stagedstr '+'
zstyle ':vcs_info:git:*' unstagedstr '*'
zstyle ':vcs_info:git:*' formats '(%b)'
zstyle ':vcs_info:git:*' actionformats '(%b %F{red}*%f)'

# iTerm2用
test -e "${HOME}/.iterm2_shell_integration.zsh" && source "${HOME}/.iterm2_shell_integration.zsh"

※通常のターミナルを使用している方は# iTerm2用の記述は不要です。

設定を保存する

source ~/.zshrc

一度ターミナルを落とす

ターミナル再起動後「ctl」+「g」のコマンドを実行してください。
もしここで何も表示されない場合は適当にgithubからアプリをクローンします。

#HTTPSの場合
ghq get https://github.com/hoge/hoge.git

#SSHの場合
ghq get git@github.com:hoge/hoge.git

これでもう一度「ctl」+「g」コマンドを実行してください。
アプリを選択できるようになっていればOKです!

お疲れ様でした✨️

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?