package com.trueaccord.scalapb

import protocbridge.ProtocBridge

import scalapb.ScalaPbCodeGenerator

object ScalaPBC {
  def main(args: Array[String]): Unit = {
    val (versionFlag, protocArgs) =
      if (args.length >= 1 && args(0).startsWith("-v")) {
        (args.head, args.tail)
      } else {
        ("-v300", args)
      }

    val code = ProtocBridge.runWithGenerators(
      a => com.github.os72.protocjar.Protoc.runProtoc(versionFlag +: a.toArray),
      protocArgs,
      Seq("scala" -> ScalaPbCodeGenerator))

    sys.exit(code)
  }
}

package com.trueaccord.scalapb

import protocbridge.ProtocBridge

import scalapb.ScalaPbCodeGenerator

case class Config(
  version: String = "-v300",
  throwException: Boolean = false,
  args: Seq[String] = Seq.empty)

class ScalaPbcException(msg: String) extends RuntimeException(msg)

object ScalaPBC {
  def processArgs(args: Array[String]): Config = {
    case class State(cfg: Config, passThrough: Boolean)

    args.foldLeft(State(Config(), false)) {
      case (state, item) =>
        (state.passThrough, item) match {
          case (false, v) if v.startsWith("-v") => state.copy(cfg = state.cfg.copy(version = v))
          case (false, "--throw") => state.copy(cfg = state.cfg.copy(throwException = true))
          case (_, other) => state.copy(
            passThrough = true, cfg=state.cfg.copy(args = state.cfg.args :+ other))
        }
    }.cfg
  }

  def main(args: Array[String]): Unit = {
    val config = processArgs(args)

    val code = ProtocBridge.runWithGenerators(
      a => com.github.os72.protocjar.Protoc.runProtoc(config.version +: a.toArray),
      config.args,
      Seq("scala" -> ScalaPbCodeGenerator))

    if (!config.throwException) {
      sys.exit(code)
    } else {
      if (code != 0) {
        throw new ScalaPbcException(s"Exit with code $code")
      }
    }
  }
}

Add --throw to throw on error instead of invoking sys.exit
Scalapbc: Add --throw to throw on error instead of invoking sys.exit

This makes ScalaPBC friendlier to tools which run it in the same JVM
like mvn.

For #162.
