$shibayu36->blog;

クラスター株式会社のソフトウェアエンジニアです。エンジニアリングや読書などについて書いています。

pecoで最近更新されたブランチにcheckoutする

昔、最近commitされたブランチをanythingライクに絞り込んでcheckoutする、というものをzawの時もpercolの時も実装していた。

最近はpecoを使うようになったので、ほぼコピペで再実装した。

設定方法

git-recent-branches.zshのようなファイルを用意し、peco-git-recent-branchesとpeco-git-recent-all-branchesを実装する。

function peco-git-recent-branches () {
    local selected_branch=$(git for-each-ref --format='%(refname)' --sort=-committerdate refs/heads | \
        perl -pne 's{^refs/heads/}{}' | \
        peco)
    if [ -n "$selected_branch" ]; then
        BUFFER="git checkout ${selected_branch}"
        zle accept-line
    fi
    zle clear-screen
}
zle -N peco-git-recent-branches

function peco-git-recent-all-branches () {
    local selected_branch=$(git for-each-ref --format='%(refname)' --sort=-committerdate refs/heads refs/remotes | \
        perl -pne 's{^refs/(heads|remotes)/}{}' | \
        peco)
    if [ -n "$selected_branch" ]; then
        BUFFER="git checkout -t ${selected_branch}"
        zle accept-line
    fi
    zle clear-screen
}
zle -N peco-git-recent-all-branches

.zshrc上で、keybindを設定する。

bindkey '^x^b' peco-git-recent-branches
bindkey '^xb' peco-git-recent-all-branches

これだけで使える。

デモ

こんなかんじで最近commitされた順でブランチが並び、pecoで更に絞り込んでcheckoutできる。使ってみないと良さはわからないけど、結構ライフチェンジング感あるのでおすすめ。
f:id:shiba_yu36:20140726150359g:plain

Tips

ちなみに昔書いたけど、更新した順でbranchのリストを取得するには、git for-each-refを使ったら出来る。他にもいろいろできそう。

ローカルブランチを更新した順に取得

git for-each-ref --format='%(refname:short)' --sort=-committerdate refs/heads

リモートブランチも一緒に取得

git for-each-ref --format='%(refname:short)' --sort=-committerdate refs/heads refs/remotes

まとめ

とにかく便利なのを何度も紹介したいので、pecoが出たタイミングでもう一度紹介しました。