私事だが、git statusをgit sta†usとtypoしてしまうことが稀によくある。
typoしないように治すことは大変そうなので、git sta†usがgit statusの動作をするようにしてしまおうと思った。
Gitのalias
Gitにはコマンドのエイリアスを設定することができる。
(詳しくはこちらを参照)
例えば
$ git config --global alias.st status
と設定しておくと
$ git st
On branch master
nothing to commit, working directory clean
というように、git stでgit statusの動作をするようになる。
git configの文字制限
では、冒頭に書いた問題は、git sta†usがgit statusの動作をするようにエイリアスの設定をすれば解決するかというと、残念ながらそうはいかない。
git configのmanページには次のような記載がある。
The variable names are case-insensitive, allow only alphanumeric characters and -, and must start with an alphabetic character.
alias(に限らず、git configで設定する変数名)はアルファベット・数字・ハイフンで構成されていなければならない。(そして変数名はアルファベットから始まる必要がある)
つまり、git sta†usというエイリアスは設定できない。
サブコマンドの設定
gitには、ユーザの作成したサブコマンドを実行する機能がある。
詳しくはこちらを参照(How to integrate new subcommands)
簡単に説明をすると、PATHの通った場所に git-hoge という実行可能ファイルを作っておけば、
$ git hoge
で、それが実行されるというもの。
サブコマンドはスクリプトでも良いし、実行可能なバイナリでも良い。
サブコマンド名に使用できる文字はファイルシステム次第。
冒頭の問題解決のために git-sta†us というスクリプトを作成した。
# !/bin/sh
git status $@
実行してみると
$ git sta†us          
error: invalid key: pager.sta†us
On branch master
Your branch is behind 'origin/master' by 357 commits, and can be fast-forwarded.
  (use "git pull" to update your local branch)
nothing to commit, working directory clean
このように、(エラーが1行表示されはするが)git statusの動作をする。
なお、git関連コマンドの一覧を表示する git help -a で、自作のサブコマンドも表示される。
alias の一覧を表示したい場合は git config --list | grep '^alias\.'
おまけ
git ls-files を git sl-files とtypoした際に、slが走らないことを寂しいと感じている人は多いと思う。
そこで、git-sl-files というサブコマンドを作ってみた。
作成したスクリプト
# !/bin/sh
which sl > /dev/null
if [ $? -eq 0 ]; then
	sl
else
	git clone https://github.com/mtoyoda/sl.git
	cd sl
	make
	./sl
fi
動作説明
+-----------------------+
|    Does sl exist?     | -+
+-----------------------+  |
  |                        |
  | no                     |
  v                        |
+-----------------------+  |
| Clone sl from Github. |  |
+-----------------------+  |
  |                        |
  |                        | yes
  v                        |
+-----------------------+  |
|      Compile sl.      |  |
+-----------------------+  |
  |                        |
  |                        |
  v                        |
+-----------------------+  |
|        Run sl.        | <+
+-----------------------+
slがインストールされている場合は、そのslを起動。
インストールされていない場合はGithubからソースコードを取得し、コンパイルした後、実行する。