git aliasで外部コマンドを呼び出して便利にしてみる
株式会社日立製作所の白井明です。
git aliasで、git以外の外部コマンドも呼び出して作業を効率化する方法を説明します。
git aliasについて
Qiitaの中にもたくさんgit aliasの記事があります。
- 【git】aliasの設定方法 - Qiita
- gitで便利なエイリアス達 - Qiita
- よく使うgitコマンドのエイリアスを設定して開発効率をアップする - Qiita
- gitで登録したaliasコマンド一の覧や内容をイイ感じに確認できるようにしてみた - Qiita
複雑なオプションを簡単に指定する使い方は上記でいろいろと出ているので、この記事では自分が使っているもので、単純な短縮でなく外部コマンドを呼び出しているものを紹介します。
環境
Windowsで作業していますが、Cygwinと組み合わせてUNIXっぽく使っています。LinuxやMacでも外部コマンドの引数が違う一部ケースを除き使えます。
% git --version
git version 2.19.1.windows.1
.gitconfigの設定例
[alias]
alias = !git config --get-regexp 'alias\\.' | sed 's/alias\\.\\([^ ]*\\) \\(.*\\)/\\1\\\t => \\2/' | sort
clean-local-branches = !git branch --merged | grep -v \\* | xargs --no-run-if-empty git branch -d
t = !git for-each-ref --sort=taggerdate --format='%(taggerdate:short) %(tag) %(subject)' refs/tags | nkf -Lw
設定の意味を以下で解説します。
外部コマンドの呼び出し方
aliasを!で書き始めると、外部コマンド呼び出しになります。
However, maybe you want to run an external command, rather than a Git subcommand. In that case, you start the command with a
!character.
alias: alias一覧を表示する
シェルでaliasと打つとaliasの一覧が見られる感じで、git aliasでgitのaliasの一覧が見られるようにしています。git configでalias.で始まる設定値を見るだけでも大体分かるのですが、sedで好みの形に加工しています。
% git alias
alias => !git config --get-regexp 'alias\.' | sed 's/alias\.\([^ ]*\) \(.*\)/\1\ => \2/' | sort
clean-local-branches => !git branch --merged | grep -v \* | xargs --no-run-if-empty git branch -d
t => !git for-each-ref --sort=taggerdate --format='%(taggerdate:short) %(tag) %(subject)' refs/tags | nkf -Lw
clean-local-branches: マージ済みのローカルブランチを削除する
git branch --mergedの出力を、grepで加工して、xargsでまとめて削除しています。
% git clean-local-branches
Deleted branch merged-branch (was 0e4aa0390).
MacOSのxargsは--no-run-if-emptyオプションをサポートしていない(デフォルトで指定した時と同じ動作)ので、削除する必要があります。
t: タグを付けた順に一覧する
git for-each-refでタグを一覧出力する方法はいろいろあるのですが、改行コードの問題でWindows上だと表示が崩れることがあったので、nkfで改行コードをCRLFに加工しています。
チームでタグを付ける頻度が高い開発の仕方をしていて、他のメンバの更新の概要把握のためによく使うので短い"t"にしています。名前付けはお好みで。
% git t
2018-11-25 version/100 Fix some bugs
and minor improvement.
2018-11-30 version/101 Support new feature.
まとめ
git aliasで!を使うと外部コマンド呼び出しができるので、設定の幅が広がります。設定例をいくつかご紹介しました。