0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Goでシンプルなコマンドラインツールを作ってみた

Last updated at Posted at 2022-06-04

はじめに

Goを使ったWebアプリケーション開発を半年以上経験していますが、業務外ではこれまで技術本を読んだり、Udemyなどを使った学習を主にしてきました。
これまでインプットをメインに自己学習をてきたので、これからはアウトプットもしていきたいと思い、Goを使ってコマンドラインツールを作ってみました。

作成したもの

今回作成したツールは pn-checker という「引数で指定した数字が素数かどうか判定するだけのシンプルなコマンドラインツール」です。
実用性のない且つくだらないツールを作ってみたいという思いから、さらに、50%くらいの割合で Think for yourself, stupid!(自分で考えろバカ!) と言ってくる仕様にしてみました。
まあ、いわゆるクソコマンドです。

コマンド作成には以下のパッケージを使用しました。

  • spf13/cobra
    • コマンドラインツールを簡単に作成できるフレームワーク
    • すごく簡単にコマンドを作成できて便利だった。
  • fatif/color
    • カラー出力を簡単にできるパッケージ

参考程度に、開発環境(使用ツール)は以下です。

  • Mac OS (intel)
  • go version go1.17.5 darwin/amd64
  • (vs code) 別になんでも良い
  • (git) gitで管理してた方が何かと便利

実際に使ってみる

まずはヘルプから

> pn-checker -h
pn-checker checks whether the number specified is a prime number or not.
And sometimes, it says "Think for yourself, stupid!" to you.

Usage:
  pn-checker [flags] [arg(positive integer)]

Examples:
  pn-checker 997

Flags:
  -d, --diligent   seriously check if it's a prime number
  -h, --help       help for pn-checker
  -v, --version    version for pn-checker

次に、コマンドライン引数に数字を入れてみます。

(素数の場合)
> pn-checker 997
Congrats!! The number 997 is a prime number.
(素数じゃない場合)
> pn-checker 997
The number 1000 is not a prime number.

ちゃんと判定してくれました。
基本的には入力した数値が素数かどうか判定してくれますが、たまに...

(真面目に判定してくれない場合)
> pn-checker 1000

   _____ _     _       _       __
  |_   _| |__ (_)_ __ | | __  / _| ___  _ __
    | | | '_ \| | '_ \| |/ / | |_ / _ \| '__|
    | | | | | | | | | |   <  |  _| (_) | |
    |_| |_| |_|_|_| |_|_|\_\ |_|  \___/|_|
                                   _  __        _               _     _   _
   _   _  ___  _   _ _ __ ___  ___| |/ _|   ___| |_ _   _ _ __ (_) __| | | |
  | | | |/ _ \| | | | '__/ __|/ _ \ | |_   / __| __| | | | '_ \| |/ _  | | |
  | |_| | (_) | |_| | |  \__ \  __/ |  _|  \__ \ |_| |_| | |_) | | (_| | |_|
   \__, |\___/ \__,_|_|  |___/\___|_|_|( ) |___/\__|\__,_| .__/|_|\__,_| (_)
   |___/                               |/                |_|

真面目に素数かどうかチェックしてくれません。
自分で作っておいてなんですが本当に実用性に欠けるコマンドですね。

ちなみに、-dオプションをつけると毎回真面目に判定してくれるようにしていいます。(せめてもの機能)

(素数じゃない場合-dオプション)
> pn-checker -d 1000
The number 1000 is not a prime number.

まとめ

今回紹介したコマンドは git hub で公開しているので「試しに使ってみたい」という、ユニークな方は是非使ってみてください。

goが実行できる環境であれば以下コマンドで簡単にインストールできます。

> go install github.com/gracefulm/pn-checker@latest
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?