Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shared options and flags between commands

Tags:

Say my CLI utility has three commands: cmd1, cmd2, cmd3

And I want cmd3 to have same options and flags as cmd1 and cmd2. Like some sort of inheritance.

@click.command() @click.options("--verbose") def cmd1():     pass  @click.command() @click.options("--directory") def cmd2():     pass  @click.command() @click.inherit(cmd1, cmd2) # HYPOTHETICAL def cmd3():     pass 

So cmd3 will have flag --verbose and option --directory. Is it possible to make this with Click? Maybe I just have overlooked something in the documentation...

EDIT: I know that I can do this with click.group(). But then all the group's options must be specified before group's command. I want to have all the options normally after command.

cli.py --verbose --directory /tmp cmd3 -> cli.py cmd3 --verbose --directory /tmp

like image 755
jirinovo Avatar asked Oct 21 '16 17:10

jirinovo


People also ask

What is a command flag?

A number of flags might follow the command name. Flags modify the operation of a command and are sometimes called options. A flag is set off by spaces or tabs and usually starts with a dash (-). Exceptions are ps, tar, and ar, which do not require a dash in front of some of the flags.

What is an option flag?

Flag options are non-positional arguments passed to the command. Flags can either be option flags which take an argument, or boolean flags which do not. An option flag must have an argument. For example, if this command was run like this: $ mycli --force --file=./myfile.


1 Answers

I have found a simple solution! I slightly edited the snippet from https://github.com/pallets/click/issues/108 :

import click   _cmd1_options = [     click.option('--cmd1-opt') ]  _cmd2_options = [     click.option('--cmd2-opt') ]   def add_options(options):     def _add_options(func):         for option in reversed(options):             func = option(func)         return func     return _add_options   @click.group() def group(**kwargs):     pass   @group.command() @add_options(_cmd1_options) def cmd1(**kwargs):     print(kwargs)   @group.command() @add_options(_cmd2_options) def cmd2(**kwargs):     print(kwargs)   @group.command() @add_options(_cmd1_options) @add_options(_cmd2_options) @click.option("--cmd3-opt") def cmd3(**kwargs):     print(kwargs)   if __name__ == '__main__':     group() 
like image 126
jirinovo Avatar answered Dec 12 '22 16:12

jirinovo