Mainargs: a small, convenient, dependency-free library for command-line argument parsing in Scala

Mainargs is a small, convenient, dependency-free library for command-line argument parsing in Scala:

To get started using MainArgs, all you need is a single method annotated with @main:

package testhello
import mainargs.{main, arg, ParserForMethods, Flag}

object Main{
  @main
  def run(@arg(short = 'f', doc = "String to print repeatedly")
          foo: String,
          @arg(name = "my-num", doc = "How many times to print string")
          myNum: Int = 2,
          @arg(doc = "Example flag, can be passed without any value to become true")
          bool: Flag) = {
    println(foo * myNum + " " + bool.value)
  }
  def main(args: Array[String]): Unit = ParserForMethods(this).runOrExit(args)
}

MainArgs is the outcome of unifying Ammonite Scala Script’s user-defined @main method implementation, with Ammonite’s own argument parser, with Mill’s user-defined T.command implementation, and Mill’s own argument parser. MainArgs is thus flexible enough support a wide range of use cases, while providing a convenient and boilerplate-free experience that scales down to the smallest programs.

As MainArgs is heavily used in the latest versions of Ammonite and Mill, I expect that it is flexible enough to handle a wide range of use cases, and is solid enough for serious real-world usage. Feel free to make use of this in your own projects!

13 Likes

Very nice!
What is the future of it in Scala-3 considering its own @main annotation.

3 Likes

We will hopefully be able to merge the two. For the moment Scala-3’s @main only covers a small subset of what Mainargs can do. But the plan is to extend that.

10 Likes