1 /* goption.c - Option parser
3 * Copyright (C) 1999, 2003 Red Hat Software
4 * Copyright (C) 2004 Anders Carlsson <andersca@gnome.org>
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with this library; if not, see <http://www.gnu.org/licenses/>.
22 * @Short_description: parses commandline options
23 * @Title: Commandline option parser
25 * The GOption commandline parser is intended to be a simpler replacement
26 * for the popt library. It supports short and long commandline options,
27 * as shown in the following example:
29 * `testtreemodel -r 1 --max-size 20 --rand --display=:1.0 -vb -- file1 file2`
31 * The example demonstrates a number of features of the GOption
34 * - Options can be single letters, prefixed by a single dash.
36 * - Multiple short options can be grouped behind a single dash.
38 * - Long options are prefixed by two consecutive dashes.
40 * - Options can have an extra argument, which can be a number, a string or
41 * a filename. For long options, the extra argument can be appended with
42 * an equals sign after the option name, which is useful if the extra
43 * argument starts with a dash, which would otherwise cause it to be
44 * interpreted as another option.
46 * - Non-option arguments are returned to the application as rest arguments.
48 * - An argument consisting solely of two dashes turns off further parsing,
49 * any remaining arguments (even those starting with a dash) are returned
50 * to the application as rest arguments.
52 * Another important feature of GOption is that it can automatically
53 * generate nicely formatted help output. Unless it is explicitly turned
54 * off with g_option_context_set_help_enabled(), GOption will recognize
55 * the `--help`, `-?`, `--help-all` and `--help-groupname` options
56 * (where `groupname` is the name of a #GOptionGroup) and write a text
57 * similar to the one shown in the following example to stdout.
61 * testtreemodel [OPTION...] - test tree model performance
64 * -h, --help Show help options
65 * --help-all Show all help options
66 * --help-gtk Show GTK+ Options
68 * Application Options:
69 * -r, --repeats=N Average over N repetitions
70 * -m, --max-size=M Test up to 2^M items
71 * --display=DISPLAY X display to use
72 * -v, --verbose Be verbose
73 * -b, --beep Beep when done
74 * --rand Randomize the data
77 * GOption groups options in #GOptionGroups, which makes it easy to
78 * incorporate options from multiple sources. The intended use for this is
79 * to let applications collect option groups from the libraries it uses,
80 * add them to their #GOptionContext, and parse all options by a single call
81 * to g_option_context_parse(). See gtk_get_option_group() for an example.
83 * If an option is declared to be of type string or filename, GOption takes
84 * care of converting it to the right encoding; strings are returned in
85 * UTF-8, filenames are returned in the GLib filename encoding. Note that
86 * this only works if setlocale() has been called before
87 * g_option_context_parse().
89 * Here is a complete example of setting up GOption to parse the example
90 * commandline above and produce the example help output.
91 * |[<!-- language="C" -->
92 * static gint repeats = 2;
93 * static gint max_size = 8;
94 * static gboolean verbose = FALSE;
95 * static gboolean beep = FALSE;
96 * static gboolean randomize = FALSE;
98 * static GOptionEntry entries[] =
100 * { "repeats", 'r', 0, G_OPTION_ARG_INT, &repeats, "Average over N repetitions", "N" },
101 * { "max-size", 'm', 0, G_OPTION_ARG_INT, &max_size, "Test up to 2^M items", "M" },
102 * { "verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose, "Be verbose", NULL },
103 * { "beep", 'b', 0, G_OPTION_ARG_NONE, &beep, "Beep when done", NULL },
104 * { "rand", 0, 0, G_OPTION_ARG_NONE, &randomize, "Randomize the data", NULL },
109 * main (int argc, char *argv[])
111 * GError *error = NULL;
112 * GOptionContext *context;
114 * context = g_option_context_new ("- test tree model performance");
115 * g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
116 * g_option_context_add_group (context, gtk_get_option_group (TRUE));
117 * if (!g_option_context_parse (context, &argc, &argv, &error))
119 * g_print ("option parsing failed: %s\n", error->message);
128 * On UNIX systems, the argv that is passed to main() has no particular
129 * encoding, even to the extent that different parts of it may have
130 * different encodings. In general, normal arguments and flags will be
131 * in the current locale and filenames should be considered to be opaque
132 * byte strings. Proper use of %G_OPTION_ARG_FILENAME vs
133 * %G_OPTION_ARG_STRING is therefore important.
135 * Note that on Windows, filenames do have an encoding, but using
136 * #GOptionContext with the argv as passed to main() will result in a
137 * program that can only accept commandline arguments with characters
138 * from the system codepage. This can cause problems when attempting to
139 * deal with filenames containing Unicode characters that fall outside
142 * A solution to this is to use g_win32_get_command_line() and
143 * g_option_context_parse_strv() which will properly handle full Unicode
144 * filenames. If you are using #GApplication, this is done
145 * automatically for you.
147 * The following example shows how you can use #GOptionContext directly
148 * in order to correctly deal with Unicode filenames on Windows:
150 * |[<!-- language="C" -->
152 * main (int argc, char **argv)
154 * GError *error = NULL;
155 * GOptionContext *context;
159 * args = g_win32_get_command_line ();
161 * args = g_strdupv (argv);
166 * if (!g_option_context_parse_strv (context, &args, &error))
187 #if defined __OpenBSD__
189 #include <sys/sysctl.h>
195 #include "glibintl.h"
197 #if defined G_OS_WIN32
201 #define TRANSLATE(group, str) (((group)->translate_func ? (* (group)->translate_func) ((str), (group)->translate_data) : (str)))
203 #define NO_ARG(entry) ((entry)->arg == G_OPTION_ARG_NONE || \
204 ((entry)->arg == G_OPTION_ARG_CALLBACK && \
205 ((entry)->flags & G_OPTION_FLAG_NO_ARG)))
207 #define OPTIONAL_ARG(entry) ((entry)->arg == G_OPTION_ARG_CALLBACK && \
208 (entry)->flags & G_OPTION_FLAG_OPTIONAL_ARG)
240 struct _GOptionContext
244 gchar *parameter_string;
248 GTranslateFunc translate_func;
249 GDestroyNotify translate_notify;
250 gpointer translate_data;
252 guint help_enabled : 1;
253 guint ignore_unknown : 1;
255 guint strict_posix : 1;
257 GOptionGroup *main_group;
259 /* We keep a list of change so we can revert them */
262 /* We also keep track of all argv elements
263 * that should be NULLed or modified.
265 GList *pending_nulls;
272 gchar *help_description;
276 GDestroyNotify destroy_notify;
279 GTranslateFunc translate_func;
280 GDestroyNotify translate_notify;
281 gpointer translate_data;
283 GOptionEntry *entries;
286 GOptionParseFunc pre_parse_func;
287 GOptionParseFunc post_parse_func;
288 GOptionErrorFunc error_func;
291 static void free_changes_list (GOptionContext *context,
293 static void free_pending_nulls (GOptionContext *context,
294 gboolean perform_nulls);
298 _g_unichar_get_width (gunichar c)
300 if (G_UNLIKELY (g_unichar_iszerowidth (c)))
303 /* we ignore the fact that we should call g_unichar_iswide_cjk() under
304 * some locales (legacy East Asian ones) */
305 if (g_unichar_iswide (c))
312 _g_utf8_strwidth (const gchar *p)
315 g_return_val_if_fail (p != NULL, 0);
319 len += _g_unichar_get_width (g_utf8_get_char (p));
320 p = g_utf8_next_char (p);
326 G_DEFINE_QUARK (g-option-context-error-quark, g_option_error)
329 * g_option_context_new:
330 * @parameter_string: (nullable): a string which is displayed in
331 * the first line of `--help` output, after the usage summary
332 * `programname [OPTION...]`
334 * Creates a new option context.
336 * The @parameter_string can serve multiple purposes. It can be used
337 * to add descriptions for "rest" arguments, which are not parsed by
338 * the #GOptionContext, typically something like "FILES" or
339 * "FILE1 FILE2...". If you are using #G_OPTION_REMAINING for
340 * collecting "rest" arguments, GLib handles this automatically by
341 * using the @arg_description of the corresponding #GOptionEntry in
344 * Another usage is to give a short summary of the program
345 * functionality, like " - frob the strings", which will be displayed
346 * in the same line as the usage. For a longer description of the
347 * program functionality that should be displayed as a paragraph
348 * below the usage line, use g_option_context_set_summary().
350 * Note that the @parameter_string is translated using the
351 * function set with g_option_context_set_translate_func(), so
352 * it should normally be passed untranslated.
354 * Returns: a newly created #GOptionContext, which must be
355 * freed with g_option_context_free() after use.
360 g_option_context_new (const gchar *parameter_string)
363 GOptionContext *context;
365 context = g_new0 (GOptionContext, 1);
367 context->parameter_string = g_strdup (parameter_string);
368 context->strict_posix = FALSE;
369 context->help_enabled = TRUE;
370 context->ignore_unknown = FALSE;
376 * g_option_context_free:
377 * @context: a #GOptionContext
379 * Frees context and all the groups which have been
382 * Please note that parsed arguments need to be freed separately (see
387 void g_option_context_free (GOptionContext *context)
389 g_return_if_fail (context != NULL);
391 g_list_free_full (context->groups, (GDestroyNotify) g_option_group_unref);
393 if (context->main_group)
394 g_option_group_unref (context->main_group);
396 free_changes_list (context, FALSE);
397 free_pending_nulls (context, FALSE);
399 g_free (context->parameter_string);
400 g_free (context->summary);
401 g_free (context->description);
403 if (context->translate_notify)
404 (* context->translate_notify) (context->translate_data);
411 * g_option_context_set_help_enabled:
412 * @context: a #GOptionContext
413 * @help_enabled: %TRUE to enable `--help`, %FALSE to disable it
415 * Enables or disables automatic generation of `--help` output.
416 * By default, g_option_context_parse() recognizes `--help`, `-h`,
417 * `-?`, `--help-all` and `--help-groupname` and creates suitable
422 void g_option_context_set_help_enabled (GOptionContext *context,
423 gboolean help_enabled)
426 g_return_if_fail (context != NULL);
428 context->help_enabled = help_enabled;
432 * g_option_context_get_help_enabled:
433 * @context: a #GOptionContext
435 * Returns whether automatic `--help` generation
436 * is turned on for @context. See g_option_context_set_help_enabled().
438 * Returns: %TRUE if automatic help generation is turned on.
443 g_option_context_get_help_enabled (GOptionContext *context)
445 g_return_val_if_fail (context != NULL, FALSE);
447 return context->help_enabled;
451 * g_option_context_set_ignore_unknown_options:
452 * @context: a #GOptionContext
453 * @ignore_unknown: %TRUE to ignore unknown options, %FALSE to produce
454 * an error when unknown options are met
456 * Sets whether to ignore unknown options or not. If an argument is
457 * ignored, it is left in the @argv array after parsing. By default,
458 * g_option_context_parse() treats unknown options as error.
460 * This setting does not affect non-option arguments (i.e. arguments
461 * which don't start with a dash). But note that GOption cannot reliably
462 * determine whether a non-option belongs to a preceding unknown option.
467 g_option_context_set_ignore_unknown_options (GOptionContext *context,
468 gboolean ignore_unknown)
470 g_return_if_fail (context != NULL);
472 context->ignore_unknown = ignore_unknown;
476 * g_option_context_get_ignore_unknown_options:
477 * @context: a #GOptionContext
479 * Returns whether unknown options are ignored or not. See
480 * g_option_context_set_ignore_unknown_options().
482 * Returns: %TRUE if unknown options are ignored.
487 g_option_context_get_ignore_unknown_options (GOptionContext *context)
489 g_return_val_if_fail (context != NULL, FALSE);
491 return context->ignore_unknown;
495 * g_option_context_set_strict_posix:
496 * @context: a #GOptionContext
497 * @strict_posix: the new value
499 * Sets strict POSIX mode.
501 * By default, this mode is disabled.
503 * In strict POSIX mode, the first non-argument parameter encountered
504 * (eg: filename) terminates argument processing. Remaining arguments
505 * are treated as non-options and are not attempted to be parsed.
507 * If strict POSIX mode is disabled then parsing is done in the GNU way
508 * where option arguments can be freely mixed with non-options.
510 * As an example, consider "ls foo -l". With GNU style parsing, this
511 * will list "foo" in long mode. In strict POSIX style, this will list
512 * the files named "foo" and "-l".
514 * It may be useful to force strict POSIX mode when creating "verb
515 * style" command line tools. For example, the "gsettings" command line
516 * tool supports the global option "--schemadir" as well as many
517 * subcommands ("get", "set", etc.) which each have their own set of
518 * arguments. Using strict POSIX mode will allow parsing the global
519 * options up to the verb name while leaving the remaining options to be
520 * parsed by the relevant subcommand (which can be determined by
521 * examining the verb name, which should be present in argv[1] after
527 g_option_context_set_strict_posix (GOptionContext *context,
528 gboolean strict_posix)
530 g_return_if_fail (context != NULL);
532 context->strict_posix = strict_posix;
536 * g_option_context_get_strict_posix:
537 * @context: a #GOptionContext
539 * Returns whether strict POSIX code is enabled.
541 * See g_option_context_set_strict_posix() for more information.
543 * Returns: %TRUE if strict POSIX is enabled, %FALSE otherwise.
548 g_option_context_get_strict_posix (GOptionContext *context)
550 g_return_val_if_fail (context != NULL, FALSE);
552 return context->strict_posix;
556 * g_option_context_add_group:
557 * @context: a #GOptionContext
558 * @group: (transfer full): the group to add
560 * Adds a #GOptionGroup to the @context, so that parsing with @context
561 * will recognize the options in the group. Note that this will take
562 * ownership of the @group and thus the @group should not be freed.
567 g_option_context_add_group (GOptionContext *context,
572 g_return_if_fail (context != NULL);
573 g_return_if_fail (group != NULL);
574 g_return_if_fail (group->name != NULL);
575 g_return_if_fail (group->description != NULL);
576 g_return_if_fail (group->help_description != NULL);
578 for (list = context->groups; list; list = list->next)
580 GOptionGroup *g = (GOptionGroup *)list->data;
582 if ((group->name == NULL && g->name == NULL) ||
583 (group->name && g->name && strcmp (group->name, g->name) == 0))
584 g_warning ("A group named \"%s\" is already part of this GOptionContext",
588 context->groups = g_list_append (context->groups, group);
592 * g_option_context_set_main_group:
593 * @context: a #GOptionContext
594 * @group: (transfer full): the group to set as main group
596 * Sets a #GOptionGroup as main group of the @context.
597 * This has the same effect as calling g_option_context_add_group(),
598 * the only difference is that the options in the main group are
599 * treated differently when generating `--help` output.
604 g_option_context_set_main_group (GOptionContext *context,
607 g_return_if_fail (context != NULL);
608 g_return_if_fail (group != NULL);
610 if (context->main_group)
612 g_warning ("This GOptionContext already has a main group");
617 context->main_group = group;
621 * g_option_context_get_main_group:
622 * @context: a #GOptionContext
624 * Returns a pointer to the main group of @context.
626 * Returns: (transfer none): the main group of @context, or %NULL if
627 * @context doesn't have a main group. Note that group belongs to
628 * @context and should not be modified or freed.
633 g_option_context_get_main_group (GOptionContext *context)
635 g_return_val_if_fail (context != NULL, NULL);
637 return context->main_group;
641 * g_option_context_add_main_entries:
642 * @context: a #GOptionContext
643 * @entries: a %NULL-terminated array of #GOptionEntrys
644 * @translation_domain: (nullable): a translation domain to use for translating
645 * the `--help` output for the options in @entries
646 * with gettext(), or %NULL
648 * A convenience function which creates a main group if it doesn't
649 * exist, adds the @entries to it and sets the translation domain.
654 g_option_context_add_main_entries (GOptionContext *context,
655 const GOptionEntry *entries,
656 const gchar *translation_domain)
658 g_return_if_fail (entries != NULL);
660 if (!context->main_group)
661 context->main_group = g_option_group_new (NULL, NULL, NULL, NULL, NULL);
663 g_option_group_add_entries (context->main_group, entries);
664 g_option_group_set_translation_domain (context->main_group, translation_domain);
668 calculate_max_length (GOptionGroup *group,
672 gsize i, len, max_length;
673 const gchar *long_name;
677 for (i = 0; i < group->n_entries; i++)
679 entry = &group->entries[i];
681 if (entry->flags & G_OPTION_FLAG_HIDDEN)
684 long_name = g_hash_table_lookup (aliases, &entry->long_name);
686 long_name = entry->long_name;
687 len = _g_utf8_strwidth (long_name);
689 if (entry->short_name)
692 if (!NO_ARG (entry) && entry->arg_description)
693 len += 1 + _g_utf8_strwidth (TRANSLATE (group, entry->arg_description));
695 max_length = MAX (max_length, len);
702 print_entry (GOptionGroup *group,
704 const GOptionEntry *entry,
709 const gchar *long_name;
711 if (entry->flags & G_OPTION_FLAG_HIDDEN)
714 if (entry->long_name[0] == 0)
717 long_name = g_hash_table_lookup (aliases, &entry->long_name);
719 long_name = entry->long_name;
721 str = g_string_new (NULL);
723 if (entry->short_name)
724 g_string_append_printf (str, " -%c, --%s", entry->short_name, long_name);
726 g_string_append_printf (str, " --%s", long_name);
728 if (entry->arg_description)
729 g_string_append_printf (str, "=%s", TRANSLATE (group, entry->arg_description));
731 g_string_append_printf (string, "%s%*s %s\n", str->str,
732 (int) (max_length + 4 - _g_utf8_strwidth (str->str)), "",
733 entry->description ? TRANSLATE (group, entry->description) : "");
734 g_string_free (str, TRUE);
738 group_has_visible_entries (GOptionContext *context,
740 gboolean main_entries)
742 GOptionFlags reject_filter = G_OPTION_FLAG_HIDDEN;
745 gboolean main_group = group == context->main_group;
748 reject_filter |= G_OPTION_FLAG_IN_MAIN;
750 for (i = 0, l = (group ? group->n_entries : 0); i < l; i++)
752 entry = &group->entries[i];
754 if (main_entries && !main_group && !(entry->flags & G_OPTION_FLAG_IN_MAIN))
756 if (entry->long_name[0] == 0) /* ignore rest entry */
758 if (!(entry->flags & reject_filter))
766 group_list_has_visible_entries (GOptionContext *context,
768 gboolean main_entries)
772 if (group_has_visible_entries (context, group_list->data, main_entries))
775 group_list = group_list->next;
782 context_has_h_entry (GOptionContext *context)
787 if (context->main_group)
789 for (i = 0; i < context->main_group->n_entries; i++)
791 if (context->main_group->entries[i].short_name == 'h')
796 for (list = context->groups; list != NULL; list = g_list_next (list))
800 group = (GOptionGroup*)list->data;
801 for (i = 0; i < group->n_entries; i++)
803 if (group->entries[i].short_name == 'h')
811 * g_option_context_get_help:
812 * @context: a #GOptionContext
813 * @main_help: if %TRUE, only include the main group
814 * @group: (nullable): the #GOptionGroup to create help for, or %NULL
816 * Returns a formatted, translated help text for the given context.
817 * To obtain the text produced by `--help`, call
818 * `g_option_context_get_help (context, TRUE, NULL)`.
819 * To obtain the text produced by `--help-all`, call
820 * `g_option_context_get_help (context, FALSE, NULL)`.
821 * To obtain the help text for an option group, call
822 * `g_option_context_get_help (context, FALSE, group)`.
824 * Returns: A newly allocated string containing the help text
829 g_option_context_get_help (GOptionContext *context,
834 gint max_length = 0, len;
837 GHashTable *shadow_map;
840 const gchar *rest_description;
844 string = g_string_sized_new (1024);
846 rest_description = NULL;
847 if (context->main_group)
850 for (i = 0; i < context->main_group->n_entries; i++)
852 entry = &context->main_group->entries[i];
853 if (entry->long_name[0] == 0)
855 rest_description = TRANSLATE (context->main_group, entry->arg_description);
861 g_string_append_printf (string, "%s\n %s", _("Usage:"), g_get_prgname ());
862 if (context->help_enabled ||
863 (context->main_group && context->main_group->n_entries > 0) ||
864 context->groups != NULL)
865 g_string_append_printf (string, " %s", _("[OPTION…]"));
867 if (rest_description)
869 g_string_append (string, " ");
870 g_string_append (string, rest_description);
873 if (context->parameter_string)
875 g_string_append (string, " ");
876 g_string_append (string, TRANSLATE (context, context->parameter_string));
879 g_string_append (string, "\n\n");
881 if (context->summary)
883 g_string_append (string, TRANSLATE (context, context->summary));
884 g_string_append (string, "\n\n");
887 memset (seen, 0, sizeof (gboolean) * 256);
888 shadow_map = g_hash_table_new (g_str_hash, g_str_equal);
889 aliases = g_hash_table_new_full (NULL, NULL, NULL, g_free);
891 if (context->main_group)
893 for (i = 0; i < context->main_group->n_entries; i++)
895 entry = &context->main_group->entries[i];
896 g_hash_table_insert (shadow_map,
897 (gpointer)entry->long_name,
900 if (seen[(guchar)entry->short_name])
901 entry->short_name = 0;
903 seen[(guchar)entry->short_name] = TRUE;
907 list = context->groups;
910 GOptionGroup *g = list->data;
911 for (i = 0; i < g->n_entries; i++)
913 entry = &g->entries[i];
914 if (g_hash_table_lookup (shadow_map, entry->long_name) &&
915 !(entry->flags & G_OPTION_FLAG_NOALIAS))
917 g_hash_table_insert (aliases, &entry->long_name,
918 g_strdup_printf ("%s-%s", g->name, entry->long_name));
921 g_hash_table_insert (shadow_map, (gpointer)entry->long_name, entry);
923 if (seen[(guchar)entry->short_name] &&
924 !(entry->flags & G_OPTION_FLAG_NOALIAS))
925 entry->short_name = 0;
927 seen[(guchar)entry->short_name] = TRUE;
932 g_hash_table_destroy (shadow_map);
934 list = context->groups;
936 if (context->help_enabled)
938 max_length = _g_utf8_strwidth ("-?, --help");
942 len = _g_utf8_strwidth ("--help-all");
943 max_length = MAX (max_length, len);
947 if (context->main_group)
949 len = calculate_max_length (context->main_group, aliases);
950 max_length = MAX (max_length, len);
955 GOptionGroup *g = list->data;
957 if (context->help_enabled)
959 /* First, we check the --help-<groupname> options */
960 len = _g_utf8_strwidth ("--help-") + _g_utf8_strwidth (g->name);
961 max_length = MAX (max_length, len);
964 /* Then we go through the entries */
965 len = calculate_max_length (g, aliases);
966 max_length = MAX (max_length, len);
971 /* Add a bit of padding */
974 if (!group && context->help_enabled)
976 list = context->groups;
978 token = context_has_h_entry (context) ? '?' : 'h';
980 g_string_append_printf (string, "%s\n -%c, --%-*s %s\n",
981 _("Help Options:"), token, max_length - 4, "help",
982 _("Show help options"));
984 /* We only want --help-all when there are groups */
986 g_string_append_printf (string, " --%-*s %s\n",
987 max_length, "help-all",
988 _("Show all help options"));
992 GOptionGroup *g = list->data;
994 if (group_has_visible_entries (context, g, FALSE))
995 g_string_append_printf (string, " --help-%-*s %s\n",
996 max_length - 5, g->name,
997 TRANSLATE (g, g->help_description));
1002 g_string_append (string, "\n");
1007 /* Print a certain group */
1009 if (group_has_visible_entries (context, group, FALSE))
1011 g_string_append (string, TRANSLATE (group, group->description));
1012 g_string_append (string, "\n");
1013 for (i = 0; i < group->n_entries; i++)
1014 print_entry (group, max_length, &group->entries[i], string, aliases);
1015 g_string_append (string, "\n");
1018 else if (!main_help)
1020 /* Print all groups */
1022 list = context->groups;
1026 GOptionGroup *g = list->data;
1028 if (group_has_visible_entries (context, g, FALSE))
1030 g_string_append (string, g->description);
1031 g_string_append (string, "\n");
1032 for (i = 0; i < g->n_entries; i++)
1033 if (!(g->entries[i].flags & G_OPTION_FLAG_IN_MAIN))
1034 print_entry (g, max_length, &g->entries[i], string, aliases);
1036 g_string_append (string, "\n");
1043 /* Print application options if --help or --help-all has been specified */
1044 if ((main_help || !group) &&
1045 (group_has_visible_entries (context, context->main_group, TRUE) ||
1046 group_list_has_visible_entries (context, context->groups, TRUE)))
1048 list = context->groups;
1050 if (context->help_enabled || list)
1051 g_string_append (string, _("Application Options:"));
1053 g_string_append (string, _("Options:"));
1054 g_string_append (string, "\n");
1055 if (context->main_group)
1056 for (i = 0; i < context->main_group->n_entries; i++)
1057 print_entry (context->main_group, max_length,
1058 &context->main_group->entries[i], string, aliases);
1060 while (list != NULL)
1062 GOptionGroup *g = list->data;
1064 /* Print main entries from other groups */
1065 for (i = 0; i < g->n_entries; i++)
1066 if (g->entries[i].flags & G_OPTION_FLAG_IN_MAIN)
1067 print_entry (g, max_length, &g->entries[i], string, aliases);
1072 g_string_append (string, "\n");
1075 if (context->description)
1077 g_string_append (string, TRANSLATE (context, context->description));
1078 g_string_append (string, "\n");
1081 g_hash_table_destroy (aliases);
1083 return g_string_free (string, FALSE);
1088 print_help (GOptionContext *context,
1090 GOptionGroup *group)
1094 help = g_option_context_get_help (context, main_help, group);
1095 g_print ("%s", help);
1102 parse_int (const gchar *arg_name,
1111 tmp = strtol (arg, &end, 0);
1113 if (*arg == '\0' || *end != '\0')
1116 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1117 _("Cannot parse integer value “%s” for %s"),
1123 if (*result != tmp || errno == ERANGE)
1126 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1127 _("Integer value “%s” for %s out of range"),
1137 parse_double (const gchar *arg_name,
1146 tmp = g_strtod (arg, &end);
1148 if (*arg == '\0' || *end != '\0')
1151 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1152 _("Cannot parse double value “%s” for %s"),
1156 if (errno == ERANGE)
1159 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1160 _("Double value “%s” for %s out of range"),
1172 parse_int64 (const gchar *arg_name,
1181 tmp = g_ascii_strtoll (arg, &end, 0);
1183 if (*arg == '\0' || *end != '\0')
1186 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1187 _("Cannot parse integer value “%s” for %s"),
1191 if (errno == ERANGE)
1194 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1195 _("Integer value “%s” for %s out of range"),
1207 get_change (GOptionContext *context,
1208 GOptionArg arg_type,
1212 Change *change = NULL;
1214 for (list = context->changes; list != NULL; list = list->next)
1216 change = list->data;
1218 if (change->arg_data == arg_data)
1222 change = g_new0 (Change, 1);
1223 change->arg_type = arg_type;
1224 change->arg_data = arg_data;
1226 context->changes = g_list_prepend (context->changes, change);
1234 add_pending_null (GOptionContext *context,
1240 n = g_new0 (PendingNull, 1);
1244 context->pending_nulls = g_list_prepend (context->pending_nulls, n);
1248 parse_arg (GOptionContext *context,
1249 GOptionGroup *group,
1250 GOptionEntry *entry,
1252 const gchar *option_name,
1258 g_assert (value || OPTIONAL_ARG (entry) || NO_ARG (entry));
1262 case G_OPTION_ARG_NONE:
1264 (void) get_change (context, G_OPTION_ARG_NONE,
1267 *(gboolean *)entry->arg_data = !(entry->flags & G_OPTION_FLAG_REVERSE);
1270 case G_OPTION_ARG_STRING:
1275 if (!context->strv_mode)
1276 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1278 data = g_strdup (value);
1280 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1286 change = get_change (context, G_OPTION_ARG_STRING,
1289 if (!change->allocated.str)
1290 change->prev.str = *(gchar **)entry->arg_data;
1292 g_free (change->allocated.str);
1294 change->allocated.str = data;
1296 *(gchar **)entry->arg_data = data;
1299 case G_OPTION_ARG_STRING_ARRAY:
1304 if (!context->strv_mode)
1305 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1307 data = g_strdup (value);
1309 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1315 change = get_change (context, G_OPTION_ARG_STRING_ARRAY,
1318 if (change->allocated.array.len == 0)
1320 change->prev.array = *(gchar ***)entry->arg_data;
1321 change->allocated.array.data = g_new (gchar *, 2);
1324 change->allocated.array.data =
1325 g_renew (gchar *, change->allocated.array.data,
1326 change->allocated.array.len + 2);
1328 change->allocated.array.data[change->allocated.array.len] = data;
1329 change->allocated.array.data[change->allocated.array.len + 1] = NULL;
1331 change->allocated.array.len ++;
1333 *(gchar ***)entry->arg_data = change->allocated.array.data;
1338 case G_OPTION_ARG_FILENAME:
1343 if (!context->strv_mode)
1344 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1346 data = g_strdup (value);
1351 data = g_strdup (value);
1353 change = get_change (context, G_OPTION_ARG_FILENAME,
1356 if (!change->allocated.str)
1357 change->prev.str = *(gchar **)entry->arg_data;
1359 g_free (change->allocated.str);
1361 change->allocated.str = data;
1363 *(gchar **)entry->arg_data = data;
1367 case G_OPTION_ARG_FILENAME_ARRAY:
1372 if (!context->strv_mode)
1373 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1375 data = g_strdup (value);
1380 data = g_strdup (value);
1382 change = get_change (context, G_OPTION_ARG_STRING_ARRAY,
1385 if (change->allocated.array.len == 0)
1387 change->prev.array = *(gchar ***)entry->arg_data;
1388 change->allocated.array.data = g_new (gchar *, 2);
1391 change->allocated.array.data =
1392 g_renew (gchar *, change->allocated.array.data,
1393 change->allocated.array.len + 2);
1395 change->allocated.array.data[change->allocated.array.len] = data;
1396 change->allocated.array.data[change->allocated.array.len + 1] = NULL;
1398 change->allocated.array.len ++;
1400 *(gchar ***)entry->arg_data = change->allocated.array.data;
1405 case G_OPTION_ARG_INT:
1409 if (!parse_int (option_name, value,
1414 change = get_change (context, G_OPTION_ARG_INT,
1416 change->prev.integer = *(gint *)entry->arg_data;
1417 *(gint *)entry->arg_data = data;
1420 case G_OPTION_ARG_CALLBACK:
1425 if (!value && entry->flags & G_OPTION_FLAG_OPTIONAL_ARG)
1427 else if (entry->flags & G_OPTION_FLAG_NO_ARG)
1429 else if (entry->flags & G_OPTION_FLAG_FILENAME)
1432 if (!context->strv_mode)
1433 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1435 data = g_strdup (value);
1437 data = g_strdup (value);
1441 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1443 if (!(entry->flags & (G_OPTION_FLAG_NO_ARG|G_OPTION_FLAG_OPTIONAL_ARG)) &&
1447 retval = (* (GOptionArgFunc) entry->arg_data) (option_name, data, group->user_data, error);
1449 if (!retval && error != NULL && *error == NULL)
1451 G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
1452 _("Error parsing option %s"), option_name);
1460 case G_OPTION_ARG_DOUBLE:
1464 if (!parse_double (option_name, value,
1471 change = get_change (context, G_OPTION_ARG_DOUBLE,
1473 change->prev.dbl = *(gdouble *)entry->arg_data;
1474 *(gdouble *)entry->arg_data = data;
1477 case G_OPTION_ARG_INT64:
1481 if (!parse_int64 (option_name, value,
1488 change = get_change (context, G_OPTION_ARG_INT64,
1490 change->prev.int64 = *(gint64 *)entry->arg_data;
1491 *(gint64 *)entry->arg_data = data;
1495 g_assert_not_reached ();
1502 parse_short_option (GOptionContext *context,
1503 GOptionGroup *group,
1514 for (j = 0; j < group->n_entries; j++)
1516 if (arg == group->entries[j].short_name)
1519 gchar *value = NULL;
1521 option_name = g_strdup_printf ("-%c", group->entries[j].short_name);
1523 if (NO_ARG (&group->entries[j]))
1530 G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
1531 _("Error parsing option %s"), option_name);
1532 g_free (option_name);
1536 if (idx < *argc - 1)
1538 if (!OPTIONAL_ARG (&group->entries[j]))
1540 value = (*argv)[idx + 1];
1541 add_pending_null (context, &((*argv)[idx + 1]), NULL);
1546 if ((*argv)[idx + 1][0] == '-')
1550 value = (*argv)[idx + 1];
1551 add_pending_null (context, &((*argv)[idx + 1]), NULL);
1556 else if (idx >= *argc - 1 && OPTIONAL_ARG (&group->entries[j]))
1561 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1562 _("Missing argument for %s"), option_name);
1563 g_free (option_name);
1568 if (!parse_arg (context, group, &group->entries[j],
1569 value, option_name, error))
1571 g_free (option_name);
1575 g_free (option_name);
1584 parse_long_option (GOptionContext *context,
1585 GOptionGroup *group,
1596 for (j = 0; j < group->n_entries; j++)
1601 if (aliased && (group->entries[j].flags & G_OPTION_FLAG_NOALIAS))
1604 if (NO_ARG (&group->entries[j]) &&
1605 strcmp (arg, group->entries[j].long_name) == 0)
1610 option_name = g_strconcat ("--", group->entries[j].long_name, NULL);
1611 retval = parse_arg (context, group, &group->entries[j],
1612 NULL, option_name, error);
1613 g_free (option_name);
1615 add_pending_null (context, &((*argv)[*idx]), NULL);
1622 gint len = strlen (group->entries[j].long_name);
1624 if (strncmp (arg, group->entries[j].long_name, len) == 0 &&
1625 (arg[len] == '=' || arg[len] == 0))
1627 gchar *value = NULL;
1630 add_pending_null (context, &((*argv)[*idx]), NULL);
1631 option_name = g_strconcat ("--", group->entries[j].long_name, NULL);
1633 if (arg[len] == '=')
1634 value = arg + len + 1;
1635 else if (*idx < *argc - 1)
1637 if (!OPTIONAL_ARG (&group->entries[j]))
1639 value = (*argv)[*idx + 1];
1640 add_pending_null (context, &((*argv)[*idx + 1]), NULL);
1645 if ((*argv)[*idx + 1][0] == '-')
1648 retval = parse_arg (context, group, &group->entries[j],
1649 NULL, option_name, error);
1651 g_free (option_name);
1656 value = (*argv)[*idx + 1];
1657 add_pending_null (context, &((*argv)[*idx + 1]), NULL);
1662 else if (*idx >= *argc - 1 && OPTIONAL_ARG (&group->entries[j]))
1665 retval = parse_arg (context, group, &group->entries[j],
1666 NULL, option_name, error);
1668 g_free (option_name);
1674 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1675 _("Missing argument for %s"), option_name);
1676 g_free (option_name);
1680 if (!parse_arg (context, group, &group->entries[j],
1681 value, option_name, error))
1683 g_free (option_name);
1687 g_free (option_name);
1697 parse_remaining_arg (GOptionContext *context,
1698 GOptionGroup *group,
1707 for (j = 0; j < group->n_entries; j++)
1712 if (group->entries[j].long_name[0])
1715 g_return_val_if_fail (group->entries[j].arg == G_OPTION_ARG_CALLBACK ||
1716 group->entries[j].arg == G_OPTION_ARG_STRING_ARRAY ||
1717 group->entries[j].arg == G_OPTION_ARG_FILENAME_ARRAY, FALSE);
1719 add_pending_null (context, &((*argv)[*idx]), NULL);
1721 if (!parse_arg (context, group, &group->entries[j], (*argv)[*idx], "", error))
1732 free_changes_list (GOptionContext *context,
1737 for (list = context->changes; list != NULL; list = list->next)
1739 Change *change = list->data;
1743 switch (change->arg_type)
1745 case G_OPTION_ARG_NONE:
1746 *(gboolean *)change->arg_data = change->prev.bool;
1748 case G_OPTION_ARG_INT:
1749 *(gint *)change->arg_data = change->prev.integer;
1751 case G_OPTION_ARG_STRING:
1752 case G_OPTION_ARG_FILENAME:
1753 g_free (change->allocated.str);
1754 *(gchar **)change->arg_data = change->prev.str;
1756 case G_OPTION_ARG_STRING_ARRAY:
1757 case G_OPTION_ARG_FILENAME_ARRAY:
1758 g_strfreev (change->allocated.array.data);
1759 *(gchar ***)change->arg_data = change->prev.array;
1761 case G_OPTION_ARG_DOUBLE:
1762 *(gdouble *)change->arg_data = change->prev.dbl;
1764 case G_OPTION_ARG_INT64:
1765 *(gint64 *)change->arg_data = change->prev.int64;
1768 g_assert_not_reached ();
1775 g_list_free (context->changes);
1776 context->changes = NULL;
1780 free_pending_nulls (GOptionContext *context,
1781 gboolean perform_nulls)
1785 for (list = context->pending_nulls; list != NULL; list = list->next)
1787 PendingNull *n = list->data;
1793 /* Copy back the short options */
1795 strcpy (*n->ptr + 1, n->value);
1799 if (context->strv_mode)
1810 g_list_free (context->pending_nulls);
1811 context->pending_nulls = NULL;
1814 /* Use a platform-specific mechanism to look up the first argument to
1815 * the current process.
1816 * Note if you implement this for other platforms, also add it to
1817 * tests/option-argv0.c
1820 platform_get_argv0 (void)
1822 #ifdef HAVE_PROC_SELF_CMDLINE
1827 if (!g_file_get_contents ("/proc/self/cmdline",
1832 /* Sanity check for a NUL terminator. */
1833 if (!memchr (cmdline, 0, len))
1835 /* We could just return cmdline, but I think it's better
1836 * to hold on to a smaller malloc block; the arguments
1839 base_arg0 = g_path_get_basename (cmdline);
1842 #elif defined __OpenBSD__
1847 int mib[] = { CTL_KERN, KERN_PROC_ARGS, getpid(), KERN_PROC_ARGV };
1849 if (sysctl (mib, G_N_ELEMENTS (mib), NULL, &len, NULL, 0) == -1)
1852 cmdline = g_malloc0 (len);
1854 if (sysctl (mib, G_N_ELEMENTS (mib), cmdline, &len, NULL, 0) == -1)
1860 /* We could just return cmdline, but I think it's better
1861 * to hold on to a smaller malloc block; the arguments
1864 base_arg0 = g_path_get_basename (*cmdline);
1867 #elif defined G_OS_WIN32
1868 const wchar_t *cmdline;
1871 gchar *utf8_buf = NULL;
1872 char *base_arg0 = NULL;
1874 /* Pretend it's const, since we're not allowed to free it */
1875 cmdline = (const wchar_t *) GetCommandLineW ();
1876 if (G_UNLIKELY (cmdline == NULL))
1879 /* Skip leading whitespace. CommandLineToArgvW() is documented
1880 * to behave weirdly with that. The character codes below
1881 * correspond to the *only* unicode characters that are
1882 * considered to be spaces by CommandLineToArgvW(). The rest
1883 * (such as 0xa0 - NO-BREAK SPACE) are treated as
1884 * normal characters.
1886 while (cmdline[0] == 0x09 ||
1887 cmdline[0] == 0x0a ||
1888 cmdline[0] == 0x0c ||
1889 cmdline[0] == 0x0d ||
1893 wargv = CommandLineToArgvW (cmdline, &wargc);
1894 if (G_UNLIKELY (wargv == NULL))
1898 utf8_buf = g_utf16_to_utf8 (wargv[0], -1, NULL, NULL, NULL);
1902 if (G_UNLIKELY (utf8_buf == NULL))
1905 /* We could just return cmdline, but I think it's better
1906 * to hold on to a smaller malloc block; the arguments
1909 base_arg0 = g_path_get_basename (utf8_buf);
1918 * g_option_context_parse:
1919 * @context: a #GOptionContext
1920 * @argc: (inout) (optional): a pointer to the number of command line arguments
1921 * @argv: (inout) (array length=argc) (optional): a pointer to the array of command line arguments
1922 * @error: a return location for errors
1924 * Parses the command line arguments, recognizing options
1925 * which have been added to @context. A side-effect of
1926 * calling this function is that g_set_prgname() will be
1929 * If the parsing is successful, any parsed arguments are
1930 * removed from the array and @argc and @argv are updated
1931 * accordingly. A '--' option is stripped from @argv
1932 * unless there are unparsed options before and after it,
1933 * or some of the options after it start with '-'. In case
1934 * of an error, @argc and @argv are left unmodified.
1936 * If automatic `--help` support is enabled
1937 * (see g_option_context_set_help_enabled()), and the
1938 * @argv array contains one of the recognized help options,
1939 * this function will produce help output to stdout and
1942 * Note that function depends on the [current locale][setlocale] for
1943 * automatic character set conversion of string and filename
1946 * Returns: %TRUE if the parsing was successful,
1947 * %FALSE if an error occurred
1952 g_option_context_parse (GOptionContext *context,
1960 /* Set program name */
1961 if (!g_get_prgname())
1965 if (argc && argv && *argc)
1966 prgname = g_path_get_basename ((*argv)[0]);
1968 prgname = platform_get_argv0 ();
1971 g_set_prgname (prgname);
1973 g_set_prgname ("<unknown>");
1978 /* Call pre-parse hooks */
1979 list = context->groups;
1982 GOptionGroup *group = list->data;
1984 if (group->pre_parse_func)
1986 if (!(* group->pre_parse_func) (context, group,
1987 group->user_data, error))
1994 if (context->main_group && context->main_group->pre_parse_func)
1996 if (!(* context->main_group->pre_parse_func) (context, context->main_group,
1997 context->main_group->user_data, error))
2003 gboolean stop_parsing = FALSE;
2004 gboolean has_unknown = FALSE;
2005 gint separator_pos = 0;
2007 for (i = 1; i < *argc; i++)
2010 gboolean parsed = FALSE;
2012 if ((*argv)[i][0] == '-' && (*argv)[i][1] != '\0' && !stop_parsing)
2014 if ((*argv)[i][1] == '-')
2018 arg = (*argv)[i] + 2;
2020 /* '--' terminates list of arguments */
2024 stop_parsing = TRUE;
2028 /* Handle help options */
2029 if (context->help_enabled)
2031 if (strcmp (arg, "help") == 0)
2032 print_help (context, TRUE, NULL);
2033 else if (strcmp (arg, "help-all") == 0)
2034 print_help (context, FALSE, NULL);
2035 else if (strncmp (arg, "help-", 5) == 0)
2037 list = context->groups;
2041 GOptionGroup *group = list->data;
2043 if (strcmp (arg + 5, group->name) == 0)
2044 print_help (context, FALSE, group);
2051 if (context->main_group &&
2052 !parse_long_option (context, context->main_group, &i, arg,
2053 FALSE, argc, argv, error, &parsed))
2059 /* Try the groups */
2060 list = context->groups;
2063 GOptionGroup *group = list->data;
2065 if (!parse_long_option (context, group, &i, arg,
2066 FALSE, argc, argv, error, &parsed))
2078 /* Now look for --<group>-<option> */
2079 dash = strchr (arg, '-');
2080 if (dash && arg < dash)
2082 /* Try the groups */
2083 list = context->groups;
2086 GOptionGroup *group = list->data;
2088 if (strncmp (group->name, arg, dash - arg) == 0)
2090 if (!parse_long_option (context, group, &i, dash + 1,
2091 TRUE, argc, argv, error, &parsed))
2102 if (context->ignore_unknown)
2106 { /* short option */
2107 gint new_i = i, arg_length;
2108 gboolean *nulled_out = NULL;
2109 gboolean has_h_entry = context_has_h_entry (context);
2110 arg = (*argv)[i] + 1;
2111 arg_length = strlen (arg);
2112 nulled_out = g_newa (gboolean, arg_length);
2113 memset (nulled_out, 0, arg_length * sizeof (gboolean));
2114 for (j = 0; j < arg_length; j++)
2116 if (context->help_enabled && (arg[j] == '?' ||
2117 (arg[j] == 'h' && !has_h_entry)))
2118 print_help (context, TRUE, NULL);
2120 if (context->main_group &&
2121 !parse_short_option (context, context->main_group,
2123 argc, argv, error, &parsed))
2127 /* Try the groups */
2128 list = context->groups;
2131 GOptionGroup *group = list->data;
2132 if (!parse_short_option (context, group, i, &new_i, arg[j],
2133 argc, argv, error, &parsed))
2141 if (context->ignore_unknown && parsed)
2142 nulled_out[j] = TRUE;
2143 else if (context->ignore_unknown)
2147 /* !context->ignore_unknown && parsed */
2149 if (context->ignore_unknown)
2151 gchar *new_arg = NULL;
2153 for (j = 0; j < arg_length; j++)
2158 new_arg = g_malloc (arg_length + 1);
2159 new_arg[arg_index++] = arg[j];
2163 new_arg[arg_index] = '\0';
2164 add_pending_null (context, &((*argv)[i]), new_arg);
2169 add_pending_null (context, &((*argv)[i]), NULL);
2177 if (!parsed && !context->ignore_unknown)
2180 G_OPTION_ERROR, G_OPTION_ERROR_UNKNOWN_OPTION,
2181 _("Unknown option %s"), (*argv)[i]);
2187 if (context->strict_posix)
2188 stop_parsing = TRUE;
2190 /* Collect remaining args */
2191 if (context->main_group &&
2192 !parse_remaining_arg (context, context->main_group, &i,
2193 argc, argv, error, &parsed))
2196 if (!parsed && (has_unknown || (*argv)[i][0] == '-'))
2201 if (separator_pos > 0)
2202 add_pending_null (context, &((*argv)[separator_pos]), NULL);
2206 /* Call post-parse hooks */
2207 list = context->groups;
2210 GOptionGroup *group = list->data;
2212 if (group->post_parse_func)
2214 if (!(* group->post_parse_func) (context, group,
2215 group->user_data, error))
2222 if (context->main_group && context->main_group->post_parse_func)
2224 if (!(* context->main_group->post_parse_func) (context, context->main_group,
2225 context->main_group->user_data, error))
2231 free_pending_nulls (context, TRUE);
2233 for (i = 1; i < *argc; i++)
2235 for (k = i; k < *argc; k++)
2236 if ((*argv)[k] != NULL)
2242 for (j = i + k; j < *argc; j++)
2244 (*argv)[j-k] = (*argv)[j];
2256 /* Call error hooks */
2257 list = context->groups;
2260 GOptionGroup *group = list->data;
2262 if (group->error_func)
2263 (* group->error_func) (context, group,
2264 group->user_data, error);
2269 if (context->main_group && context->main_group->error_func)
2270 (* context->main_group->error_func) (context, context->main_group,
2271 context->main_group->user_data, error);
2273 free_changes_list (context, TRUE);
2274 free_pending_nulls (context, FALSE);
2280 * g_option_group_new:
2281 * @name: the name for the option group, this is used to provide
2282 * help for the options in this group with `--help-`@name
2283 * @description: a description for this group to be shown in
2284 * `--help`. This string is translated using the translation
2285 * domain or translation function of the group
2286 * @help_description: a description for the `--help-`@name option.
2287 * This string is translated using the translation domain or translation function
2289 * @user_data: (nullable): user data that will be passed to the pre- and post-parse hooks,
2290 * the error hook and to callbacks of %G_OPTION_ARG_CALLBACK options, or %NULL
2291 * @destroy: (nullable): a function that will be called to free @user_data, or %NULL
2293 * Creates a new #GOptionGroup.
2295 * Returns: a newly created option group. It should be added
2296 * to a #GOptionContext or freed with g_option_group_unref().
2301 g_option_group_new (const gchar *name,
2302 const gchar *description,
2303 const gchar *help_description,
2305 GDestroyNotify destroy)
2308 GOptionGroup *group;
2310 group = g_new0 (GOptionGroup, 1);
2311 group->ref_count = 1;
2312 group->name = g_strdup (name);
2313 group->description = g_strdup (description);
2314 group->help_description = g_strdup (help_description);
2315 group->user_data = user_data;
2316 group->destroy_notify = destroy;
2323 * g_option_group_free:
2324 * @group: a #GOptionGroup
2326 * Frees a #GOptionGroup. Note that you must not free groups
2327 * which have been added to a #GOptionContext.
2331 * Deprecated: 2.44: Use g_option_group_unref() instead.
2334 g_option_group_free (GOptionGroup *group)
2336 g_option_group_unref (group);
2340 * g_option_group_ref:
2341 * @group: a #GOptionGroup
2343 * Increments the reference count of @group by one.
2345 * Returns: a #GOptionGroup
2350 g_option_group_ref (GOptionGroup *group)
2352 g_return_val_if_fail (group != NULL, NULL);
2360 * g_option_group_unref:
2361 * @group: a #GOptionGroup
2363 * Decrements the reference count of @group by one.
2364 * If the reference count drops to 0, the @group will be freed.
2365 * and all memory allocated by the @group is released.
2370 g_option_group_unref (GOptionGroup *group)
2372 g_return_if_fail (group != NULL);
2374 if (--group->ref_count == 0)
2376 g_free (group->name);
2377 g_free (group->description);
2378 g_free (group->help_description);
2380 g_free (group->entries);
2382 if (group->destroy_notify)
2383 (* group->destroy_notify) (group->user_data);
2385 if (group->translate_notify)
2386 (* group->translate_notify) (group->translate_data);
2393 * g_option_group_add_entries:
2394 * @group: a #GOptionGroup
2395 * @entries: a %NULL-terminated array of #GOptionEntrys
2397 * Adds the options specified in @entries to @group.
2402 g_option_group_add_entries (GOptionGroup *group,
2403 const GOptionEntry *entries)
2407 g_return_if_fail (entries != NULL);
2409 for (n_entries = 0; entries[n_entries].long_name != NULL; n_entries++) ;
2411 group->entries = g_renew (GOptionEntry, group->entries, group->n_entries + n_entries);
2413 /* group->entries could be NULL in the trivial case where we add no
2414 * entries to no entries */
2416 memcpy (group->entries + group->n_entries, entries, sizeof (GOptionEntry) * n_entries);
2418 for (i = group->n_entries; i < group->n_entries + n_entries; i++)
2420 gchar c = group->entries[i].short_name;
2422 if (c == '-' || (c != 0 && !g_ascii_isprint (c)))
2424 g_warning (G_STRLOC ": ignoring invalid short option '%c' (%d) in entry %s:%s",
2425 c, c, group->name, group->entries[i].long_name);
2426 group->entries[i].short_name = '\0';
2429 if (group->entries[i].arg != G_OPTION_ARG_NONE &&
2430 (group->entries[i].flags & G_OPTION_FLAG_REVERSE) != 0)
2432 g_warning (G_STRLOC ": ignoring reverse flag on option of arg-type %d in entry %s:%s",
2433 group->entries[i].arg, group->name, group->entries[i].long_name);
2435 group->entries[i].flags &= ~G_OPTION_FLAG_REVERSE;
2438 if (group->entries[i].arg != G_OPTION_ARG_CALLBACK &&
2439 (group->entries[i].flags & (G_OPTION_FLAG_NO_ARG|G_OPTION_FLAG_OPTIONAL_ARG|G_OPTION_FLAG_FILENAME)) != 0)
2441 g_warning (G_STRLOC ": ignoring no-arg, optional-arg or filename flags (%d) on option of arg-type %d in entry %s:%s",
2442 group->entries[i].flags, group->entries[i].arg, group->name, group->entries[i].long_name);
2444 group->entries[i].flags &= ~(G_OPTION_FLAG_NO_ARG|G_OPTION_FLAG_OPTIONAL_ARG|G_OPTION_FLAG_FILENAME);
2448 group->n_entries += n_entries;
2452 * g_option_group_set_parse_hooks:
2453 * @group: a #GOptionGroup
2454 * @pre_parse_func: (nullable): a function to call before parsing, or %NULL
2455 * @post_parse_func: (nullable): a function to call after parsing, or %NULL
2457 * Associates two functions with @group which will be called
2458 * from g_option_context_parse() before the first option is parsed
2459 * and after the last option has been parsed, respectively.
2461 * Note that the user data to be passed to @pre_parse_func and
2462 * @post_parse_func can be specified when constructing the group
2463 * with g_option_group_new().
2468 g_option_group_set_parse_hooks (GOptionGroup *group,
2469 GOptionParseFunc pre_parse_func,
2470 GOptionParseFunc post_parse_func)
2472 g_return_if_fail (group != NULL);
2474 group->pre_parse_func = pre_parse_func;
2475 group->post_parse_func = post_parse_func;
2479 * g_option_group_set_error_hook:
2480 * @group: a #GOptionGroup
2481 * @error_func: a function to call when an error occurs
2483 * Associates a function with @group which will be called
2484 * from g_option_context_parse() when an error occurs.
2486 * Note that the user data to be passed to @error_func can be
2487 * specified when constructing the group with g_option_group_new().
2492 g_option_group_set_error_hook (GOptionGroup *group,
2493 GOptionErrorFunc error_func)
2495 g_return_if_fail (group != NULL);
2497 group->error_func = error_func;
2502 * g_option_group_set_translate_func:
2503 * @group: a #GOptionGroup
2504 * @func: (nullable): the #GTranslateFunc, or %NULL
2505 * @data: (nullable): user data to pass to @func, or %NULL
2506 * @destroy_notify: (nullable): a function which gets called to free @data, or %NULL
2508 * Sets the function which is used to translate user-visible strings,
2509 * for `--help` output. Different groups can use different
2510 * #GTranslateFuncs. If @func is %NULL, strings are not translated.
2512 * If you are using gettext(), you only need to set the translation
2513 * domain, see g_option_group_set_translation_domain().
2518 g_option_group_set_translate_func (GOptionGroup *group,
2519 GTranslateFunc func,
2521 GDestroyNotify destroy_notify)
2523 g_return_if_fail (group != NULL);
2525 if (group->translate_notify)
2526 group->translate_notify (group->translate_data);
2528 group->translate_func = func;
2529 group->translate_data = data;
2530 group->translate_notify = destroy_notify;
2533 static const gchar *
2534 dgettext_swapped (const gchar *msgid,
2535 const gchar *domainname)
2537 return g_dgettext (domainname, msgid);
2541 * g_option_group_set_translation_domain:
2542 * @group: a #GOptionGroup
2543 * @domain: the domain to use
2545 * A convenience function to use gettext() for translating
2546 * user-visible strings.
2551 g_option_group_set_translation_domain (GOptionGroup *group,
2552 const gchar *domain)
2554 g_return_if_fail (group != NULL);
2556 g_option_group_set_translate_func (group,
2557 (GTranslateFunc)dgettext_swapped,
2563 * g_option_context_set_translate_func:
2564 * @context: a #GOptionContext
2565 * @func: (nullable): the #GTranslateFunc, or %NULL
2566 * @data: (nullable): user data to pass to @func, or %NULL
2567 * @destroy_notify: (nullable): a function which gets called to free @data, or %NULL
2569 * Sets the function which is used to translate the contexts
2570 * user-visible strings, for `--help` output. If @func is %NULL,
2571 * strings are not translated.
2573 * Note that option groups have their own translation functions,
2574 * this function only affects the @parameter_string (see g_option_context_new()),
2575 * the summary (see g_option_context_set_summary()) and the description
2576 * (see g_option_context_set_description()).
2578 * If you are using gettext(), you only need to set the translation
2579 * domain, see g_option_context_set_translation_domain().
2584 g_option_context_set_translate_func (GOptionContext *context,
2585 GTranslateFunc func,
2587 GDestroyNotify destroy_notify)
2589 g_return_if_fail (context != NULL);
2591 if (context->translate_notify)
2592 context->translate_notify (context->translate_data);
2594 context->translate_func = func;
2595 context->translate_data = data;
2596 context->translate_notify = destroy_notify;
2600 * g_option_context_set_translation_domain:
2601 * @context: a #GOptionContext
2602 * @domain: the domain to use
2604 * A convenience function to use gettext() for translating
2605 * user-visible strings.
2610 g_option_context_set_translation_domain (GOptionContext *context,
2611 const gchar *domain)
2613 g_return_if_fail (context != NULL);
2615 g_option_context_set_translate_func (context,
2616 (GTranslateFunc)dgettext_swapped,
2622 * g_option_context_set_summary:
2623 * @context: a #GOptionContext
2624 * @summary: (nullable): a string to be shown in `--help` output
2625 * before the list of options, or %NULL
2627 * Adds a string to be displayed in `--help` output before the list
2628 * of options. This is typically a summary of the program functionality.
2630 * Note that the summary is translated (see
2631 * g_option_context_set_translate_func() and
2632 * g_option_context_set_translation_domain()).
2637 g_option_context_set_summary (GOptionContext *context,
2638 const gchar *summary)
2640 g_return_if_fail (context != NULL);
2642 g_free (context->summary);
2643 context->summary = g_strdup (summary);
2648 * g_option_context_get_summary:
2649 * @context: a #GOptionContext
2651 * Returns the summary. See g_option_context_set_summary().
2653 * Returns: the summary
2658 g_option_context_get_summary (GOptionContext *context)
2660 g_return_val_if_fail (context != NULL, NULL);
2662 return context->summary;
2666 * g_option_context_set_description:
2667 * @context: a #GOptionContext
2668 * @description: (nullable): a string to be shown in `--help` output
2669 * after the list of options, or %NULL
2671 * Adds a string to be displayed in `--help` output after the list
2672 * of options. This text often includes a bug reporting address.
2674 * Note that the summary is translated (see
2675 * g_option_context_set_translate_func()).
2680 g_option_context_set_description (GOptionContext *context,
2681 const gchar *description)
2683 g_return_if_fail (context != NULL);
2685 g_free (context->description);
2686 context->description = g_strdup (description);
2691 * g_option_context_get_description:
2692 * @context: a #GOptionContext
2694 * Returns the description. See g_option_context_set_description().
2696 * Returns: the description
2701 g_option_context_get_description (GOptionContext *context)
2703 g_return_val_if_fail (context != NULL, NULL);
2705 return context->description;
2709 * g_option_context_parse_strv:
2710 * @context: a #GOptionContext
2711 * @arguments: (inout) (array zero-terminated=1): a pointer to the
2712 * command line arguments (which must be in UTF-8 on Windows)
2713 * @error: a return location for errors
2715 * Parses the command line arguments.
2717 * This function is similar to g_option_context_parse() except that it
2718 * respects the normal memory rules when dealing with a strv instead of
2719 * assuming that the passed-in array is the argv of the main function.
2721 * In particular, strings that are removed from the arguments list will
2722 * be freed using g_free().
2724 * On Windows, the strings are expected to be in UTF-8. This is in
2725 * contrast to g_option_context_parse() which expects them to be in the
2726 * system codepage, which is how they are passed as @argv to main().
2727 * See g_win32_get_command_line() for a solution.
2729 * This function is useful if you are trying to use #GOptionContext with
2732 * Returns: %TRUE if the parsing was successful,
2733 * %FALSE if an error occurred
2738 g_option_context_parse_strv (GOptionContext *context,
2745 context->strv_mode = TRUE;
2746 argc = g_strv_length (*arguments);
2747 success = g_option_context_parse (context, &argc, arguments, error);
2748 context->strv_mode = FALSE;