How to implement CLI option as "repeat to increase value"?

Imagine that I have an app, my_app, I want to design its CLI option as:

my_app -v

with -v being “verbose”, and to increase verbosity, user just repeat that option, like:

my_app -vv

How to archive that with Gio.Application.add_main_option and friends?

GOptionContext can’t do that, so you just have to do the parsing yourself.

1 Like

I don’t know pygi well enough off the top of my head, so here’s a C version which hopefully you can translate to Python :slight_smile: You can use a combination of G_OPTION_FLAG_NO_ARG and G_OPTION_ARG_CALLBACK. For example:

/* gcc -Wall -g -O0 -o foo foo.c `pkg-config --cflags --libs glib-2.0` */
#include <stdio.h>
#include <glib.h>

static guint verbosity = 0;

static gboolean verbosity_callback (const gchar    *option_name,
				    const gchar    *value,
				    gpointer        data,
				    GError        **error)
{
    verbosity++;
    return TRUE;
}

static GOptionEntry entries[] = {
    { "verbose", 'v', G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, verbosity_callback, "Increase verbosity", "" },
    { NULL }
};

int
main (int argc, char **argv)
{
    GOptionContext *context;
    GError *error = NULL;

    context = g_option_context_new ("- test verbosity flag");
    g_option_context_add_main_entries (context, entries, NULL);

    if (!g_option_context_parse (context, &argc, &argv, &error)) {
        printf ("invalid options: %s\n", error->message);
        exit (1);
    }

    printf ("verbosity level %u\n", verbosity);
    return 0;
}

If you run it like “foo -vvv” it will print “verbosity level 3”.

1 Like

Thanks. I hope that GTK developers will add this feature, because this pattern seems to be popular enough.

It’s extremely unlikely that will happen. You can easily use the callback notation to do that yourself, and that kind of incremental globbing is only ever useful for a very small subset of command line arguments.

Among Python applications, this pattern is popular enough that it is added to Python standard library:

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--verbose', '-v', action='count', default=0)
>>> parser.parse_args(['-vvv'])
Namespace(verbose=3)

and also welknown 3-rd party library:

@click.command()
@click.option('-v', '--verbose', count=True)
def log(verbose):
    click.echo('Verbosity: %s' % verbose)

It doesn’t really matter what’s popular with Python, though.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.