update : 0001-01-01
2020-05-10 / syui

rust

rustで作るcli toolに入門してみる

前からrustでcli toolを作ってみようかなと思っていたので作ってみました。

こちらの記事がわかりやすすぎた。

https://qiita.com/watawuwu/items/b20abfae62f76e4b4c0c

rustでコードを書くところから、toolのテストやmakefileでの自動化、ciでbuildしてtoolを配布するところまで、おおよそ必要な情報すべてが解説されています。

rustで作ったcli tool(そのまんま) :

https://github.com/syui/udrs

travis-ciでgithub-releasesにupload

$ sudo gem i travis
$ travis login
$ travis encrypt $GITHUB_ACCESS_TOKEN

$ cat .travis.yml
deploy:
  api_key:
    secure: "xxx"

makefileでtaskの自動化

LOG_LEVEL := debug
APP_ARGS  := "foo%20bar"
export RUST_LOG=url=$(LOG_LEVEL)
PREFIX := $(HOME)/.cargo

run:
	cargo run $(APP_ARGS)

test:
	cargo test

check:
	cargo check $(OPTION)

install:
	cargo install --force --root $(PREFIX) --path .
$ make test

base64のencodeを追加してみることにしました。cliはseahorseがおすすめです。

https://qiita.com/KeisukeToyota/items/996a09b10c462ee94cc8

base64 = "0.9.2"
seahorse = "0.6.2"
use std::env;
use seahorse::{App, Command, Context};

fn main() {
    let args: Vec<String> = env::args().collect();
    let app = App::new()
        .name(env!("CARGO_PKG_NAME"))
        .author(env!("CARGO_PKG_AUTHORS"))
        .version(env!("CARGO_PKG_VERSION"))
        .usage("cli_tool [command] [x] [y]")
        .command(
            Command::new()
                .name("b64")
                .usage("cli b64 {}")
                .action(b64),
        );
    app.run(args);
}

fn b64(c: &Context) {
    let b64 = base64::encode(&c.args[0]);
    println!("{}", b64);
}
$ udrs b64 "hello"