gi-glib-2.0.27: GLib bindings
CopyrightWill Thompson and Iñaki García Etxebarria
LicenseLGPL-2.1
MaintainerIñaki García Etxebarria
Safe HaskellSafe-Inferred
LanguageHaskell2010

GI.GLib.Structs.OptionContext

Description

The GOption commandline parser is intended to be a simpler replacement for the popt library. It supports short and long commandline options, as shown in the following example:

testtreemodel -r 1 --max-size 20 --rand --display=:1.0 -vb -- file1 file2

The example demonstrates a number of features of the GOption commandline parser:

  • Options can be single letters, prefixed by a single dash.
  • Multiple short options can be grouped behind a single dash.
  • Long options are prefixed by two consecutive dashes.
  • Options can have an extra argument, which can be a number, a string or a filename. For long options, the extra argument can be appended with an equals sign after the option name, which is useful if the extra argument starts with a dash, which would otherwise cause it to be interpreted as another option.
  • Non-option arguments are returned to the application as rest arguments.
  • An argument consisting solely of two dashes turns off further parsing, any remaining arguments (even those starting with a dash) are returned to the application as rest arguments.

Another important feature of GOption is that it can automatically generate nicely formatted help output. Unless it is explicitly turned off with optionContextSetHelpEnabled, GOption will recognize the --help, -?, --help-all and --help-groupname options (where groupname is the name of a OptionGroup) and write a text similar to the one shown in the following example to stdout.

Usage:
  testtreemodel [OPTION...] - test tree model performance
 
Help Options:
  -h, --help               Show help options
  --help-all               Show all help options
  --help-gtk               Show GTK Options
 
Application Options:
  -r, --repeats=N          Average over N repetitions
  -m, --max-size=M         Test up to 2^M items
  --display=DISPLAY        X display to use
  -v, --verbose            Be verbose
  -b, --beep               Beep when done
  --rand                   Randomize the data

GOption groups options in GOptionGroups, which makes it easy to incorporate options from multiple sources. The intended use for this is to let applications collect option groups from the libraries it uses, add them to their OptionContext, and parse all options by a single call to optionContextParse. See gtk_get_option_group() for an example.

If an option is declared to be of type string or filename, GOption takes care of converting it to the right encoding; strings are returned in UTF-8, filenames are returned in the GLib filename encoding. Note that this only works if setlocale() has been called before optionContextParse.

Here is a complete example of setting up GOption to parse the example commandline above and produce the example help output.

C code

static gint repeats = 2;
static gint max_size = 8;
static gboolean verbose = FALSE;
static gboolean beep = FALSE;
static gboolean randomize = FALSE;

static GOptionEntry entries[] =
{
  { "repeats", 'r', 0, G_OPTION_ARG_INT, &repeats, "Average over N repetitions", "N" },
  { "max-size", 'm', 0, G_OPTION_ARG_INT, &max_size, "Test up to 2^M items", "M" },
  { "verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose, "Be verbose", NULL },
  { "beep", 'b', 0, G_OPTION_ARG_NONE, &beep, "Beep when done", NULL },
  { "rand", 0, 0, G_OPTION_ARG_NONE, &randomize, "Randomize the data", NULL },
  G_OPTION_ENTRY_NULL
};

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

  context = g_option_context_new ("- test tree model performance");
  g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
  g_option_context_add_group (context, gtk_get_option_group (TRUE));
  if (!g_option_context_parse (context, &argc, &argv, &error))
    {
      g_print ("option parsing failed: %s\n", error->message);
      exit (1);
    }

  ...

}

On UNIX systems, the argv that is passed to main() has no particular encoding, even to the extent that different parts of it may have different encodings. In general, normal arguments and flags will be in the current locale and filenames should be considered to be opaque byte strings. Proper use of OptionArgFilename vs OptionArgString is therefore important.

Note that on Windows, filenames do have an encoding, but using OptionContext with the argv as passed to main() will result in a program that can only accept commandline arguments with characters from the system codepage. This can cause problems when attempting to deal with filenames containing Unicode characters that fall outside of the codepage.

A solution to this is to use g_win32_get_command_line() and optionContextParseStrv which will properly handle full Unicode filenames. If you are using GApplication, this is done automatically for you.

The following example shows how you can use OptionContext directly in order to correctly deal with Unicode filenames on Windows:

C code

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

#ifdef G_OS_WIN32
  args = g_win32_get_command_line ();
#else
  args = g_strdupv (argv);
#endif

  // set up context

  if (!g_option_context_parse_strv (context, &args, &error))
    {
      // error happened
    }

  ...

  g_strfreev (args);

  ...
}
Synopsis

Exported types

Methods

addGroup

optionContextAddGroup Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> OptionContext

context: a OptionContext

-> OptionGroup

group: the group to add

-> m () 

Adds a OptionGroup to the context, so that parsing with context will recognize the options in the group. Note that this will take ownership of the group and thus the group should not be freed.

Since: 2.6

addMainEntries

optionContextAddMainEntries Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> OptionContext

context: a OptionContext

-> [OptionEntry]

entries: a Nothing-terminated array of GOptionEntrys

-> Maybe Text

translationDomain: a translation domain to use for translating the --help output for the options in entries with gettext(), or Nothing

-> m () 

A convenience function which creates a main group if it doesn't exist, adds the entries to it and sets the translation domain.

Since: 2.6

free

optionContextFree Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> OptionContext

context: a OptionContext

-> m () 

Frees context and all the groups which have been added to it.

Please note that parsed arguments need to be freed separately (see OptionEntry).

Since: 2.6

getDescription

optionContextGetDescription Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> OptionContext

context: a OptionContext

-> m Text

Returns: the description

Returns the description. See optionContextSetDescription.

Since: 2.12

getHelp

optionContextGetHelp Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> OptionContext

context: a OptionContext

-> Bool

mainHelp: if True, only include the main group

-> Maybe OptionGroup

group: the OptionGroup to create help for, or Nothing

-> m Text

Returns: A newly allocated string containing the help text

Returns a formatted, translated help text for the given context. To obtain the text produced by --help, call g_option_context_get_help (context, TRUE, NULL). To obtain the text produced by --help-all, call g_option_context_get_help (context, FALSE, NULL). To obtain the help text for an option group, call g_option_context_get_help (context, FALSE, group).

Since: 2.14

getHelpEnabled

optionContextGetHelpEnabled Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> OptionContext

context: a OptionContext

-> m Bool

Returns: True if automatic help generation is turned on.

Returns whether automatic --help generation is turned on for context. See optionContextSetHelpEnabled.

Since: 2.6

getIgnoreUnknownOptions

optionContextGetIgnoreUnknownOptions Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> OptionContext

context: a OptionContext

-> m Bool

Returns: True if unknown options are ignored.

Returns whether unknown options are ignored or not. See optionContextSetIgnoreUnknownOptions.

Since: 2.6

getMainGroup

optionContextGetMainGroup Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> OptionContext

context: a OptionContext

-> m OptionGroup

Returns: the main group of context, or Nothing if context doesn't have a main group. Note that group belongs to context and should not be modified or freed.

Returns a pointer to the main group of context.

Since: 2.6

getStrictPosix

optionContextGetStrictPosix Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> OptionContext

context: a OptionContext

-> m Bool

Returns: True if strict POSIX is enabled, False otherwise.

Returns whether strict POSIX code is enabled.

See optionContextSetStrictPosix for more information.

Since: 2.44

getSummary

optionContextGetSummary Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> OptionContext

context: a OptionContext

-> m Text

Returns: the summary

Returns the summary. See optionContextSetSummary.

Since: 2.12

parse

optionContextParse Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> OptionContext

context: a OptionContext

-> Maybe [Text]

argv: a pointer to the array of command line arguments

-> m (Maybe [Text])

(Can throw GError)

Parses the command line arguments, recognizing options which have been added to context. A side-effect of calling this function is that setPrgname will be called.

If the parsing is successful, any parsed arguments are removed from the array and argc and argv are updated accordingly. A '--' option is stripped from argv unless there are unparsed options before and after it, or some of the options after it start with '-'. In case of an error, argc and argv are left unmodified.

If automatic --help support is enabled (see optionContextSetHelpEnabled), and the argv array contains one of the recognized help options, this function will produce help output to stdout and call exit (0).

Note that function depends on the [current locale][setlocale] for automatic character set conversion of string and filename arguments.

Since: 2.6

setDescription

optionContextSetDescription Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> OptionContext

context: a OptionContext

-> Maybe Text

description: a string to be shown in --help output after the list of options, or Nothing

-> m () 

Adds a string to be displayed in --help output after the list of options. This text often includes a bug reporting address.

Note that the summary is translated (see optionContextSetTranslateFunc).

Since: 2.12

setHelpEnabled

optionContextSetHelpEnabled Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> OptionContext

context: a OptionContext

-> Bool

helpEnabled: True to enable --help, False to disable it

-> m () 

Enables or disables automatic generation of --help output. By default, optionContextParse recognizes --help, -h, -?, --help-all and --help-groupname and creates suitable output to stdout.

Since: 2.6

setIgnoreUnknownOptions

optionContextSetIgnoreUnknownOptions Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> OptionContext

context: a OptionContext

-> Bool

ignoreUnknown: True to ignore unknown options, False to produce an error when unknown options are met

-> m () 

Sets whether to ignore unknown options or not. If an argument is ignored, it is left in the argv array after parsing. By default, optionContextParse treats unknown options as error.

This setting does not affect non-option arguments (i.e. arguments which don't start with a dash). But note that GOption cannot reliably determine whether a non-option belongs to a preceding unknown option.

Since: 2.6

setMainGroup

optionContextSetMainGroup Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> OptionContext

context: a OptionContext

-> OptionGroup

group: the group to set as main group

-> m () 

Sets a OptionGroup as main group of the context. This has the same effect as calling optionContextAddGroup, the only difference is that the options in the main group are treated differently when generating --help output.

Since: 2.6

setStrictPosix

optionContextSetStrictPosix Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> OptionContext

context: a OptionContext

-> Bool

strictPosix: the new value

-> m () 

Sets strict POSIX mode.

By default, this mode is disabled.

In strict POSIX mode, the first non-argument parameter encountered (eg: filename) terminates argument processing. Remaining arguments are treated as non-options and are not attempted to be parsed.

If strict POSIX mode is disabled then parsing is done in the GNU way where option arguments can be freely mixed with non-options.

As an example, consider "ls foo -l". With GNU style parsing, this will list "foo" in long mode. In strict POSIX style, this will list the files named "foo" and "-l".

It may be useful to force strict POSIX mode when creating "verb style" command line tools. For example, the "gsettings" command line tool supports the global option "--schemadir" as well as many subcommands ("get", "set", etc.) which each have their own set of arguments. Using strict POSIX mode will allow parsing the global options up to the verb name while leaving the remaining options to be parsed by the relevant subcommand (which can be determined by examining the verb name, which should be present in argv[1] after parsing).

Since: 2.44

setSummary

optionContextSetSummary Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> OptionContext

context: a OptionContext

-> Maybe Text

summary: a string to be shown in --help output before the list of options, or Nothing

-> m () 

Adds a string to be displayed in --help output before the list of options. This is typically a summary of the program functionality.

Note that the summary is translated (see optionContextSetTranslateFunc and optionContextSetTranslationDomain).

Since: 2.12

setTranslateFunc

optionContextSetTranslateFunc Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> OptionContext

context: a OptionContext

-> Maybe TranslateFunc

func: the TranslateFunc, or Nothing

-> m () 

Sets the function which is used to translate the contexts user-visible strings, for --help output. If func is Nothing, strings are not translated.

Note that option groups have their own translation functions, this function only affects the parameterString (see g_option_context_new()), the summary (see optionContextSetSummary) and the description (see optionContextSetDescription).

If you are using gettext(), you only need to set the translation domain, see optionContextSetTranslationDomain.

Since: 2.12

setTranslationDomain

optionContextSetTranslationDomain Source #

Arguments

:: (HasCallStack, MonadIO m) 
=> OptionContext

context: a OptionContext

-> Text

domain: the domain to use

-> m () 

A convenience function to use gettext() for translating user-visible strings.

Since: 2.12