LoginSignup
13
10

More than 5 years have passed since last update.

aliasにできないならsub-commandにすれば良い

Posted at

私事だが、git statusgit sta†usとtypoしてしまうことが稀によくある。
typoしないように治すことは大変そうなので、git sta†usgit statusの動作をするようにしてしまおうと思った。

Gitのalias

Gitにはコマンドのエイリアスを設定することができる。
(詳しくはこちらを参照)
例えば

example-to-set-alias
$ git config --global alias.st status

と設定しておくと

git-st-output
$ git st
On branch master
nothing to commit, working directory clean

というように、git stgit statusの動作をするようになる。

git configの文字制限

では、冒頭に書いた問題は、git sta†usgit 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 というスクリプトを作成した。

git-sta†us
#!/bin/sh
git status $@

実行してみると

result-output
$ 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-filesgit sl-files とtypoした際に、slが走らないことを寂しいと感じている人は多いと思う。
そこで、git-sl-files というサブコマンドを作ってみた。

作成したスクリプト

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

動作説明

flow-chart
+-----------------------+
|    Does sl exist?     | -+
+-----------------------+  |
  |                        |
  | no                     |
  v                        |
+-----------------------+  |
| Clone sl from Github. |  |
+-----------------------+  |
  |                        |
  |                        | yes
  v                        |
+-----------------------+  |
|      Compile sl.      |  |
+-----------------------+  |
  |                        |
  |                        |
  v                        |
+-----------------------+  |
|        Run sl.        | <+
+-----------------------+

slがインストールされている場合は、そのslを起動。
インストールされていない場合はGithubからソースコードを取得し、コンパイルした後、実行する。

13
10
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
13
10