LoginSignup
7
6

More than 5 years have passed since last update.

scoptでコマンドラインオプションを解析

Last updated at Posted at 2014-02-13

パターンマッチで解析でもある程度事足りるけど、ライブラリを使ってみることに。
scallopでは、util-evalと併用したらEvalでexceptionが発生したので※、scoptを使うことにした。

※exception
java.lang.NoSuchMethodException scala.reflect.internal.TreeInfo.firstArgument

解析結果を保持するcase classを用意する

コマンドラインで期間指定したい時。指定なしは前日とする。

caseclass
case class CommandLineArgs(
  from: DateTime = DateTime.now.minusDays(1),
  to: DateTime = DateTime.now.minusDays(1))

parserを作る

文字列をorg.joda.time.DateTimeに変換する。

parser
   val parser = new scopt.OptionParser[CommandLineArgs]("your program name") {
      val dtf = DateTimeFormat.forPattern("yyyyMMdd")
      opt[String]('f', "from") action { (x, c) =>
        c.copy(from = DateTime.parse(x, dtf))
      } text ("from is date")

      opt[String]('t', "to") action { (x, c) =>
        c.copy(to = DateTime.parse(x, dtf))
      } text ("to is date")

      help("help") text("print this usage text.")
    }

parse

Option[CommandLineArgs]が返ってくる。

parse
parser.parse(args, CommandLineArgs())
7
6
1

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
7
6