Skip to content

Instantly share code, notes, and snippets.

@andreypopp
Created January 26, 2011 19:32
Show Gist options
  • Save andreypopp/797262 to your computer and use it in GitHub Desktop.
Save andreypopp/797262 to your computer and use it in GitHub Desktop.
package ru.braintrace
class OptionParser {
private val optionInfo = new mutable.ListBuffer[OptionInfo]
def addOption(option: OptionInfo) =
optionInfo.append(option)
def addOption(short: String, long: String): Unit =
addOption(OptionInfo(short, long, false))
def addFlag(short: String, long: String): Unit =
addOption(OptionInfo(short, long, true))
def parseArgs(rawArgs: Seq[String]): (Map[String, String], Seq[String]) = {
object option {
def unapply(obj: Any): Option[OptionInfo] =
(obj match {
case OptionParser.option(opt) => Some(opt)
case OptionParser.longOption(opt) => Some(opt)
case _ => None
}) flatMap { opt =>
optionInfo.find { x => x.short == opt || x.long == opt }
}
}
val (options, args) =
rawArgs.reverse.foldLeft((Map.empty[String, String], Nil: List[String])) {
(results, arg) =>
val (options, args) = results
arg match {
case option(opt) if opt.isFlag =>
(options.updated(opt.long, ""), args)
case option(opt) =>
val (x :: xs) = args
(options.updated(opt.long, x), xs)
case arg =>
(options, arg :: args)
}
}
(options, args)
}
}
object OptionParser {
private val option = """-(\w)""".r
private val longOption = """--([^-\s]\w+)""".r
}
case class OptionInfo(val short: String, val long: String, val isFlag: Boolean)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment