Extension OptionParser Scopt in Scala

I am trying to have a basic parameter parser with some default parameters.

In other projects, I would like to expand the parameter parser with other parameters.

Sort of:

case class Config(foo: String = null)

trait DefaultParser { self: OptionParser[Config] =>
  opt[String]('f', "foo") action { (x, c) =>
    c.copy(foo = x)
  }
}

case class MyConfig(bar: String = "hello world")

trait MyParser { self: OptionParser[MyConfig] =>
  opt[String]('b', "bar") action { (x, c) =>
    c.copy(bar = x)
  }
}

I'm new to Scala, and I'm not sure how now I can use both of them on the same thing args.

I am using Scala2.10 with scopt_2.10v3.3.0.

+4
source share
1 answer

I opened https://github.com/scopt/scopt/issues/132 .

So far, the best I've been able to come up with is combining two parsers.

case class OutputOpts(
  val outputOption: Int = 1
)

trait OptsWithOutput {
  def output: OutputOpts
}

The parser for this lives in the parent class.

def parseOutputOpts(args: Array[String]): OutputOpts = {
  val parser = new scopt.OptionParser[OutputOpts]("scopt") {
    override def errorOnUnknownArgument = false

    opt[Int]("outputOption") action { (x, c) =>
      c.copy(outputOption = x)
    } text ("some output option")
  }

  parser.parse(args, OutputOpts())
    .getOrElse(throw new Exception("Error parsing output cli args"))
}

Now you can use the child class:

case class ChildOpts(
  childThing: Int = 42,
  output: OutputOpts = OutputOpts()
) extends OptsWithOutput

.

val opts = ChildOpts(output = super.parseOutputOpts(args))

val parser = new scopt.OptionParser[ChildOpts]("scopt") {
  override def errorOnUnknownArgument = false

  opt[Int]("childThing") action { (x, c) =>
    c.copy(childThing = x)
  } text ("some child thing")
}

parser.parse(args, opts).getOrElse(throw new Exception("failed"))

, errorOnUnknownArgument false, .

+1

Source: https://habr.com/ru/post/1618156/


All Articles