I want to use several options together, or not at all, as the title says, but my methods seem relatively ugly, and I was wondering if there was a cleaner way to implement this. I have, in addition, looked at this, about how it might be done in argparse
, but I would like to implement it in click
if possible (I am trying to avoid using nargs=[...]
).
So far, this is what I have:
@click.group(invoke_without_command=True, no_args_is_help=True)
@click.option(
"-d",
"--group-dir",
type=click.Path(),
default="default",
help='the directory to find the TOML file from which to run multiple jobs at the same time; defaults to the configuration directory of melmetal: "~/.melmetal" on Unix systems, and "C:\\Users\\user\\.melmetal" on Windows',
)
@click.option("-f", "--group-file", help="the TOML file name")
@click.option(
"-n", "--group-name", help="name of the group of jobs"
)
@click.option(
"--no-debug",
is_flag=True,
type=bool,
help="prevent logging from being output to the terminal",
)
@click.pass_context
@logger.catch
def main(ctx, group_dir, group_file, group_name, no_debug):
options = [group_file, group_name]
group_dir = False if not any(options) else group_dir
options.append(group_dir)
if not any(options):
pass
elif not all(options):
logger.error(
colorize("red", "Sorry; you must use all options at once.")
)
exit(1)
else:
[...]
And a second example:
if any(createStuff):
if not all(createStuff):
le(
colorize("red", 'Sorry; you must use both the "--config-dir" and "--config-file" options at once.')
)
exit(1)
elif any(filtered):
if len(filtered) is not len(drbc):
le(
colorize("red", 'Sorry; you must use all of "--device", "--repo-name", "--backup-type", and "--config-dir" at once.')
)
exit(1)
else:
ctx = click.get_current_context()
click.echo(ctx.get_help())
exit(0)
How do I get the help text to show when no sub-commands are given? As I understand it, this is supposed to happen automatically, but for my code it automatically goes to the main function. An example of my workaround is in the second example, i.e. under the else
statement.