{"id":13533097,"url":"https://github.com/scopt/scopt","last_synced_at":"2025-10-07T01:31:07.698Z","repository":{"id":2759426,"uuid":"3757395","full_name":"scopt/scopt","owner":"scopt","description":"command line options parsing for Scala","archived":false,"fork":true,"pushed_at":"2024-04-12T08:31:36.000Z","size":2165,"stargazers_count":1433,"open_issues_count":57,"forks_count":164,"subscribers_count":36,"default_branch":"develop","last_synced_at":"2024-10-01T15:23:20.395Z","etag":null,"topics":["command-line","options-parsing","scala"],"latest_commit_sha":null,"homepage":"","language":"Scala","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":"jstrachan/scopt","license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/scopt.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2012-03-18T19:27:17.000Z","updated_at":"2024-09-13T02:51:02.000Z","dependencies_parsed_at":"2023-07-05T20:16:51.380Z","dependency_job_id":null,"html_url":"https://github.com/scopt/scopt","commit_stats":null,"previous_names":[],"tags_count":18,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/scopt%2Fscopt","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/scopt%2Fscopt/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/scopt%2Fscopt/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/scopt%2Fscopt/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/scopt","download_url":"https://codeload.github.com/scopt/scopt/tar.gz/refs/heads/develop","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":235575693,"owners_count":19012156,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["command-line","options-parsing","scala"],"created_at":"2024-08-01T07:01:16.544Z","updated_at":"2025-10-07T01:31:07.241Z","avatar_url":"https://github.com/scopt.png","language":"Scala","readme":"  [1]: https://scopt.github.io/scopt/4.0.0/api/scopt/OParserBuilder.html\n\n# scopt\n[![Maven Central](https://img.shields.io/maven-central/v/com.github.scopt/scopt_2.11.svg)](https://maven-badges.herokuapp.com/maven-central/com.github.scopt/scopt_2.11)\n[![Javadocs](https://javadoc.io/badge/com.github.scopt/scopt_2.12.svg)](https://javadoc.io/doc/com.github.scopt/scopt_2.12)\n[![Build Status](https://github.com/scopt/scopt/actions/workflows/ci.yml/badge.svg?branch=develop\u0026event=push)](https://github.com/scopt/scopt/actions/workflows/ci.yml)\n\nscopt is a little command line options parsing library.\n\nSonatype\n--------\n\n```scala\nlibraryDependencies += \"com.github.scopt\" %% \"scopt\" % \"X.Y.Z\"\n```\n\nSee the Maven Central badge above.\n\n| Scala Version | JVM | JS (1.x) |  JS (0.6.x) |  Native (0.4.x) |  Native (0.3.x) |\n| ------------- | :-: | :------: | :---------: | :------------:  | :------------:  |\n| 3.x           | ✅  |   ✅     |     n/a     |      ✅         |      n/a        |\n| 2.13.x        | ✅  |   ✅     |     ✅      |      ✅         |      n/a        |\n| 2.12.x        | ✅  |   ✅     |     ✅      |      ✅         |      n/a        |\n| 2.11.x        | ✅  |   ✅     |     ✅      |      ✅         |      ✅         |\n\nUsage\n-----\n\nscopt 4.x provides two styles of constructing a command line option parser: functional DSL and object-oriented DSL.\nEither case, first you need a case class that represents the configuration:\n\n```scala\nimport java.io.File\ncase class Config(\n    foo: Int = -1,\n    out: File = new File(\".\"),\n    xyz: Boolean = false,\n    libName: String = \"\",\n    maxCount: Int = -1,\n    verbose: Boolean = false,\n    debug: Boolean = false,\n    mode: String = \"\",\n    files: Seq[File] = Seq(),\n    keepalive: Boolean = false,\n    jars: Seq[File] = Seq(),\n    kwargs: Map[String, String] = Map())\n```\n\nDuring the parsing process, a config object is passed around as an argument into `action` callbacks.\n\n### Functional DSL\n\nHere's how you create a `scopt.OParser[Config]`.\n\n```scala\nimport scopt.OParser\nval builder = OParser.builder[Config]\nval parser1 = {\n  import builder._\n  OParser.sequence(\n    programName(\"scopt\"),\n    head(\"scopt\", \"4.x\"),\n    // option -f, --foo\n    opt[Int]('f', \"foo\")\n      .action((x, c) =\u003e c.copy(foo = x))\n      .text(\"foo is an integer property\"),\n    // more options here...\n  )\n}\n\n// OParser.parse returns Option[Config]\nOParser.parse(parser1, args, Config()) match {\n  case Some(config) =\u003e\n    // do something\n  case _ =\u003e\n    // arguments are bad, error message will have been displayed\n}\n```\n\nSee [Scaladoc API][1] and the rest of this page for the details on various builder methods.\n\n#### Abstracting over effects\n\nBy default, scopt emits output when needed to stderr and stdout.  This is expected behavior when using scopt to process arguments for your stand-alone application.  However, if your application requires parsing arguments while not producing output directly, you may wish to intercept the side effects.\nUse `OParser.runParser(...)` to do so:\n\n```scala\n// OParser.runParser returns (Option[Config], List[OEffect])\nOParser.runParser(parser1, args, Config()) match {\n  case (result, effects) =\u003e\n    OParser.runEffects(effects, new DefaultOEffectSetup {\n      // override def displayToOut(msg: String): Unit = Console.out.println(msg)\n      // override def displayToErr(msg: String): Unit = Console.err.println(msg)\n      // override def reportError(msg: String): Unit = displayToErr(\"Error: \" + msg)\n      // override def reportWarning(msg: String): Unit = displayToErr(\"Warning: \" + msg)\n      \n      // ignore terminate\n      override def terminate(exitState: Either[String, Unit]): Unit = ()\n    })\n\n    result match {\n      Some(config) =\u003e\n        // do something\n      case _ =\u003e\n        // arguments are bad, error message will have been displayed\n    }\n}\n```\n\n#### Full example\n\n```scala\nimport scopt.OParser\nval builder = OParser.builder[Config]\nval parser1 = {\n  import builder._\n  OParser.sequence(\n    programName(\"scopt\"),\n    head(\"scopt\", \"4.x\"),\n    opt[Int]('f', \"foo\")\n      .action((x, c) =\u003e c.copy(foo = x))\n      .text(\"foo is an integer property\"),\n    opt[File]('o', \"out\")\n      .required()\n      .valueName(\"\u003cfile\u003e\")\n      .action((x, c) =\u003e c.copy(out = x))\n      .text(\"out is a required file property\"),\n    opt[(String, Int)](\"max\")\n      .action({ case ((k, v), c) =\u003e c.copy(libName = k, maxCount = v) })\n      .validate(x =\u003e\n        if (x._2 \u003e 0) success\n        else failure(\"Value \u003cmax\u003e must be \u003e0\"))\n      .keyValueName(\"\u003clibname\u003e\", \"\u003cmax\u003e\")\n      .text(\"maximum count for \u003clibname\u003e\"),\n    opt[Seq[File]]('j', \"jars\")\n      .valueName(\"\u003cjar1\u003e,\u003cjar2\u003e...\")\n      .action((x, c) =\u003e c.copy(jars = x))\n      .text(\"jars to include\"),\n    opt[Map[String, String]](\"kwargs\")\n      .valueName(\"k1=v1,k2=v2...\")\n      .action((x, c) =\u003e c.copy(kwargs = x))\n      .text(\"other arguments\"),\n    opt[Unit](\"verbose\")\n      .action((_, c) =\u003e c.copy(verbose = true))\n      .text(\"verbose is a flag\"),\n    opt[Unit](\"debug\")\n      .hidden()\n      .action((_, c) =\u003e c.copy(debug = true))\n      .text(\"this option is hidden in the usage text\"),\n    help(\"help\").text(\"prints this usage text\"),\n    arg[File](\"\u003cfile\u003e...\")\n      .unbounded()\n      .optional()\n      .action((x, c) =\u003e c.copy(files = c.files :+ x))\n      .text(\"optional unbounded args\"),\n    note(\"some notes.\" + sys.props(\"line.separator\")),\n    cmd(\"update\")\n      .action((_, c) =\u003e c.copy(mode = \"update\"))\n      .text(\"update is a command.\")\n      .children(\n        opt[Unit](\"not-keepalive\")\n          .abbr(\"nk\")\n          .action((_, c) =\u003e c.copy(keepalive = false))\n          .text(\"disable keepalive\"),\n        opt[Boolean](\"xyz\")\n          .action((x, c) =\u003e c.copy(xyz = x))\n          .text(\"xyz is a boolean property\"),\n        opt[Unit](\"debug-update\")\n          .hidden()\n          .action((_, c) =\u003e c.copy(debug = true))\n          .text(\"this option is hidden in the usage text\"),\n        checkConfig(\n          c =\u003e\n            if (c.keepalive \u0026\u0026 c.xyz) failure(\"xyz cannot keep alive\")\n            else success)\n      )\n  )\n}\n\n// OParser.parse returns Option[Config]\nOParser.parse(parser1, args, Config()) match {\n  case Some(config) =\u003e\n    // do something\n  case _ =\u003e\n    // arguments are bad, error message will have been displayed\n}\n```\n\nThe above generates the following usage text:\n\n```\nscopt 4.x\nUsage: scopt [update] [options] [\u003cfile\u003e...]\n\n  -f, --foo \u003cvalue\u003e        foo is an integer property\n  -o, --out \u003cfile\u003e         out is a required file property\n  --max:\u003clibname\u003e=\u003cmax\u003e    maximum count for \u003clibname\u003e\n  -j, --jars \u003cjar1\u003e,\u003cjar2\u003e...\n                           jars to include\n  --kwargs k1=v1,k2=v2...  other arguments\n  --verbose                verbose is a flag\n  --help                   prints this usage text\n  \u003cfile\u003e...                optional unbounded args\nsome notes.\n\nCommand: update [options]\nupdate is a command.\n  -nk, --not-keepalive     disable keepalive\n  --xyz \u003cvalue\u003e            xyz is a boolean property\n```\n\n#### Options\n\nCommand line options are defined using `opt[A]('f', \"foo\")` or `opt[A](\"foo\")` where `A` is any type that is an instance of `Read` typeclass.\n\n- `Unit` works as a plain flag `--foo` or `-f`\n- `Int`, `Long`, `Double`, `String`, `BigInt`, `BigDecimal`, `java.io.File`, `java.nio.file.Path`, `java.net.URI`, and `java.net.InetAddress` accept a value like `--foo 80` or `--foo:80`\n- `Boolean` accepts a value like `--foo true` or `--foo:1`\n- `java.util.Calendar` accepts a value like `--foo 2000-12-01`\n- `scala.concurrent.duration.Duration` accepts a value like `--foo 30s`\n- A pair of types like `(String, Int)` accept a key-value like `--foo:k=1` or `-f k=1`\n- A `Seq[File]` accepts a string containing comma-separated values such as `--jars foo.jar,bar.jar`\n- A `Map[String, String]` accepts a string containing comma-separated pairs like `--kwargs key1=val1,key2=val2`\n\nThis could be extended by defining `Read` instances in the scope. For example,\n\n```scala\nobject WeekDays extends Enumeration {\n  type WeekDays = Value\n  val Mon, Tue, Wed, Thur, Fri, Sat, Sun = Value\n}\nimplicit val weekDaysRead: scopt.Read[WeekDays.Value] =\n  scopt.Read.reads(WeekDays withName _)\n```\n\nBy default these options are optional.\n\n#### Short options\n\nFor plain flags (`opt[Unit]`) short options can be grouped as `-fb` to mean `--foo --bar`.\n\n`opt` accepts only a single character, but using `abbr(\"ab\")` a string can be used too:\n\n```scala\nopt[Unit](\"no-keepalive\").abbr(\"nk\").action( (x, c) =\u003e c.copy(keepalive = false) )\n```\n\n#### Help, Version, and Notes\n\nThere are special options with predefined action called `help(\"help\")` and `version(\"version\")`, which prints usage text and header text respectively. When `help(\"help\")` is defined, parser will print out short error message when it fails instead of printing the entire usage text.\n\n`note(\"...\")` is used add given string to the usage text.\n\n#### Arguments\n\nCommand line arguments are defined using `arg[A](\"\u003cfile\u003e\")`. It works similar to options, but instead it accepts values without `--` or `-`. By default, arguments accept a single value and are required.\n\n```scala\narg[String](\"\u003cfile\u003e...\")\n```\n\n#### Occurrence\n\nEach opt/arg carries occurrence information `minOccurs` and `maxOccurs`.\n`minOccurs` specify at least how many times an opt/arg must appear, and\n`maxOccurs` specify at most how many times an opt/arg may appear.\n\nOccurrence can be set using the methods on the opt/arg:\n\n```scala\nopt[String]('o', \"out\").required()\nopt[String]('o', \"out\").required().withFallback(() =\u003e \"default value\")\nopt[String]('o', \"out\").minOccurs(1) // same as above\narg[String](\"\u003cmode\u003e\").optional()\narg[String](\"\u003cmode\u003e\").minOccurs(0) // same as above\narg[String](\"\u003cfile\u003e...\").optional().unbounded()\narg[String](\"\u003cfile\u003e...\").minOccurs(0).maxOccurs(1024) // same as above\n```\n\n#### Visibility\n\nEach opt/arg can be hidden from the usage text using `hidden()` method:\n\n```scala\nopt[Unit](\"debug\")\n  .hidden()\n  .action( (_, c) =\u003e c.copy(debug = true) )\n  .text(\"this option is hidden in the usage text\")\n```\n\n#### Validation\n\nEach opt/arg can carry multiple validation functions.\n\n```scala\nopt[Int]('f', \"foo\")\n  .action( (x, c) =\u003e c.copy(intValue = x) )\n  .validate( x =\u003e\n    if (x \u003e 0) success\n    else failure(\"Option --foo must be \u003e0\") )\n  .validate( x =\u003e failure(\"Just because\") )\n```\n\nThe first function validates if the values are positive, and\nthe second function always fails.\n\n#### Check configuration\n\nConsistency among the option values can be checked using `checkConfig`.\n\n```scala\ncheckConfig( c =\u003e\n  if (c.keepalive \u0026\u0026 c.xyz) failure(\"xyz cannot keep alive\")\n  else success )\n```\n\nThese are called at the end of parsing.\n\n#### Commands\n\nCommands may be defined using `cmd(\"update\")`. Commands could be used to express `git branch` kind of argument, whose name means something. Using `children` method, a command may define child opts/args that get inserted in the presence of the command. To distinguish commands from arguments, they must appear in the first position within the level. It is generally recommended to avoid mixing args both in parent level and commands to avoid confusion.\n\n```scala\ncmd(\"update\")\n  .action( (_, c) =\u003e c.copy(mode = \"update\") )\n  .text(\"update is a command.\")\n  .children(\n    opt[Unit](\"not-keepalive\").abbr(\"nk\").action( (_, c) =\u003e\n      c.copy(keepalive = false) ).text(\"disable keepalive\"),\n    opt[Boolean](\"xyz\").action( (x, c) =\u003e\n      c.copy(xyz = x) ).text(\"xyz is a boolean property\"),\n    checkConfig( c =\u003e\n      if (c.keepalive \u0026\u0026 c.xyz) failure(\"xyz cannot keep alive\")\n      else success )\n  )\n```\n\nIn the above, `update test.txt` would trigger the update command, but `test.txt update` won't.\n\nCommands could be nested into another command as follows:\n\n```scala\ncmd(\"backend\")\n  .text(\"commands to manipulate backends:\\n\")\n  .action( (x, c) =\u003e c.copy(flag = true) )\n  .children(\n    cmd(\"update\").children(\n      arg[String](\"\u003ca\u003e\").action( (x, c) =\u003e c.copy(a = x) )\n    )\n  )\n```\n\n### Object-oriented DSL, immutable parsing\n\nHere's the object-oriented DSL that's mostly source-compatible with scopt 3.x.\n\nCreate a parser by extending `scopt.OptionParser[Config]`. See [Scaladoc API][1] for the details on various builder methods.\n\n```scala\nval parser = new scopt.OptionParser[Config](\"scopt\") {\n  head(\"scopt\", \"4.x\")\n\n  opt[Int]('f', \"foo\")\n    .action((x, c) =\u003e c.copy(foo = x))\n    .text(\"foo is an integer property\")\n\n  opt[File]('o', \"out\")\n    .required()\n    .valueName(\"\u003cfile\u003e\")\n    .action((x, c) =\u003e c.copy(out = x))\n    .text(\"out is a required file property\")\n}\n\n// parser.parse returns Option[C]\nparser.parse(args, Config()) match {\n  case Some(config) =\u003e\n    // do stuff\n\n  case None =\u003e\n    // arguments are bad, error message will have been displayed\n}\n```\n\n### Object-oriented DSL, mutable parsing\n\nCreate a `scopt.OptionParser[Unit]` and customize it with the options you need, passing in functions to process each option or argument. Use `foreach` instead of `action`.\n\nMutable parsing has changed from scopt 3.x. When upgrading from 3.x, replace `parser.parse(args)` with `parser.parse(args, ()).isDefined`.\n\n```scala\nval parser = new scopt.OptionParser[Unit](\"scopt\") {\n  head(\"scopt\", \"4.x\")\n\n  opt[Int]('f', \"foo\")\n    .foreach( x =\u003e c = c.copy(foo = x) )\n    .text(\"foo is an integer property\")\n\n  opt[File]('o', \"out\")\n    .required()\n    .valueName(\"\u003cfile\u003e\")\n    .foreach( x =\u003e c = c.copy(out = x) )\n    .text(\"out is a required file property\")\n}\nif (parser.parse(args, ()).isDefined) {\n  // do stuff\n}\nelse {\n  // arguments are bad, usage message will have been displayed\n}\n```\n\n### Advanced: showUsageOnError\n\nWhen `help(\"help\")` is defined, parser will print out short error message when it fails instead of printing the entire usage text.\n\nThis behavior could be changed by overriding `showUsageOnError` as follows:\n\n```scala\nimport scopt.{ OParserSetup, DefaultOParserSetup }\nval setup: OParserSetup = new DefaultOParserSetup {\n  override def showUsageOnError = Some(true)\n}\nval result = OParser.parse(parser1, args, Config(), setup)\n```\n\n### Advanced: Rendering mode\n\nscopt 3.5.0 introduced rendering mode, and adopted two-column rendering of the usage text by default. To switch back to the older one-column rendering override the `renderingMode` method:\n\n```scala\nimport scopt.{ OParserSetup, DefaultOParserSetup }\nval setup: OParserSetup = new DefaultOParserSetup {\n  override def renderingMode = scopt.RenderingMode.OneColumn\n}\nval result = OParser.parse(parser1, args, Config(), setup)\n```\n\n### Advanced: Termination handling\n\nBy default, when the `--help` or `--version` are invoked, they call `sys.exit(0)` after printing the help or version information. If this is not desired (e.g. testing purposes), you can override the `terminate(exitState: Either[String, Unit])` method:\n\n```scala\nimport scopt.{ OParser, DefaultOEffectSetup }\n\nOParser.runParser(parser1, args, Config()) match {\n  case (result, effects) =\u003e\n    OParser.runEffects(effects, new DefaultOEffectSetup {\n      // ignore terminate\n      override def terminate(exitState: Either[String, Unit]): Unit = ()\n    })\n\n    result match {\n      Some(config) =\u003e\n        // do something\n      case _ =\u003e\n        // arguments are bad, error message will have been displayed\n    }\n}\n```\n\nBuilding\n--------\n\nsbt to build scopt.\n\nLicense\n-------\n\n[MIT License](LICENSE.md).\n\nCredits\n-------\n\n- January 13, 2008: Aaron Harnly creates [aaronharnly/scala-options](https://github.com/aaronharnly/scala-options).\n- December 1, 2009: Tim Perrett introduces it [as a gist](http://gist.github.com/246481) on [Parsing command lines argument in a \"scalaesque\" way](http://www.scala-lang.org/node/4380).\n- January 10, 2010: James Strachan takes the code, adds usage text, sbt build, etc and creates [jstrachan/scopt](https://github.com/jstrachan/scopt), which is also mentioned in [Scala CLI Library?](http://www.scala-lang.org/node/4959).\n- March 4th, 2010: Eugene Yokota joins scopt project, improves usage text, and adds support for key=value option and argument list.\n- May 27, 2011: scopt 1.0.0 is released to scala-tools.org.\n- March 18, 2012: Eugene adds immutable parser, forks the project to [scopt/scopt](https://github.com/scopt/scopt), and releases scopt 2.0.0.\n- June 7, 2013: Eugene rewrites scopt from scratch for polymorphic options, and releases scopt 3.0.0.\n\nChanges\n-------\n\nSee [notes](https://github.com/scopt/scopt/tree/scopt3/notes).\n","funding_links":[],"categories":["Console","Table of Contents","Parsing","[Scala](https://www.scala-lang.org/)"],"sub_categories":["Command Line Interfaces","Useful awesome list for Ruby cli"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fscopt%2Fscopt","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fscopt%2Fscopt","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fscopt%2Fscopt/lists"}