Who?
twitter: @carimatics
気持ちよくエンジニアリングができる環境を作りたい
という気持ちを抱いて早幾星霜
仕事ではこんなのよく触ってる
- Shell script
- Perl
- Python
- JavaScript
- AWS
- Docker
今日のお話
CLI
つくる
CLI
Command Line Interface
行ごとにコマンドを実行するためのツールです(雑)
もっと雑に言うとmacOSのterminal、もしくはWindowsのcmdです
何でCLIツール作るのです?
shell script書きたくなさが臨界点を超えて爆発した
Pythonとかでもよかったんだけど何事も挑戦なので...
使うライブラリ
urfave/cli
- 
flag(オプション)のパースが簡単にできる
- 
subcommandsを作るのも簡単- 
gitコマンドのaddとかcommitとか
 
- 
- 
Usageを記述すればいい感じのヘルプも作ってくれるのでマニュアルが腐りにくい
簡単なコマンドを作る
みんな大好き
カウンター!
動作はこんな感じ(雑)
ディレクトリ構成
mycmd
├── Gopkg.lock   # 依存関係
├── Gopkg.toml   # プロジェクトの設定
├── count.txt    # ストレージ(雑)
├── main.go      # entry point
├── modules      # 今回作ったコマンド処理本体
│   └── commands
│       └── counter
│           └── counter_command.go
└── vendor       # 外部ライブラリ
    └── github.com
        └── urfave
            └── cli
やること
これだけ!
- Application設定
- Command登録
- Action登録
- SubCommand登録
Application設定
app := cli.NewApp()
app.Name    = "mycmd"
app.Usage   = "The sample application"
app.Version = "0.0.1"
Command登録
今回はcounterコマンドを追加する
app.Commands = []cli.Command{
	counter.CounterCommand(count),
}
コマンド叩いたときに以下のように表示される
$ mycmd 
NAME:
   mycmd - The sample application
USAGE:
   mycmd [global options] command [command options] [arguments...]
VERSION:
   0.0.1
COMMANDS:
     counter  Execute count up/down
     help, h  Shows a list of commands or help for one command
GLOBAL OPTIONS:
   --help, -h     show help
   --version, -v  print the version
Action登録
CounterCommand
cli.Command{
	Name:  "counter",
	Usage: "Execute count up/down",
	Action: func(context *cli.Context) error {
		printCurrentCount(count)
		return nil
	},
	Subcommands: []cli.Command{
		upCommand(count),
		downCommand(count),
	},
}
コマンド叩くと
$ mycnt counter
current count: 0
SubCommand登録
down
cli.Command{
	Name:  "down",
	Usage: "Down count",
	Action: func(context *cli.Context) error {
		count--
		printCurrentCount(count)
		saveCount(count)
		return nil
	},
}
コマンドを叩くと
$ mycnt counter
current count: -1
まとめ
CLIツール簡単に作れる〜!
みんなはもっと有益なコマンド作ろう!

