LoginSignup
1
4

More than 5 years have passed since last update.

scoptって何?

Last updated at Posted at 2017-07-09

scoptとは

"scopt is a little command line options parsing library."

パーサーライブラリらしいです。

パーサーって?

"一定の文法に従って記述された複雑な構造のテキスト文書を解析し、プログラムで扱えるようなデータ構造の集合体に変換するプログラムのこと"

( ,,`・ω・´)ンンン?
最初これ読んでよくわかんなかったんで、コード書いて理解してみました。

コード

参考というかそのまま
http://qiita.com/yoheihonda/items/7d6bdedfe0df36d11da8

githubにサンプルコード作りました。
https://github.com/kazuogawa/samplescopt
intellijのsbtでプロジェクト作成

build.sbt
name := "samplescopt"

version := "1.0"

scalaVersion := "2.12.1"

libraryDependencies ++= Seq(
  "com.github.scopt" %% "scopt" % "3.6.0",
  "joda-time" % "joda-time" % "2.9.9"

)
samplescopt.scala
import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat

object samplescopt {
  case class CommandLineArgs(
    //引数が設定されていなかった場合は現在時間の1日前を入れるみたいです
    from: DateTime = DateTime.now.minusDays(1),
    to: DateTime = DateTime.now.minusDays(1))
  def main(args: Array[String]): Unit = {
    //scopt.OptionParserにcase classの型を入れるみたいです。そのあとにパーサーの名前を入れるみたいです
    val parser = new scopt.OptionParser[CommandLineArgs]("your program name") {
      //--helpしたときに表示されるやつ?
      head("scopt", "3.6.0")

      val dtf = DateTimeFormat.forPattern("yyyyMMdd")
      //引数で設定する「-ほげほげ 値」またはの部分を作っているみたいですね
      //値の部分はcase classで設定した値を指定すればいいみたいですね
      //xには値が、cにはcase classに設定した型にパースされた値が入っているみたいです
      opt[String]('f', "from") action { (x, c) =>
        //println("x = "+ x)
        //println("c = "+ c)
        c.copy(from = DateTime.parse(x, dtf))
        //--helpを使った場合のメッセージが書かれるみたいです
      } text ("from is date")

      //上と同じようにしましょう
      opt[String]('t', "to") action { (x, c) =>
        c.copy(to = DateTime.parse(x, dtf))
      } text ("to is date")

      //--helpを出す場合に書くみたいですね
      help("help") text("print this usage text.")
    }
    println(parser.parse(args, CommandLineArgs()))
  }
}

sbtを実行

>sbt "run-main samplescopt -f 20170509 -t 20170709"
Some(CommandLineArgs(2017-05-09T00:00:00.000+09:00,2017-07-09T00:00:00.000+09:00))

>sbt "run-main samplescopt --from 20170509 --to 20170709"
Some(CommandLineArgs(2017-05-09T00:00:00.000+09:00,2017-07-09T00:00:00.000+09:00))

>sbt "run-main samplescopt --help"
scopt 3.6.0
Usage: your program name [options]

  -f, --from <value>  from is date
  -t, --to <value>    to is date
  --help              print this usage text.

要するに

case class で扱いやすいように渡された値をごにょごにょしてくれるものですね。

他に参考:
http://d.hatena.ne.jp/Kazuhira/20140115/1389801398
https://stackoverflow.com/questions/2315912/best-way-to-parse-command-line-parameters

1
4
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
1
4