spiegel-im-spiegel/gocli v0.9.1 をリリースした
CLI で使える細々した機能を詰め合わせた自作パッケージ spiegel-im-spiegel/gocli の v0.9.1 をリリースした。
対話モードで動かしたいツールがあって,それ用に使えるサブパッケージ gocli
/prompt
を追加してみた。
こんな感じに書ける。
package main
import (
"fmt"
"os"
"github.com/spiegel-im-spiegel/gocli/prompt"
"github.com/spiegel-im-spiegel/gocli/rwi"
)
func main() {
p := prompt.New(
rwi.New(
rwi.WithReader(os.Stdin),
rwi.WithWriter(os.Stdout),
),
func(s string) (string, error) {
if s == "q" || s == "quit" {
return "quit prompt", prompt.ErrTerminate
}
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
return string(runes), nil
},
prompt.WithPromptString("Sample> "),
prompt.WithHeaderMessage("Input 'q' or 'quit' to stop"),
)
if !p.IsTerminal() {
fmt.Fprintln(os.Stderr, "not terminal (or pipe?)")
return
}
if err := p.Run(); err != nil {
fmt.Fprintln(os.Stderr, err)
}
}
このコードでは入力した文字列を逆順に並べ替えて出力する。
“q
” または “quit
” を入力するとプログラムを終了する。
これを動かすとこんな感じ。
$ go run prompt/sample/sample.go
Input 'q' or 'quit' to stop
Sample> abcdef
fedcba
Sample> quit
quit prompt
ちなみに github.com/atotto/clipboard と組み合わせて
package main
import (
"fmt"
"os"
"github.com/atotto/clipboard"
"github.com/spiegel-im-spiegel/gocli/prompt"
"github.com/spiegel-im-spiegel/gocli/rwi"
)
func main() {
p := prompt.New(
rwi.New(
rwi.WithReader(os.Stdin),
rwi.WithWriter(os.Stdout),
),
func(s string) (string, error) {
if s == "q" || s == "quit" {
return "quit prompt", prompt.ErrTerminate
}
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
res := string(runes)
return res, clipboard.WriteAll(res)
},
prompt.WithPromptString("Sample> "),
prompt.WithHeaderMessage("Input 'q' or 'quit' to stop"),
)
if !p.IsTerminal() {
fmt.Fprintln(os.Stderr, "not terminal (or pipe?)")
return
}
if err := p.Run(); err != nil {
fmt.Fprintln(os.Stderr, err)
}
}
とか書けば標準出力への出力と同時にクリップボードにも出力される。
spiegel-im-spiegel/gocli パッケージは CLI を組む際に(主に自分が)便利な細々とした機能を収録している。 他の人には使いにくいかもしれないし大した内容でもないため CC0 で公開している。 一切の権利を放棄しているので自由に持っていって弄っていただいて構わない。
参考図書
- プログラミング言語Go
- アラン・ドノバン (著), ブライアン・カーニハン (著), 柴田芳樹 (著)
- 丸善出版 2016-06-20 (Release 2021-07-13)
- Kindle版
- B099928SJD (ASIN)
- 評価
Kindle 版出た! 一部内容が古びてしまったが,この本は Go 言語の教科書と言ってもいいだろう。感想はこちら。