1 /* goption.c - Option parser
3 * Copyright (C) 1999, 2003 Red Hat Software
4 * Copyright (C) 2004 Anders Carlsson <andersca@gnome.org>
6 * SPDX-License-Identifier: LGPL-2.1-or-later
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public License
19 * along with this library; if not, see <http://www.gnu.org/licenses/>.
24 * @Short_description: parses commandline options
25 * @Title: Commandline option parser
27 * The GOption commandline parser is intended to be a simpler replacement
28 * for the popt library. It supports short and long commandline options,
29 * as shown in the following example:
31 * `testtreemodel -r 1 --max-size 20 --rand --display=:1.0 -vb -- file1 file2`
33 * The example demonstrates a number of features of the GOption
36 * - Options can be single letters, prefixed by a single dash.
38 * - Multiple short options can be grouped behind a single dash.
40 * - Long options are prefixed by two consecutive dashes.
42 * - Options can have an extra argument, which can be a number, a string or
43 * a filename. For long options, the extra argument can be appended with
44 * an equals sign after the option name, which is useful if the extra
45 * argument starts with a dash, which would otherwise cause it to be
46 * interpreted as another option.
48 * - Non-option arguments are returned to the application as rest arguments.
50 * - An argument consisting solely of two dashes turns off further parsing,
51 * any remaining arguments (even those starting with a dash) are returned
52 * to the application as rest arguments.
54 * Another important feature of GOption is that it can automatically
55 * generate nicely formatted help output. Unless it is explicitly turned
56 * off with g_option_context_set_help_enabled(), GOption will recognize
57 * the `--help`, `-?`, `--help-all` and `--help-groupname` options
58 * (where `groupname` is the name of a #GOptionGroup) and write a text
59 * similar to the one shown in the following example to stdout.
63 * testtreemodel [OPTION...] - test tree model performance
66 * -h, --help Show help options
67 * --help-all Show all help options
68 * --help-gtk Show GTK+ Options
70 * Application Options:
71 * -r, --repeats=N Average over N repetitions
72 * -m, --max-size=M Test up to 2^M items
73 * --display=DISPLAY X display to use
74 * -v, --verbose Be verbose
75 * -b, --beep Beep when done
76 * --rand Randomize the data
79 * GOption groups options in #GOptionGroups, which makes it easy to
80 * incorporate options from multiple sources. The intended use for this is
81 * to let applications collect option groups from the libraries it uses,
82 * add them to their #GOptionContext, and parse all options by a single call
83 * to g_option_context_parse(). See gtk_get_option_group() for an example.
85 * If an option is declared to be of type string or filename, GOption takes
86 * care of converting it to the right encoding; strings are returned in
87 * UTF-8, filenames are returned in the GLib filename encoding. Note that
88 * this only works if setlocale() has been called before
89 * g_option_context_parse().
91 * Here is a complete example of setting up GOption to parse the example
92 * commandline above and produce the example help output.
93 * |[<!-- language="C" -->
94 * static gint repeats = 2;
95 * static gint max_size = 8;
96 * static gboolean verbose = FALSE;
97 * static gboolean beep = FALSE;
98 * static gboolean randomize = FALSE;
100 * static GOptionEntry entries[] =
102 * { "repeats", 'r', 0, G_OPTION_ARG_INT, &repeats, "Average over N repetitions", "N" },
103 * { "max-size", 'm', 0, G_OPTION_ARG_INT, &max_size, "Test up to 2^M items", "M" },
104 * { "verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose, "Be verbose", NULL },
105 * { "beep", 'b', 0, G_OPTION_ARG_NONE, &beep, "Beep when done", NULL },
106 * { "rand", 0, 0, G_OPTION_ARG_NONE, &randomize, "Randomize the data", NULL },
107 * G_OPTION_ENTRY_NULL
111 * main (int argc, char *argv[])
113 * GError *error = NULL;
114 * GOptionContext *context;
116 * context = g_option_context_new ("- test tree model performance");
117 * g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
118 * g_option_context_add_group (context, gtk_get_option_group (TRUE));
119 * if (!g_option_context_parse (context, &argc, &argv, &error))
121 * g_print ("option parsing failed: %s\n", error->message);
130 * On UNIX systems, the argv that is passed to main() has no particular
131 * encoding, even to the extent that different parts of it may have
132 * different encodings. In general, normal arguments and flags will be
133 * in the current locale and filenames should be considered to be opaque
134 * byte strings. Proper use of %G_OPTION_ARG_FILENAME vs
135 * %G_OPTION_ARG_STRING is therefore important.
137 * Note that on Windows, filenames do have an encoding, but using
138 * #GOptionContext with the argv as passed to main() will result in a
139 * program that can only accept commandline arguments with characters
140 * from the system codepage. This can cause problems when attempting to
141 * deal with filenames containing Unicode characters that fall outside
144 * A solution to this is to use g_win32_get_command_line() and
145 * g_option_context_parse_strv() which will properly handle full Unicode
146 * filenames. If you are using #GApplication, this is done
147 * automatically for you.
149 * The following example shows how you can use #GOptionContext directly
150 * in order to correctly deal with Unicode filenames on Windows:
152 * |[<!-- language="C" -->
154 * main (int argc, char **argv)
156 * GError *error = NULL;
157 * GOptionContext *context;
161 * args = g_win32_get_command_line ();
163 * args = g_strdupv (argv);
168 * if (!g_option_context_parse_strv (context, &args, &error))
189 #if defined __OpenBSD__
191 #include <sys/sysctl.h>
197 #include "glibintl.h"
199 #if defined G_OS_WIN32
203 #define TRANSLATE(group, str) (((group)->translate_func ? (* (group)->translate_func) ((str), (group)->translate_data) : (str)))
205 #define NO_ARG(entry) ((entry)->arg == G_OPTION_ARG_NONE || \
206 ((entry)->arg == G_OPTION_ARG_CALLBACK && \
207 ((entry)->flags & G_OPTION_FLAG_NO_ARG)))
209 #define OPTIONAL_ARG(entry) ((entry)->arg == G_OPTION_ARG_CALLBACK && \
210 (entry)->flags & G_OPTION_FLAG_OPTIONAL_ARG)
242 struct _GOptionContext
246 gchar *parameter_string; /* (nullable) */
250 GTranslateFunc translate_func;
251 GDestroyNotify translate_notify;
252 gpointer translate_data;
254 guint help_enabled : 1;
255 guint ignore_unknown : 1;
257 guint strict_posix : 1;
259 GOptionGroup *main_group;
261 /* We keep a list of change so we can revert them */
264 /* We also keep track of all argv elements
265 * that should be NULLed or modified.
267 GList *pending_nulls;
274 gchar *help_description;
278 GDestroyNotify destroy_notify;
281 GTranslateFunc translate_func;
282 GDestroyNotify translate_notify;
283 gpointer translate_data;
285 GOptionEntry *entries;
288 GOptionParseFunc pre_parse_func;
289 GOptionParseFunc post_parse_func;
290 GOptionErrorFunc error_func;
293 static void free_changes_list (GOptionContext *context,
295 static void free_pending_nulls (GOptionContext *context,
296 gboolean perform_nulls);
300 _g_unichar_get_width (gunichar c)
302 if (G_UNLIKELY (g_unichar_iszerowidth (c)))
305 /* we ignore the fact that we should call g_unichar_iswide_cjk() under
306 * some locales (legacy East Asian ones) */
307 if (g_unichar_iswide (c))
314 _g_utf8_strwidth (const gchar *p)
317 g_return_val_if_fail (p != NULL, 0);
321 len += _g_unichar_get_width (g_utf8_get_char (p));
322 p = g_utf8_next_char (p);
328 G_DEFINE_QUARK (g-option-context-error-quark, g_option_error)
331 * g_option_context_new:
332 * @parameter_string: (nullable): a string which is displayed in
333 * the first line of `--help` output, after the usage summary
334 * `programname [OPTION...]`
336 * Creates a new option context.
338 * The @parameter_string can serve multiple purposes. It can be used
339 * to add descriptions for "rest" arguments, which are not parsed by
340 * the #GOptionContext, typically something like "FILES" or
341 * "FILE1 FILE2...". If you are using %G_OPTION_REMAINING for
342 * collecting "rest" arguments, GLib handles this automatically by
343 * using the @arg_description of the corresponding #GOptionEntry in
346 * Another usage is to give a short summary of the program
347 * functionality, like " - frob the strings", which will be displayed
348 * in the same line as the usage. For a longer description of the
349 * program functionality that should be displayed as a paragraph
350 * below the usage line, use g_option_context_set_summary().
352 * Note that the @parameter_string is translated using the
353 * function set with g_option_context_set_translate_func(), so
354 * it should normally be passed untranslated.
356 * Returns: a newly created #GOptionContext, which must be
357 * freed with g_option_context_free() after use.
362 g_option_context_new (const gchar *parameter_string)
365 GOptionContext *context;
367 context = g_new0 (GOptionContext, 1);
369 /* Clear the empty string to NULL, otherwise we end up calling gettext(""),
370 * which returns the translation header. */
371 if (parameter_string != NULL && *parameter_string == '\0')
372 parameter_string = NULL;
374 context->parameter_string = g_strdup (parameter_string);
375 context->strict_posix = FALSE;
376 context->help_enabled = TRUE;
377 context->ignore_unknown = FALSE;
383 * g_option_context_free:
384 * @context: a #GOptionContext
386 * Frees context and all the groups which have been
389 * Please note that parsed arguments need to be freed separately (see
394 void g_option_context_free (GOptionContext *context)
396 g_return_if_fail (context != NULL);
398 g_list_free_full (context->groups, (GDestroyNotify) g_option_group_unref);
400 if (context->main_group)
401 g_option_group_unref (context->main_group);
403 free_changes_list (context, FALSE);
404 free_pending_nulls (context, FALSE);
406 g_free (context->parameter_string);
407 g_free (context->summary);
408 g_free (context->description);
410 if (context->translate_notify)
411 (* context->translate_notify) (context->translate_data);
418 * g_option_context_set_help_enabled:
419 * @context: a #GOptionContext
420 * @help_enabled: %TRUE to enable `--help`, %FALSE to disable it
422 * Enables or disables automatic generation of `--help` output.
423 * By default, g_option_context_parse() recognizes `--help`, `-h`,
424 * `-?`, `--help-all` and `--help-groupname` and creates suitable
429 void g_option_context_set_help_enabled (GOptionContext *context,
430 gboolean help_enabled)
433 g_return_if_fail (context != NULL);
435 context->help_enabled = help_enabled;
439 * g_option_context_get_help_enabled:
440 * @context: a #GOptionContext
442 * Returns whether automatic `--help` generation
443 * is turned on for @context. See g_option_context_set_help_enabled().
445 * Returns: %TRUE if automatic help generation is turned on.
450 g_option_context_get_help_enabled (GOptionContext *context)
452 g_return_val_if_fail (context != NULL, FALSE);
454 return context->help_enabled;
458 * g_option_context_set_ignore_unknown_options:
459 * @context: a #GOptionContext
460 * @ignore_unknown: %TRUE to ignore unknown options, %FALSE to produce
461 * an error when unknown options are met
463 * Sets whether to ignore unknown options or not. If an argument is
464 * ignored, it is left in the @argv array after parsing. By default,
465 * g_option_context_parse() treats unknown options as error.
467 * This setting does not affect non-option arguments (i.e. arguments
468 * which don't start with a dash). But note that GOption cannot reliably
469 * determine whether a non-option belongs to a preceding unknown option.
474 g_option_context_set_ignore_unknown_options (GOptionContext *context,
475 gboolean ignore_unknown)
477 g_return_if_fail (context != NULL);
479 context->ignore_unknown = ignore_unknown;
483 * g_option_context_get_ignore_unknown_options:
484 * @context: a #GOptionContext
486 * Returns whether unknown options are ignored or not. See
487 * g_option_context_set_ignore_unknown_options().
489 * Returns: %TRUE if unknown options are ignored.
494 g_option_context_get_ignore_unknown_options (GOptionContext *context)
496 g_return_val_if_fail (context != NULL, FALSE);
498 return context->ignore_unknown;
502 * g_option_context_set_strict_posix:
503 * @context: a #GOptionContext
504 * @strict_posix: the new value
506 * Sets strict POSIX mode.
508 * By default, this mode is disabled.
510 * In strict POSIX mode, the first non-argument parameter encountered
511 * (eg: filename) terminates argument processing. Remaining arguments
512 * are treated as non-options and are not attempted to be parsed.
514 * If strict POSIX mode is disabled then parsing is done in the GNU way
515 * where option arguments can be freely mixed with non-options.
517 * As an example, consider "ls foo -l". With GNU style parsing, this
518 * will list "foo" in long mode. In strict POSIX style, this will list
519 * the files named "foo" and "-l".
521 * It may be useful to force strict POSIX mode when creating "verb
522 * style" command line tools. For example, the "gsettings" command line
523 * tool supports the global option "--schemadir" as well as many
524 * subcommands ("get", "set", etc.) which each have their own set of
525 * arguments. Using strict POSIX mode will allow parsing the global
526 * options up to the verb name while leaving the remaining options to be
527 * parsed by the relevant subcommand (which can be determined by
528 * examining the verb name, which should be present in argv[1] after
534 g_option_context_set_strict_posix (GOptionContext *context,
535 gboolean strict_posix)
537 g_return_if_fail (context != NULL);
539 context->strict_posix = strict_posix;
543 * g_option_context_get_strict_posix:
544 * @context: a #GOptionContext
546 * Returns whether strict POSIX code is enabled.
548 * See g_option_context_set_strict_posix() for more information.
550 * Returns: %TRUE if strict POSIX is enabled, %FALSE otherwise.
555 g_option_context_get_strict_posix (GOptionContext *context)
557 g_return_val_if_fail (context != NULL, FALSE);
559 return context->strict_posix;
563 * g_option_context_add_group:
564 * @context: a #GOptionContext
565 * @group: (transfer full): the group to add
567 * Adds a #GOptionGroup to the @context, so that parsing with @context
568 * will recognize the options in the group. Note that this will take
569 * ownership of the @group and thus the @group should not be freed.
574 g_option_context_add_group (GOptionContext *context,
579 g_return_if_fail (context != NULL);
580 g_return_if_fail (group != NULL);
581 g_return_if_fail (group->name != NULL);
582 g_return_if_fail (group->description != NULL);
583 g_return_if_fail (group->help_description != NULL);
585 for (list = context->groups; list; list = list->next)
587 GOptionGroup *g = (GOptionGroup *)list->data;
589 if ((group->name == NULL && g->name == NULL) ||
590 (group->name && g->name && strcmp (group->name, g->name) == 0))
591 g_warning ("A group named \"%s\" is already part of this GOptionContext",
595 context->groups = g_list_append (context->groups, group);
599 * g_option_context_set_main_group:
600 * @context: a #GOptionContext
601 * @group: (transfer full): the group to set as main group
603 * Sets a #GOptionGroup as main group of the @context.
604 * This has the same effect as calling g_option_context_add_group(),
605 * the only difference is that the options in the main group are
606 * treated differently when generating `--help` output.
611 g_option_context_set_main_group (GOptionContext *context,
614 g_return_if_fail (context != NULL);
615 g_return_if_fail (group != NULL);
617 if (context->main_group)
619 g_warning ("This GOptionContext already has a main group");
624 context->main_group = group;
628 * g_option_context_get_main_group:
629 * @context: a #GOptionContext
631 * Returns a pointer to the main group of @context.
633 * Returns: (transfer none): the main group of @context, or %NULL if
634 * @context doesn't have a main group. Note that group belongs to
635 * @context and should not be modified or freed.
640 g_option_context_get_main_group (GOptionContext *context)
642 g_return_val_if_fail (context != NULL, NULL);
644 return context->main_group;
648 * g_option_context_add_main_entries:
649 * @context: a #GOptionContext
650 * @entries: (array zero-terminated=1): a %NULL-terminated array of #GOptionEntrys
651 * @translation_domain: (nullable): a translation domain to use for translating
652 * the `--help` output for the options in @entries
653 * with gettext(), or %NULL
655 * A convenience function which creates a main group if it doesn't
656 * exist, adds the @entries to it and sets the translation domain.
661 g_option_context_add_main_entries (GOptionContext *context,
662 const GOptionEntry *entries,
663 const gchar *translation_domain)
665 g_return_if_fail (context != NULL);
666 g_return_if_fail (entries != NULL);
668 if (!context->main_group)
669 context->main_group = g_option_group_new (NULL, NULL, NULL, NULL, NULL);
671 g_option_group_add_entries (context->main_group, entries);
672 g_option_group_set_translation_domain (context->main_group, translation_domain);
676 calculate_max_length (GOptionGroup *group,
680 gsize i, len, max_length;
681 const gchar *long_name;
685 for (i = 0; i < group->n_entries; i++)
687 entry = &group->entries[i];
689 if (entry->flags & G_OPTION_FLAG_HIDDEN)
692 long_name = g_hash_table_lookup (aliases, &entry->long_name);
694 long_name = entry->long_name;
695 len = _g_utf8_strwidth (long_name);
697 if (entry->short_name)
700 if (!NO_ARG (entry) && entry->arg_description)
701 len += 1 + _g_utf8_strwidth (TRANSLATE (group, entry->arg_description));
703 max_length = MAX (max_length, len);
710 print_entry (GOptionGroup *group,
712 const GOptionEntry *entry,
717 const gchar *long_name;
719 if (entry->flags & G_OPTION_FLAG_HIDDEN)
722 if (entry->long_name[0] == 0)
725 long_name = g_hash_table_lookup (aliases, &entry->long_name);
727 long_name = entry->long_name;
729 str = g_string_new (NULL);
731 if (entry->short_name)
732 g_string_append_printf (str, " -%c, --%s", entry->short_name, long_name);
734 g_string_append_printf (str, " --%s", long_name);
736 if (entry->arg_description)
737 g_string_append_printf (str, "=%s", TRANSLATE (group, entry->arg_description));
739 g_string_append_printf (string, "%s%*s %s\n", str->str,
740 (int) (max_length + 4 - _g_utf8_strwidth (str->str)), "",
741 entry->description ? TRANSLATE (group, entry->description) : "");
742 g_string_free (str, TRUE);
746 group_has_visible_entries (GOptionContext *context,
748 gboolean main_entries)
750 GOptionFlags reject_filter = G_OPTION_FLAG_HIDDEN;
753 gboolean main_group = group == context->main_group;
756 reject_filter |= G_OPTION_FLAG_IN_MAIN;
758 for (i = 0, l = (group ? group->n_entries : 0); i < l; i++)
760 entry = &group->entries[i];
762 if (main_entries && !main_group && !(entry->flags & G_OPTION_FLAG_IN_MAIN))
764 if (entry->long_name[0] == 0) /* ignore rest entry */
766 if (!(entry->flags & reject_filter))
774 group_list_has_visible_entries (GOptionContext *context,
776 gboolean main_entries)
780 if (group_has_visible_entries (context, group_list->data, main_entries))
783 group_list = group_list->next;
790 context_has_h_entry (GOptionContext *context)
795 if (context->main_group)
797 for (i = 0; i < context->main_group->n_entries; i++)
799 if (context->main_group->entries[i].short_name == 'h')
804 for (list = context->groups; list != NULL; list = g_list_next (list))
808 group = (GOptionGroup*)list->data;
809 for (i = 0; i < group->n_entries; i++)
811 if (group->entries[i].short_name == 'h')
819 * g_option_context_get_help:
820 * @context: a #GOptionContext
821 * @main_help: if %TRUE, only include the main group
822 * @group: (nullable): the #GOptionGroup to create help for, or %NULL
824 * Returns a formatted, translated help text for the given context.
825 * To obtain the text produced by `--help`, call
826 * `g_option_context_get_help (context, TRUE, NULL)`.
827 * To obtain the text produced by `--help-all`, call
828 * `g_option_context_get_help (context, FALSE, NULL)`.
829 * To obtain the help text for an option group, call
830 * `g_option_context_get_help (context, FALSE, group)`.
832 * Returns: A newly allocated string containing the help text
837 g_option_context_get_help (GOptionContext *context,
842 gint max_length = 0, len;
845 GHashTable *shadow_map;
848 const gchar *rest_description;
852 g_return_val_if_fail (context != NULL, NULL);
854 string = g_string_sized_new (1024);
856 rest_description = NULL;
857 if (context->main_group)
860 for (i = 0; i < context->main_group->n_entries; i++)
862 entry = &context->main_group->entries[i];
863 if (entry->long_name[0] == 0)
865 rest_description = TRANSLATE (context->main_group, entry->arg_description);
871 g_string_append_printf (string, "%s\n %s", _("Usage:"), g_get_prgname ());
872 if (context->help_enabled ||
873 (context->main_group && context->main_group->n_entries > 0) ||
874 context->groups != NULL)
875 g_string_append_printf (string, " %s", _("[OPTION…]"));
877 if (rest_description)
879 g_string_append (string, " ");
880 g_string_append (string, rest_description);
883 if (context->parameter_string)
885 g_string_append (string, " ");
886 g_string_append (string, TRANSLATE (context, context->parameter_string));
889 g_string_append (string, "\n\n");
891 if (context->summary)
893 g_string_append (string, TRANSLATE (context, context->summary));
894 g_string_append (string, "\n\n");
897 memset (seen, 0, sizeof (gboolean) * 256);
898 shadow_map = g_hash_table_new (g_str_hash, g_str_equal);
899 aliases = g_hash_table_new_full (NULL, NULL, NULL, g_free);
901 if (context->main_group)
903 for (i = 0; i < context->main_group->n_entries; i++)
905 entry = &context->main_group->entries[i];
906 g_hash_table_insert (shadow_map,
907 (gpointer)entry->long_name,
910 if (seen[(guchar)entry->short_name])
911 entry->short_name = 0;
913 seen[(guchar)entry->short_name] = TRUE;
917 list = context->groups;
920 GOptionGroup *g = list->data;
921 for (i = 0; i < g->n_entries; i++)
923 entry = &g->entries[i];
924 if (g_hash_table_lookup (shadow_map, entry->long_name) &&
925 !(entry->flags & G_OPTION_FLAG_NOALIAS))
927 g_hash_table_insert (aliases, &entry->long_name,
928 g_strdup_printf ("%s-%s", g->name, entry->long_name));
931 g_hash_table_insert (shadow_map, (gpointer)entry->long_name, entry);
933 if (seen[(guchar)entry->short_name] &&
934 !(entry->flags & G_OPTION_FLAG_NOALIAS))
935 entry->short_name = 0;
937 seen[(guchar)entry->short_name] = TRUE;
942 g_hash_table_destroy (shadow_map);
944 list = context->groups;
946 if (context->help_enabled)
948 max_length = _g_utf8_strwidth ("-?, --help");
952 len = _g_utf8_strwidth ("--help-all");
953 max_length = MAX (max_length, len);
957 if (context->main_group)
959 len = calculate_max_length (context->main_group, aliases);
960 max_length = MAX (max_length, len);
965 GOptionGroup *g = list->data;
967 if (context->help_enabled)
969 /* First, we check the --help-<groupname> options */
970 len = _g_utf8_strwidth ("--help-") + _g_utf8_strwidth (g->name);
971 max_length = MAX (max_length, len);
974 /* Then we go through the entries */
975 len = calculate_max_length (g, aliases);
976 max_length = MAX (max_length, len);
981 /* Add a bit of padding */
984 if (!group && context->help_enabled)
986 list = context->groups;
988 token = context_has_h_entry (context) ? '?' : 'h';
990 g_string_append_printf (string, "%s\n -%c, --%-*s %s\n",
991 _("Help Options:"), token, max_length - 4, "help",
992 _("Show help options"));
994 /* We only want --help-all when there are groups */
996 g_string_append_printf (string, " --%-*s %s\n",
997 max_length, "help-all",
998 _("Show all help options"));
1002 GOptionGroup *g = list->data;
1004 if (group_has_visible_entries (context, g, FALSE))
1005 g_string_append_printf (string, " --help-%-*s %s\n",
1006 max_length - 5, g->name,
1007 TRANSLATE (g, g->help_description));
1012 g_string_append (string, "\n");
1017 /* Print a certain group */
1019 if (group_has_visible_entries (context, group, FALSE))
1021 g_string_append (string, TRANSLATE (group, group->description));
1022 g_string_append (string, "\n");
1023 for (i = 0; i < group->n_entries; i++)
1024 print_entry (group, max_length, &group->entries[i], string, aliases);
1025 g_string_append (string, "\n");
1028 else if (!main_help)
1030 /* Print all groups */
1032 list = context->groups;
1036 GOptionGroup *g = list->data;
1038 if (group_has_visible_entries (context, g, FALSE))
1040 g_string_append (string, g->description);
1041 g_string_append (string, "\n");
1042 for (i = 0; i < g->n_entries; i++)
1043 if (!(g->entries[i].flags & G_OPTION_FLAG_IN_MAIN))
1044 print_entry (g, max_length, &g->entries[i], string, aliases);
1046 g_string_append (string, "\n");
1053 /* Print application options if --help or --help-all has been specified */
1054 if ((main_help || !group) &&
1055 (group_has_visible_entries (context, context->main_group, TRUE) ||
1056 group_list_has_visible_entries (context, context->groups, TRUE)))
1058 list = context->groups;
1060 if (context->help_enabled || list)
1061 g_string_append (string, _("Application Options:"));
1063 g_string_append (string, _("Options:"));
1064 g_string_append (string, "\n");
1065 if (context->main_group)
1066 for (i = 0; i < context->main_group->n_entries; i++)
1067 print_entry (context->main_group, max_length,
1068 &context->main_group->entries[i], string, aliases);
1070 while (list != NULL)
1072 GOptionGroup *g = list->data;
1074 /* Print main entries from other groups */
1075 for (i = 0; i < g->n_entries; i++)
1076 if (g->entries[i].flags & G_OPTION_FLAG_IN_MAIN)
1077 print_entry (g, max_length, &g->entries[i], string, aliases);
1082 g_string_append (string, "\n");
1085 if (context->description)
1087 g_string_append (string, TRANSLATE (context, context->description));
1088 g_string_append (string, "\n");
1091 g_hash_table_destroy (aliases);
1093 return g_string_free (string, FALSE);
1098 print_help (GOptionContext *context,
1100 GOptionGroup *group)
1104 help = g_option_context_get_help (context, main_help, group);
1105 g_print ("%s", help);
1112 parse_int (const gchar *arg_name,
1121 tmp = strtol (arg, &end, 0);
1123 if (*arg == '\0' || *end != '\0')
1126 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1127 _("Cannot parse integer value “%s” for %s"),
1133 if (*result != tmp || errno == ERANGE)
1136 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1137 _("Integer value “%s” for %s out of range"),
1147 parse_double (const gchar *arg_name,
1156 tmp = g_strtod (arg, &end);
1158 if (*arg == '\0' || *end != '\0')
1161 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1162 _("Cannot parse double value “%s” for %s"),
1166 if (errno == ERANGE)
1169 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1170 _("Double value “%s” for %s out of range"),
1182 parse_int64 (const gchar *arg_name,
1191 tmp = g_ascii_strtoll (arg, &end, 0);
1193 if (*arg == '\0' || *end != '\0')
1196 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1197 _("Cannot parse integer value “%s” for %s"),
1201 if (errno == ERANGE)
1204 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1205 _("Integer value “%s” for %s out of range"),
1217 get_change (GOptionContext *context,
1218 GOptionArg arg_type,
1222 Change *change = NULL;
1224 for (list = context->changes; list != NULL; list = list->next)
1226 change = list->data;
1228 if (change->arg_data == arg_data)
1232 change = g_new0 (Change, 1);
1233 change->arg_type = arg_type;
1234 change->arg_data = arg_data;
1236 context->changes = g_list_prepend (context->changes, change);
1244 add_pending_null (GOptionContext *context,
1250 n = g_new0 (PendingNull, 1);
1254 context->pending_nulls = g_list_prepend (context->pending_nulls, n);
1258 parse_arg (GOptionContext *context,
1259 GOptionGroup *group,
1260 GOptionEntry *entry,
1262 const gchar *option_name,
1268 g_assert (value || OPTIONAL_ARG (entry) || NO_ARG (entry));
1272 case G_OPTION_ARG_NONE:
1274 (void) get_change (context, G_OPTION_ARG_NONE,
1277 *(gboolean *)entry->arg_data = !(entry->flags & G_OPTION_FLAG_REVERSE);
1280 case G_OPTION_ARG_STRING:
1285 if (!context->strv_mode)
1286 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1288 data = g_strdup (value);
1290 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1296 change = get_change (context, G_OPTION_ARG_STRING,
1299 if (!change->allocated.str)
1300 change->prev.str = *(gchar **)entry->arg_data;
1302 g_free (change->allocated.str);
1304 change->allocated.str = data;
1306 *(gchar **)entry->arg_data = data;
1309 case G_OPTION_ARG_STRING_ARRAY:
1314 if (!context->strv_mode)
1315 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1317 data = g_strdup (value);
1319 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1325 change = get_change (context, G_OPTION_ARG_STRING_ARRAY,
1328 if (change->allocated.array.len == 0)
1330 change->prev.array = *(gchar ***)entry->arg_data;
1331 change->allocated.array.data = g_new (gchar *, 2);
1334 change->allocated.array.data =
1335 g_renew (gchar *, change->allocated.array.data,
1336 change->allocated.array.len + 2);
1338 change->allocated.array.data[change->allocated.array.len] = data;
1339 change->allocated.array.data[change->allocated.array.len + 1] = NULL;
1341 change->allocated.array.len ++;
1343 *(gchar ***)entry->arg_data = change->allocated.array.data;
1348 case G_OPTION_ARG_FILENAME:
1353 if (!context->strv_mode)
1354 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1356 data = g_strdup (value);
1361 data = g_strdup (value);
1363 change = get_change (context, G_OPTION_ARG_FILENAME,
1366 if (!change->allocated.str)
1367 change->prev.str = *(gchar **)entry->arg_data;
1369 g_free (change->allocated.str);
1371 change->allocated.str = data;
1373 *(gchar **)entry->arg_data = data;
1377 case G_OPTION_ARG_FILENAME_ARRAY:
1382 if (!context->strv_mode)
1383 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1385 data = g_strdup (value);
1390 data = g_strdup (value);
1392 change = get_change (context, G_OPTION_ARG_STRING_ARRAY,
1395 if (change->allocated.array.len == 0)
1397 change->prev.array = *(gchar ***)entry->arg_data;
1398 change->allocated.array.data = g_new (gchar *, 2);
1401 change->allocated.array.data =
1402 g_renew (gchar *, change->allocated.array.data,
1403 change->allocated.array.len + 2);
1405 change->allocated.array.data[change->allocated.array.len] = data;
1406 change->allocated.array.data[change->allocated.array.len + 1] = NULL;
1408 change->allocated.array.len ++;
1410 *(gchar ***)entry->arg_data = change->allocated.array.data;
1415 case G_OPTION_ARG_INT:
1419 if (!parse_int (option_name, value,
1424 change = get_change (context, G_OPTION_ARG_INT,
1426 change->prev.integer = *(gint *)entry->arg_data;
1427 *(gint *)entry->arg_data = data;
1430 case G_OPTION_ARG_CALLBACK:
1435 if (!value && entry->flags & G_OPTION_FLAG_OPTIONAL_ARG)
1437 else if (entry->flags & G_OPTION_FLAG_NO_ARG)
1439 else if (entry->flags & G_OPTION_FLAG_FILENAME)
1442 if (!context->strv_mode)
1443 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1445 data = g_strdup (value);
1447 data = g_strdup (value);
1451 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1453 if (!(entry->flags & (G_OPTION_FLAG_NO_ARG|G_OPTION_FLAG_OPTIONAL_ARG)) &&
1457 retval = (* (GOptionArgFunc) entry->arg_data) (option_name, data, group->user_data, error);
1459 if (!retval && error != NULL && *error == NULL)
1461 G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
1462 _("Error parsing option %s"), option_name);
1470 case G_OPTION_ARG_DOUBLE:
1474 if (!parse_double (option_name, value,
1481 change = get_change (context, G_OPTION_ARG_DOUBLE,
1483 change->prev.dbl = *(gdouble *)entry->arg_data;
1484 *(gdouble *)entry->arg_data = data;
1487 case G_OPTION_ARG_INT64:
1491 if (!parse_int64 (option_name, value,
1498 change = get_change (context, G_OPTION_ARG_INT64,
1500 change->prev.int64 = *(gint64 *)entry->arg_data;
1501 *(gint64 *)entry->arg_data = data;
1505 g_assert_not_reached ();
1512 parse_short_option (GOptionContext *context,
1513 GOptionGroup *group,
1524 for (j = 0; j < group->n_entries; j++)
1526 if (arg == group->entries[j].short_name)
1529 gchar *value = NULL;
1531 option_name = g_strdup_printf ("-%c", group->entries[j].short_name);
1533 if (NO_ARG (&group->entries[j]))
1540 G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
1541 _("Error parsing option %s"), option_name);
1542 g_free (option_name);
1546 if (idx < *argc - 1)
1548 if (OPTIONAL_ARG (&group->entries[j]) && ((*argv)[idx + 1][0] == '-'))
1552 value = (*argv)[idx + 1];
1553 add_pending_null (context, &((*argv)[idx + 1]), NULL);
1557 else if (idx >= *argc - 1 && OPTIONAL_ARG (&group->entries[j]))
1562 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1563 _("Missing argument for %s"), option_name);
1564 g_free (option_name);
1569 if (!parse_arg (context, group, &group->entries[j],
1570 value, option_name, error))
1572 g_free (option_name);
1576 g_free (option_name);
1585 parse_long_option (GOptionContext *context,
1586 GOptionGroup *group,
1597 for (j = 0; j < group->n_entries; j++)
1602 if (aliased && (group->entries[j].flags & G_OPTION_FLAG_NOALIAS))
1605 if (NO_ARG (&group->entries[j]) &&
1606 strcmp (arg, group->entries[j].long_name) == 0)
1611 option_name = g_strconcat ("--", group->entries[j].long_name, NULL);
1612 retval = parse_arg (context, group, &group->entries[j],
1613 NULL, option_name, error);
1614 g_free (option_name);
1616 add_pending_null (context, &((*argv)[*idx]), NULL);
1623 gint len = strlen (group->entries[j].long_name);
1625 if (strncmp (arg, group->entries[j].long_name, len) == 0 &&
1626 (arg[len] == '=' || arg[len] == 0))
1628 gchar *value = NULL;
1631 add_pending_null (context, &((*argv)[*idx]), NULL);
1632 option_name = g_strconcat ("--", group->entries[j].long_name, NULL);
1634 if (arg[len] == '=')
1635 value = arg + len + 1;
1636 else if (*idx < *argc - 1)
1638 if (!OPTIONAL_ARG (&group->entries[j]))
1640 value = (*argv)[*idx + 1];
1641 add_pending_null (context, &((*argv)[*idx + 1]), NULL);
1646 if ((*argv)[*idx + 1][0] == '-')
1649 retval = parse_arg (context, group, &group->entries[j],
1650 NULL, option_name, error);
1652 g_free (option_name);
1657 value = (*argv)[*idx + 1];
1658 add_pending_null (context, &((*argv)[*idx + 1]), NULL);
1663 else if (*idx >= *argc - 1 && OPTIONAL_ARG (&group->entries[j]))
1666 retval = parse_arg (context, group, &group->entries[j],
1667 NULL, option_name, error);
1669 g_free (option_name);
1675 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1676 _("Missing argument for %s"), option_name);
1677 g_free (option_name);
1681 if (!parse_arg (context, group, &group->entries[j],
1682 value, option_name, error))
1684 g_free (option_name);
1688 g_free (option_name);
1698 parse_remaining_arg (GOptionContext *context,
1699 GOptionGroup *group,
1708 for (j = 0; j < group->n_entries; j++)
1713 if (group->entries[j].long_name[0])
1716 g_return_val_if_fail (group->entries[j].arg == G_OPTION_ARG_CALLBACK ||
1717 group->entries[j].arg == G_OPTION_ARG_STRING_ARRAY ||
1718 group->entries[j].arg == G_OPTION_ARG_FILENAME_ARRAY, FALSE);
1720 add_pending_null (context, &((*argv)[*idx]), NULL);
1722 if (!parse_arg (context, group, &group->entries[j], (*argv)[*idx], "", error))
1733 free_changes_list (GOptionContext *context,
1738 for (list = context->changes; list != NULL; list = list->next)
1740 Change *change = list->data;
1744 switch (change->arg_type)
1746 case G_OPTION_ARG_NONE:
1747 *(gboolean *)change->arg_data = change->prev.bool;
1749 case G_OPTION_ARG_INT:
1750 *(gint *)change->arg_data = change->prev.integer;
1752 case G_OPTION_ARG_STRING:
1753 case G_OPTION_ARG_FILENAME:
1754 g_free (change->allocated.str);
1755 *(gchar **)change->arg_data = change->prev.str;
1757 case G_OPTION_ARG_STRING_ARRAY:
1758 case G_OPTION_ARG_FILENAME_ARRAY:
1759 g_strfreev (change->allocated.array.data);
1760 *(gchar ***)change->arg_data = change->prev.array;
1762 case G_OPTION_ARG_DOUBLE:
1763 *(gdouble *)change->arg_data = change->prev.dbl;
1765 case G_OPTION_ARG_INT64:
1766 *(gint64 *)change->arg_data = change->prev.int64;
1769 g_assert_not_reached ();
1776 g_list_free (context->changes);
1777 context->changes = NULL;
1781 free_pending_nulls (GOptionContext *context,
1782 gboolean perform_nulls)
1786 for (list = context->pending_nulls; list != NULL; list = list->next)
1788 PendingNull *n = list->data;
1794 /* Copy back the short options */
1796 strcpy (*n->ptr + 1, n->value);
1800 if (context->strv_mode)
1811 g_list_free (context->pending_nulls);
1812 context->pending_nulls = NULL;
1815 /* Use a platform-specific mechanism to look up the first argument to
1816 * the current process.
1817 * Note if you implement this for other platforms, also add it to
1818 * tests/option-argv0.c
1821 platform_get_argv0 (void)
1823 #ifdef HAVE_PROC_SELF_CMDLINE
1828 if (!g_file_get_contents ("/proc/self/cmdline",
1834 /* g_file_get_contents() guarantees to put a NUL immediately after the
1835 * file's contents (at cmdline[len] here), even if the file itself was
1836 * not NUL-terminated. */
1837 g_assert (memchr (cmdline, 0, len + 1));
1839 /* We could just return cmdline, but I think it's better
1840 * to hold on to a smaller malloc block; the arguments
1843 base_arg0 = g_path_get_basename (cmdline);
1846 #elif defined __OpenBSD__
1851 int mib[] = { CTL_KERN, KERN_PROC_ARGS, getpid(), KERN_PROC_ARGV };
1853 if (sysctl (mib, G_N_ELEMENTS (mib), NULL, &len, NULL, 0) == -1)
1856 cmdline = g_malloc0 (len);
1858 if (sysctl (mib, G_N_ELEMENTS (mib), cmdline, &len, NULL, 0) == -1)
1864 /* We could just return cmdline, but I think it's better
1865 * to hold on to a smaller malloc block; the arguments
1868 base_arg0 = g_path_get_basename (*cmdline);
1871 #elif defined G_OS_WIN32
1872 const wchar_t *cmdline;
1875 gchar *utf8_buf = NULL;
1876 char *base_arg0 = NULL;
1878 /* Pretend it's const, since we're not allowed to free it */
1879 cmdline = (const wchar_t *) GetCommandLineW ();
1880 if (G_UNLIKELY (cmdline == NULL))
1883 /* Skip leading whitespace. CommandLineToArgvW() is documented
1884 * to behave weirdly with that. The character codes below
1885 * correspond to the *only* unicode characters that are
1886 * considered to be spaces by CommandLineToArgvW(). The rest
1887 * (such as 0xa0 - NO-BREAK SPACE) are treated as
1888 * normal characters.
1890 while (cmdline[0] == 0x09 ||
1891 cmdline[0] == 0x0a ||
1892 cmdline[0] == 0x0c ||
1893 cmdline[0] == 0x0d ||
1897 wargv = CommandLineToArgvW (cmdline, &wargc);
1898 if (G_UNLIKELY (wargv == NULL))
1902 utf8_buf = g_utf16_to_utf8 (wargv[0], -1, NULL, NULL, NULL);
1906 if (G_UNLIKELY (utf8_buf == NULL))
1909 /* We could just return cmdline, but I think it's better
1910 * to hold on to a smaller malloc block; the arguments
1913 base_arg0 = g_path_get_basename (utf8_buf);
1922 * g_option_context_parse:
1923 * @context: a #GOptionContext
1924 * @argc: (inout) (optional): a pointer to the number of command line arguments
1925 * @argv: (inout) (array length=argc) (optional): a pointer to the array of command line arguments
1926 * @error: a return location for errors
1928 * Parses the command line arguments, recognizing options
1929 * which have been added to @context. A side-effect of
1930 * calling this function is that g_set_prgname() will be
1933 * If the parsing is successful, any parsed arguments are
1934 * removed from the array and @argc and @argv are updated
1935 * accordingly. A '--' option is stripped from @argv
1936 * unless there are unparsed options before and after it,
1937 * or some of the options after it start with '-'. In case
1938 * of an error, @argc and @argv are left unmodified.
1940 * If automatic `--help` support is enabled
1941 * (see g_option_context_set_help_enabled()), and the
1942 * @argv array contains one of the recognized help options,
1943 * this function will produce help output to stdout and
1946 * Note that function depends on the [current locale][setlocale] for
1947 * automatic character set conversion of string and filename
1950 * Returns: %TRUE if the parsing was successful,
1951 * %FALSE if an error occurred
1956 g_option_context_parse (GOptionContext *context,
1964 g_return_val_if_fail (context != NULL, FALSE);
1966 /* Set program name */
1967 if (!g_get_prgname())
1971 if (argc && argv && *argc)
1972 prgname = g_path_get_basename ((*argv)[0]);
1974 prgname = platform_get_argv0 ();
1977 g_set_prgname (prgname);
1979 g_set_prgname ("<unknown>");
1984 /* Call pre-parse hooks */
1985 list = context->groups;
1988 GOptionGroup *group = list->data;
1990 if (group->pre_parse_func)
1992 if (!(* group->pre_parse_func) (context, group,
1993 group->user_data, error))
2000 if (context->main_group && context->main_group->pre_parse_func)
2002 if (!(* context->main_group->pre_parse_func) (context, context->main_group,
2003 context->main_group->user_data, error))
2009 gboolean stop_parsing = FALSE;
2010 gboolean has_unknown = FALSE;
2011 gint separator_pos = 0;
2013 for (i = 1; i < *argc; i++)
2016 gboolean parsed = FALSE;
2018 if ((*argv)[i][0] == '-' && (*argv)[i][1] != '\0' && !stop_parsing)
2020 if ((*argv)[i][1] == '-')
2024 arg = (*argv)[i] + 2;
2026 /* '--' terminates list of arguments */
2030 stop_parsing = TRUE;
2034 /* Handle help options */
2035 if (context->help_enabled)
2037 if (strcmp (arg, "help") == 0)
2038 print_help (context, TRUE, NULL);
2039 else if (strcmp (arg, "help-all") == 0)
2040 print_help (context, FALSE, NULL);
2041 else if (strncmp (arg, "help-", 5) == 0)
2043 list = context->groups;
2047 GOptionGroup *group = list->data;
2049 if (strcmp (arg + 5, group->name) == 0)
2050 print_help (context, FALSE, group);
2057 if (context->main_group &&
2058 !parse_long_option (context, context->main_group, &i, arg,
2059 FALSE, argc, argv, error, &parsed))
2065 /* Try the groups */
2066 list = context->groups;
2069 GOptionGroup *group = list->data;
2071 if (!parse_long_option (context, group, &i, arg,
2072 FALSE, argc, argv, error, &parsed))
2084 /* Now look for --<group>-<option> */
2085 dash = strchr (arg, '-');
2086 if (dash && arg < dash)
2088 /* Try the groups */
2089 list = context->groups;
2092 GOptionGroup *group = list->data;
2094 if (strncmp (group->name, arg, dash - arg) == 0)
2096 if (!parse_long_option (context, group, &i, dash + 1,
2097 TRUE, argc, argv, error, &parsed))
2108 if (context->ignore_unknown)
2112 { /* short option */
2113 gint new_i = i, arg_length;
2114 gboolean *nulled_out = NULL;
2115 gboolean has_h_entry = context_has_h_entry (context);
2116 arg = (*argv)[i] + 1;
2117 arg_length = strlen (arg);
2118 nulled_out = g_newa0 (gboolean, arg_length);
2119 for (j = 0; j < arg_length; j++)
2121 if (context->help_enabled && (arg[j] == '?' ||
2122 (arg[j] == 'h' && !has_h_entry)))
2123 print_help (context, TRUE, NULL);
2125 if (context->main_group &&
2126 !parse_short_option (context, context->main_group,
2128 argc, argv, error, &parsed))
2132 /* Try the groups */
2133 list = context->groups;
2136 GOptionGroup *group = list->data;
2137 if (!parse_short_option (context, group, i, &new_i, arg[j],
2138 argc, argv, error, &parsed))
2146 if (context->ignore_unknown && parsed)
2147 nulled_out[j] = TRUE;
2148 else if (context->ignore_unknown)
2152 /* !context->ignore_unknown && parsed */
2154 if (context->ignore_unknown)
2156 gchar *new_arg = NULL;
2158 for (j = 0; j < arg_length; j++)
2163 new_arg = g_malloc (arg_length + 1);
2164 new_arg[arg_index++] = arg[j];
2168 new_arg[arg_index] = '\0';
2169 add_pending_null (context, &((*argv)[i]), new_arg);
2174 add_pending_null (context, &((*argv)[i]), NULL);
2182 if (!parsed && !context->ignore_unknown)
2185 G_OPTION_ERROR, G_OPTION_ERROR_UNKNOWN_OPTION,
2186 _("Unknown option %s"), (*argv)[i]);
2192 if (context->strict_posix)
2193 stop_parsing = TRUE;
2195 /* Collect remaining args */
2196 if (context->main_group &&
2197 !parse_remaining_arg (context, context->main_group, &i,
2198 argc, argv, error, &parsed))
2201 if (!parsed && (has_unknown || (*argv)[i][0] == '-'))
2206 if (separator_pos > 0)
2207 add_pending_null (context, &((*argv)[separator_pos]), NULL);
2211 /* Call post-parse hooks */
2212 list = context->groups;
2215 GOptionGroup *group = list->data;
2217 if (group->post_parse_func)
2219 if (!(* group->post_parse_func) (context, group,
2220 group->user_data, error))
2227 if (context->main_group && context->main_group->post_parse_func)
2229 if (!(* context->main_group->post_parse_func) (context, context->main_group,
2230 context->main_group->user_data, error))
2236 free_pending_nulls (context, TRUE);
2238 for (i = 1; i < *argc; i++)
2240 for (k = i; k < *argc; k++)
2241 if ((*argv)[k] != NULL)
2247 for (j = i + k; j < *argc; j++)
2249 (*argv)[j-k] = (*argv)[j];
2261 /* Call error hooks */
2262 list = context->groups;
2265 GOptionGroup *group = list->data;
2267 if (group->error_func)
2268 (* group->error_func) (context, group,
2269 group->user_data, error);
2274 if (context->main_group && context->main_group->error_func)
2275 (* context->main_group->error_func) (context, context->main_group,
2276 context->main_group->user_data, error);
2278 free_changes_list (context, TRUE);
2279 free_pending_nulls (context, FALSE);
2285 * g_option_group_new:
2286 * @name: the name for the option group, this is used to provide
2287 * help for the options in this group with `--help-`@name
2288 * @description: a description for this group to be shown in
2289 * `--help`. This string is translated using the translation
2290 * domain or translation function of the group
2291 * @help_description: a description for the `--help-`@name option.
2292 * This string is translated using the translation domain or translation function
2294 * @user_data: (nullable): user data that will be passed to the pre- and post-parse hooks,
2295 * the error hook and to callbacks of %G_OPTION_ARG_CALLBACK options, or %NULL
2296 * @destroy: (nullable): a function that will be called to free @user_data, or %NULL
2298 * Creates a new #GOptionGroup.
2300 * Returns: a newly created option group. It should be added
2301 * to a #GOptionContext or freed with g_option_group_unref().
2306 g_option_group_new (const gchar *name,
2307 const gchar *description,
2308 const gchar *help_description,
2310 GDestroyNotify destroy)
2313 GOptionGroup *group;
2315 group = g_new0 (GOptionGroup, 1);
2316 group->ref_count = 1;
2317 group->name = g_strdup (name);
2318 group->description = g_strdup (description);
2319 group->help_description = g_strdup (help_description);
2320 group->user_data = user_data;
2321 group->destroy_notify = destroy;
2328 * g_option_group_free:
2329 * @group: a #GOptionGroup
2331 * Frees a #GOptionGroup. Note that you must not free groups
2332 * which have been added to a #GOptionContext.
2336 * Deprecated: 2.44: Use g_option_group_unref() instead.
2339 g_option_group_free (GOptionGroup *group)
2341 g_option_group_unref (group);
2345 * g_option_group_ref:
2346 * @group: a #GOptionGroup
2348 * Increments the reference count of @group by one.
2350 * Returns: a #GOptionGroup
2355 g_option_group_ref (GOptionGroup *group)
2357 g_return_val_if_fail (group != NULL, NULL);
2365 * g_option_group_unref:
2366 * @group: a #GOptionGroup
2368 * Decrements the reference count of @group by one.
2369 * If the reference count drops to 0, the @group will be freed.
2370 * and all memory allocated by the @group is released.
2375 g_option_group_unref (GOptionGroup *group)
2377 g_return_if_fail (group != NULL);
2379 if (--group->ref_count == 0)
2381 g_free (group->name);
2382 g_free (group->description);
2383 g_free (group->help_description);
2385 g_free (group->entries);
2387 if (group->destroy_notify)
2388 (* group->destroy_notify) (group->user_data);
2390 if (group->translate_notify)
2391 (* group->translate_notify) (group->translate_data);
2398 * g_option_group_add_entries:
2399 * @group: a #GOptionGroup
2400 * @entries: (array zero-terminated=1): a %NULL-terminated array of #GOptionEntrys
2402 * Adds the options specified in @entries to @group.
2407 g_option_group_add_entries (GOptionGroup *group,
2408 const GOptionEntry *entries)
2412 g_return_if_fail (group != NULL);
2413 g_return_if_fail (entries != NULL);
2415 for (n_entries = 0; entries[n_entries].long_name != NULL; n_entries++) ;
2417 g_return_if_fail (n_entries <= G_MAXSIZE - group->n_entries);
2419 group->entries = g_renew (GOptionEntry, group->entries, group->n_entries + n_entries);
2421 /* group->entries could be NULL in the trivial case where we add no
2422 * entries to no entries */
2424 memcpy (group->entries + group->n_entries, entries, sizeof (GOptionEntry) * n_entries);
2426 for (i = group->n_entries; i < group->n_entries + n_entries; i++)
2428 gchar c = group->entries[i].short_name;
2430 if (c == '-' || (c != 0 && !g_ascii_isprint (c)))
2432 g_warning (G_STRLOC ": ignoring invalid short option '%c' (%d) in entry %s:%s",
2433 c, c, group->name, group->entries[i].long_name);
2434 group->entries[i].short_name = '\0';
2437 if (group->entries[i].arg != G_OPTION_ARG_NONE &&
2438 (group->entries[i].flags & G_OPTION_FLAG_REVERSE) != 0)
2440 g_warning (G_STRLOC ": ignoring reverse flag on option of arg-type %d in entry %s:%s",
2441 group->entries[i].arg, group->name, group->entries[i].long_name);
2443 group->entries[i].flags &= ~G_OPTION_FLAG_REVERSE;
2446 if (group->entries[i].arg != G_OPTION_ARG_CALLBACK &&
2447 (group->entries[i].flags & (G_OPTION_FLAG_NO_ARG|G_OPTION_FLAG_OPTIONAL_ARG|G_OPTION_FLAG_FILENAME)) != 0)
2449 g_warning (G_STRLOC ": ignoring no-arg, optional-arg or filename flags (%d) on option of arg-type %d in entry %s:%s",
2450 group->entries[i].flags, group->entries[i].arg, group->name, group->entries[i].long_name);
2452 group->entries[i].flags &= ~(G_OPTION_FLAG_NO_ARG|G_OPTION_FLAG_OPTIONAL_ARG|G_OPTION_FLAG_FILENAME);
2456 group->n_entries += n_entries;
2460 * g_option_group_set_parse_hooks:
2461 * @group: a #GOptionGroup
2462 * @pre_parse_func: (nullable): a function to call before parsing, or %NULL
2463 * @post_parse_func: (nullable): a function to call after parsing, or %NULL
2465 * Associates two functions with @group which will be called
2466 * from g_option_context_parse() before the first option is parsed
2467 * and after the last option has been parsed, respectively.
2469 * Note that the user data to be passed to @pre_parse_func and
2470 * @post_parse_func can be specified when constructing the group
2471 * with g_option_group_new().
2476 g_option_group_set_parse_hooks (GOptionGroup *group,
2477 GOptionParseFunc pre_parse_func,
2478 GOptionParseFunc post_parse_func)
2480 g_return_if_fail (group != NULL);
2482 group->pre_parse_func = pre_parse_func;
2483 group->post_parse_func = post_parse_func;
2487 * g_option_group_set_error_hook:
2488 * @group: a #GOptionGroup
2489 * @error_func: a function to call when an error occurs
2491 * Associates a function with @group which will be called
2492 * from g_option_context_parse() when an error occurs.
2494 * Note that the user data to be passed to @error_func can be
2495 * specified when constructing the group with g_option_group_new().
2500 g_option_group_set_error_hook (GOptionGroup *group,
2501 GOptionErrorFunc error_func)
2503 g_return_if_fail (group != NULL);
2505 group->error_func = error_func;
2510 * g_option_group_set_translate_func:
2511 * @group: a #GOptionGroup
2512 * @func: (nullable): the #GTranslateFunc, or %NULL
2513 * @data: (nullable): user data to pass to @func, or %NULL
2514 * @destroy_notify: (nullable): a function which gets called to free @data, or %NULL
2516 * Sets the function which is used to translate user-visible strings,
2517 * for `--help` output. Different groups can use different
2518 * #GTranslateFuncs. If @func is %NULL, strings are not translated.
2520 * If you are using gettext(), you only need to set the translation
2521 * domain, see g_option_group_set_translation_domain().
2526 g_option_group_set_translate_func (GOptionGroup *group,
2527 GTranslateFunc func,
2529 GDestroyNotify destroy_notify)
2531 g_return_if_fail (group != NULL);
2533 if (group->translate_notify)
2534 group->translate_notify (group->translate_data);
2536 group->translate_func = func;
2537 group->translate_data = data;
2538 group->translate_notify = destroy_notify;
2541 static const gchar *
2542 dgettext_swapped (const gchar *msgid,
2543 const gchar *domainname)
2545 return g_dgettext (domainname, msgid);
2549 * g_option_group_set_translation_domain:
2550 * @group: a #GOptionGroup
2551 * @domain: the domain to use
2553 * A convenience function to use gettext() for translating
2554 * user-visible strings.
2559 g_option_group_set_translation_domain (GOptionGroup *group,
2560 const gchar *domain)
2562 g_return_if_fail (group != NULL);
2564 g_option_group_set_translate_func (group,
2565 (GTranslateFunc)dgettext_swapped,
2571 * g_option_context_set_translate_func:
2572 * @context: a #GOptionContext
2573 * @func: (nullable): the #GTranslateFunc, or %NULL
2574 * @data: (nullable): user data to pass to @func, or %NULL
2575 * @destroy_notify: (nullable): a function which gets called to free @data, or %NULL
2577 * Sets the function which is used to translate the contexts
2578 * user-visible strings, for `--help` output. If @func is %NULL,
2579 * strings are not translated.
2581 * Note that option groups have their own translation functions,
2582 * this function only affects the @parameter_string (see g_option_context_new()),
2583 * the summary (see g_option_context_set_summary()) and the description
2584 * (see g_option_context_set_description()).
2586 * If you are using gettext(), you only need to set the translation
2587 * domain, see g_option_context_set_translation_domain().
2592 g_option_context_set_translate_func (GOptionContext *context,
2593 GTranslateFunc func,
2595 GDestroyNotify destroy_notify)
2597 g_return_if_fail (context != NULL);
2599 if (context->translate_notify)
2600 context->translate_notify (context->translate_data);
2602 context->translate_func = func;
2603 context->translate_data = data;
2604 context->translate_notify = destroy_notify;
2608 * g_option_context_set_translation_domain:
2609 * @context: a #GOptionContext
2610 * @domain: the domain to use
2612 * A convenience function to use gettext() for translating
2613 * user-visible strings.
2618 g_option_context_set_translation_domain (GOptionContext *context,
2619 const gchar *domain)
2621 g_return_if_fail (context != NULL);
2623 g_option_context_set_translate_func (context,
2624 (GTranslateFunc)dgettext_swapped,
2630 * g_option_context_set_summary:
2631 * @context: a #GOptionContext
2632 * @summary: (nullable): a string to be shown in `--help` output
2633 * before the list of options, or %NULL
2635 * Adds a string to be displayed in `--help` output before the list
2636 * of options. This is typically a summary of the program functionality.
2638 * Note that the summary is translated (see
2639 * g_option_context_set_translate_func() and
2640 * g_option_context_set_translation_domain()).
2645 g_option_context_set_summary (GOptionContext *context,
2646 const gchar *summary)
2648 g_return_if_fail (context != NULL);
2650 g_free (context->summary);
2651 context->summary = g_strdup (summary);
2656 * g_option_context_get_summary:
2657 * @context: a #GOptionContext
2659 * Returns the summary. See g_option_context_set_summary().
2661 * Returns: the summary
2666 g_option_context_get_summary (GOptionContext *context)
2668 g_return_val_if_fail (context != NULL, NULL);
2670 return context->summary;
2674 * g_option_context_set_description:
2675 * @context: a #GOptionContext
2676 * @description: (nullable): a string to be shown in `--help` output
2677 * after the list of options, or %NULL
2679 * Adds a string to be displayed in `--help` output after the list
2680 * of options. This text often includes a bug reporting address.
2682 * Note that the summary is translated (see
2683 * g_option_context_set_translate_func()).
2688 g_option_context_set_description (GOptionContext *context,
2689 const gchar *description)
2691 g_return_if_fail (context != NULL);
2693 g_free (context->description);
2694 context->description = g_strdup (description);
2699 * g_option_context_get_description:
2700 * @context: a #GOptionContext
2702 * Returns the description. See g_option_context_set_description().
2704 * Returns: the description
2709 g_option_context_get_description (GOptionContext *context)
2711 g_return_val_if_fail (context != NULL, NULL);
2713 return context->description;
2717 * g_option_context_parse_strv:
2718 * @context: a #GOptionContext
2719 * @arguments: (inout) (array null-terminated=1) (optional): a pointer
2720 * to the command line arguments (which must be in UTF-8 on Windows).
2721 * Starting with GLib 2.62, @arguments can be %NULL, which matches
2722 * g_option_context_parse().
2723 * @error: a return location for errors
2725 * Parses the command line arguments.
2727 * This function is similar to g_option_context_parse() except that it
2728 * respects the normal memory rules when dealing with a strv instead of
2729 * assuming that the passed-in array is the argv of the main function.
2731 * In particular, strings that are removed from the arguments list will
2732 * be freed using g_free().
2734 * On Windows, the strings are expected to be in UTF-8. This is in
2735 * contrast to g_option_context_parse() which expects them to be in the
2736 * system codepage, which is how they are passed as @argv to main().
2737 * See g_win32_get_command_line() for a solution.
2739 * This function is useful if you are trying to use #GOptionContext with
2742 * Returns: %TRUE if the parsing was successful,
2743 * %FALSE if an error occurred
2748 g_option_context_parse_strv (GOptionContext *context,
2755 g_return_val_if_fail (context != NULL, FALSE);
2757 context->strv_mode = TRUE;
2758 argc = arguments && *arguments ? g_strv_length (*arguments) : 0;
2759 success = g_option_context_parse (context, &argc, arguments, error);
2760 context->strv_mode = FALSE;