gitで最近コミットしたブランチを探す
gitを使った開発で複数のブランチが平行で走っていて、チェックアウトしようとしたときに「アレ名前なんだっけ」と忘れることがよくある。 適当なブランチ名をつけているわけではないんだけど。ちなみにブランチ名はこんな感じでつけてる。
たとえば、feature/1234/optimize-top-page
最近コミットしたブランチの一覧
git for-each-refを使えば良いことが分かった。
git for-each-ref --count=10 --sort=-committerdate refs/heads/ --format='%(authordate:iso8601) %(refname:short)'
上の例だと、
- ローカルのリポジトリを
- 最近のコミット順に
- フォーマットは、
iso8601形式の日時 短いブランチ名
で - 10件取得する
という意味。
git for-each-refのドキュメントを見ると、フォーマットには%(subject)
や%(authorname)
なども指定できるみたいなので、いろいろできそう。
.gitconfigにaliasとして追加した
[alias] mru = for-each-ref --format='%(refname:short) (%(authordate:relative))' --sort=-committerdate refs/heads/
便利。
pecoのsourceにした
hagiyatさんのzshrcからそのままコピーさせていただきました。
#!/bin/zsh function peco-git-branches () { # exists? .git/ git rev-parse --git-dir >/dev/null 2>&1 if [[ $? == 0 ]]; then local selected="$(git for-each-ref --format="%(refname) (%(authordate:relative))" --sort=-committerdate refs/heads/ refs/remotes/ refs/tags/ | sed -e "s/^refs\///g" | peco --query "$LBUFFER" --prompt "[GIT BRANCH] >")" if [ -n "$selected" ]; then local branch_type=${selected%%/*} local branch_name=${selected[(w)1]#(heads|remotes|tags)/} case "$branch_type" in "heads"|"tags") BUFFER="git checkout $branch_name" zle accept-line ;; "remotes") BUFFER="git checkout -t $branch_name" zle accept-line ;; esac fi fi zle redisplay } zle -N peco-git-branches
かなり便利。
bashやzshで文字列操作する方法いろいろ
tim.vanwerkhoven.org とても勉強になった。すぐsedとかしたくなっちゃうので。