Mutually exclusive options using Apache Commons CLI
Asked Answered
L

2

13

I can create 2 mutually exclusive options using the following:

Option a = OptionBuilder.create("a");
Option b = OptionBuilder.create("b");

OptionGroup optgrp = new OptionGroup();
optgrp .setRequired(true);
optgrp .addOption(a);
optgrp .addOption(b);

The above will force the user to provide either option a or option b.

But if I have a third option, c:

Option c = OptionBuilder.create("c");

is it possible to create mutually exclusive options such that:

Either:

  1. Option a must be provided OR
  2. Both options b and c must be provided

I couldn't see a way to do it using OptionGroup?

Labelle answered 7/1, 2015 at 14:29 Comment(0)
L
8

As a workaround to this, I implemented the following, not ideal, but..

public static void validate(final CommandLine cmdLine) {
   final boolean aSupplied = cmdLine.hasOption(A);

   final boolean bAndCSupplied = cmdLine.hasOption(B) && cmdLine.hasOption(C);

   final boolean bOrCSupplied = !bAndCSupplied && (cmdLine.hasOption(B) || cmdLine.hasOption(C));

   if ((aSupplied && bAndCSupplied) || (!aSupplied && !bAndCSupplied)
      || (aSupplied && bOrCSupplied )) {
          throw new Exception(...);
   }
}
Labelle answered 8/1, 2015 at 8:34 Comment(1)
Yes, I don't think functionality in commons-cli goes that far, but on the other hand it would add a lot of very complicated code for a few cases that can easily be dealt with outside of the library like you did.Mutiny
R
0

I think a possible workaround could be defining both option b and c in one option. If they are flags, they could both be true, or both be false, but no different combination is possible depending of the rules you set. So I guess they have values. So you could define an option which have two values.

Roehm answered 6/6 at 12:47 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Pontificals

© 2022 - 2024 — McMap. All rights reserved.