LoginSignup
6
1

More than 5 years have passed since last update.

git aliasで外部コマンドを呼び出して便利にしてみる

Last updated at Posted at 2018-12-11

git aliasで外部コマンドを呼び出して便利にしてみる

株式会社日立製作所の白井明です。

git aliasで、git以外の外部コマンドも呼び出して作業を効率化する方法を説明します。

git aliasについて

Qiitaの中にもたくさんgit aliasの記事があります。

複雑なオプションを簡単に指定する使い方は上記でいろいろと出ているので、この記事では自分が使っているもので、単純な短縮でなく外部コマンドを呼び出しているものを紹介します。

環境

Windowsで作業していますが、Cygwinと組み合わせてUNIXっぽく使っています。LinuxやMacでも外部コマンドの引数が違う一部ケースを除き使えます。
console
% git --version
git version 2.19.1.windows.1

.gitconfigの設定例

.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 configalias.で始まる設定値を見るだけでも大体分かるのですが、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!を使うと外部コマンド呼び出しができるので、設定の幅が広がります。設定例をいくつかご紹介しました。

6
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
6
1