2

I am used to use Scala scopt for command line option parsing. You can choose whether an argument is .required() by calling the just shown function.

How can I define an argument that is required only if another argument has been defined? For instance, I have a flag --writeToSnowflake defined via scopt like this:

opt[Unit]("writeToSnowflake")
    .action((_, config) => config.copy(writeToSnowflake = true))

If I choose that a job writes to snowflake, a set of other arguments become mandatory. For instance, --snowflake_table, --snowflake_database, etc.

How can I achieve it?

dadadima
  • 938
  • 4
  • 28
  • 1
    [cmd](https://github.com/scopt/scopt#commands)? – Dima May 11 '21 at 15:38
  • 1
    Hi @Dima, could you expand a bit more? I have managed to write some arguments nested to another one using the `.children()` property. Now, how I am gonna pass them to my application? Using the regular `--whatever` even for the children? Also, am I able to use `children()` without `cmd()`? – dadadima May 12 '21 at 06:38
  • 1
    I don't know really, I am just reading the doc. The examples seem to be fairly clear (like `foo command1 child1 child2 command2 child3 child4`, but I suggest, if something is unclear, you just experiment with it and see for yourself what it does. Same goes for `children` without `cmd`: I don't _think_ you can do it, but if you try it and it works, that would prove me wrong! – Dima May 12 '21 at 11:05

1 Answers1

2

I discovered that .children() can be used outside of .cmd()s to achieve what I asked. This is an example:

If the parent is specified, in this case if --snowflake is "passed" hence evaluates to True, then the children that are .required() will throw an error if they are null (but only when the parent is specified, like in my case).

opt[Unit]("snowflake")
        .action((_, config) => config.copy(writeToSnowflake = true))
        .text("optional flag for writing to Snowflake")
        .children(
          opt[Unit]("snowflake_incremental_writing")
            .action((_, config) => config.copy(snowflakeIncrementalWriting = true))
            .text("optional flag for enabling incremental writing"),
          opt[Map[String, String]]("snowflake_options")
            .required()
            .action((snowflakeOptions, config) => config.copy(snowflakeOptions = snowflakeOptions))
            .text("options for writing to snowflake: user, privateKey, warehouse, database, schema, and table")
        )
dadadima
  • 938
  • 4
  • 28