I want to make a simple CLI program that would accept --edit-config option to open its config in an editor. However, I can't figure out how to make Click ignore Missing Argument error if I specify the --edit-config flag only.
import click
@click.group(invoke_without_command=True)
@click.argument("name")
@click.option("--edit-config", is_flag=True)
def cli(name, edit_config):
# If we run it like
# $ myprog --edit-config | Missing Argument: NAME
if edit_config:
click.echo("Editing config")
...
exit(0)
# But this is the main functionality
# $ myprog John
click.echo(f"Hello, {name}")
@cli.command()
def command_a():
...
...
The first command causes Missing Argument error. There can be workarounds, like nargs=-1 or required=False, however, it seems that this makes the help page to either go completely or the name argument to be marked as optional in the help message, which is not true in the majority of use cases.
Is there is a simple way to make Click not raise Missing Argument error if a certain option is specified?
--edit-configwould be cleaner than a whole subcommand because the usage I'm planning is: default command:myapp John -> Hello John, some other action:myapp John bye -> Bye Johnandmyapp --edit-configto just edit the config. In all usages except when editing config (withclick.edit()) you specify John as an argument for the whole program and then do whatever you need with it. So using an option to essentially completely alter the program's behavior seems more logical to me.default=""behaves likenargs=-1, it marks the argument in help page as optional which is not true, and it also breaks the help page when nothing is passed tomyapp.default=Nonedoesn't change anything, the Missing argument error is still raised. Putting the code inif name: ...doesn't work as it is never reached because of the error.