Skip to content

Instantly share code, notes, and snippets.

@jacobtolar
Last active March 21, 2024 14:27
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save jacobtolar/fb80d5552a9a9dfc32b12a829fa21c0c to your computer and use it in GitHub Desktop.
Save jacobtolar/fb80d5552a9a9dfc32b12a829fa21c0c to your computer and use it in GitHub Desktop.
from click import command, option, Option, UsageError
class MutuallyExclusiveOption(Option):
def __init__(self, *args, **kwargs):
self.mutually_exclusive = set(kwargs.pop('mutually_exclusive', []))
help = kwargs.get('help', '')
if self.mutually_exclusive:
ex_str = ', '.join(self.mutually_exclusive)
kwargs['help'] = help + (
' NOTE: This argument is mutually exclusive with '
' arguments: [' + ex_str + '].'
)
super(MutuallyExclusiveOption, self).__init__(*args, **kwargs)
def handle_parse_result(self, ctx, opts, args):
if self.mutually_exclusive.intersection(opts) and self.name in opts:
raise UsageError(
"Illegal usage: `{}` is mutually exclusive with "
"arguments `{}`.".format(
self.name,
', '.join(self.mutually_exclusive)
)
)
return super(MutuallyExclusiveOption, self).handle_parse_result(
ctx,
opts,
args
)
@command(help="Run the command.")
@option('--jar-file', cls=MutuallyExclusiveOption,
help="The jar file the topology lives in.",
mutually_exclusive=["other_arg"])
@option('--other-arg',
cls=MutuallyExclusiveOption,
help="Another argument.",
mutually_exclusive=["jar_file"])
def cli(jar_file, other_arg):
print "Running cli."
print "jar-file: {}".format(jar_file)
print "other-arg: {}".format(other_arg)
if __name__ == '__main__':
cli()
$ python2.7 click_mutually_exclusive_argument.py --help
Usage: click_mutually_exclusive_argument.py [OPTIONS]
Run the command.
Options:
--jar-file TEXT The jar file the topology lives in. NOTE: This argument is
mutually exclusive with arguments: [other_arg].
--other-arg TEXT Another argument. NOTE: This argument is
mutually exclusive with arguments: [jar_file].
--help Show this message and exit.
$ python2.7 click_mutually_exclusive_argument.py --jar-file some/jar.jar
Running cli.
jar-file: some/jar.jar
other-arg: None
$ python2.7 click_mutually_exclusive_argument.py --other-arg some/arg.txt
Running cli.
jar-file: None
other-arg: some/arg.txt
$ python2.7 click_mutually_exclusive_argument.py --other-arg some/arg.txt --jar-file some/jar.jar
Error: Illegal usage: `other_arg` is mutually exclusive with arguments `jar_file`.
@elprimato
Copy link

Hi, jacobtolar,
Could you maybe add a permissive license (i.e., MIT) to this gist?
It would make it easier in downstream projects to correctly annotate the origin.
Thanks, Vo

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment