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 (context != NULL);
659 g_return_if_fail (entries != NULL);
661 if (!context->main_group)
662 context->main_group = g_option_group_new (NULL, NULL, NULL, NULL, NULL);
664 g_option_group_add_entries (context->main_group, entries);
665 g_option_group_set_translation_domain (context->main_group, translation_domain);
669 calculate_max_length (GOptionGroup *group,
673 gsize i, len, max_length;
674 const gchar *long_name;
678 for (i = 0; i < group->n_entries; i++)
680 entry = &group->entries[i];
682 if (entry->flags & G_OPTION_FLAG_HIDDEN)
685 long_name = g_hash_table_lookup (aliases, &entry->long_name);
687 long_name = entry->long_name;
688 len = _g_utf8_strwidth (long_name);
690 if (entry->short_name)
693 if (!NO_ARG (entry) && entry->arg_description)
694 len += 1 + _g_utf8_strwidth (TRANSLATE (group, entry->arg_description));
696 max_length = MAX (max_length, len);
703 print_entry (GOptionGroup *group,
705 const GOptionEntry *entry,
710 const gchar *long_name;
712 if (entry->flags & G_OPTION_FLAG_HIDDEN)
715 if (entry->long_name[0] == 0)
718 long_name = g_hash_table_lookup (aliases, &entry->long_name);
720 long_name = entry->long_name;
722 str = g_string_new (NULL);
724 if (entry->short_name)
725 g_string_append_printf (str, " -%c, --%s", entry->short_name, long_name);
727 g_string_append_printf (str, " --%s", long_name);
729 if (entry->arg_description)
730 g_string_append_printf (str, "=%s", TRANSLATE (group, entry->arg_description));
732 g_string_append_printf (string, "%s%*s %s\n", str->str,
733 (int) (max_length + 4 - _g_utf8_strwidth (str->str)), "",
734 entry->description ? TRANSLATE (group, entry->description) : "");
735 g_string_free (str, TRUE);
739 group_has_visible_entries (GOptionContext *context,
741 gboolean main_entries)
743 GOptionFlags reject_filter = G_OPTION_FLAG_HIDDEN;
746 gboolean main_group = group == context->main_group;
749 reject_filter |= G_OPTION_FLAG_IN_MAIN;
751 for (i = 0, l = (group ? group->n_entries : 0); i < l; i++)
753 entry = &group->entries[i];
755 if (main_entries && !main_group && !(entry->flags & G_OPTION_FLAG_IN_MAIN))
757 if (entry->long_name[0] == 0) /* ignore rest entry */
759 if (!(entry->flags & reject_filter))
767 group_list_has_visible_entries (GOptionContext *context,
769 gboolean main_entries)
773 if (group_has_visible_entries (context, group_list->data, main_entries))
776 group_list = group_list->next;
783 context_has_h_entry (GOptionContext *context)
788 if (context->main_group)
790 for (i = 0; i < context->main_group->n_entries; i++)
792 if (context->main_group->entries[i].short_name == 'h')
797 for (list = context->groups; list != NULL; list = g_list_next (list))
801 group = (GOptionGroup*)list->data;
802 for (i = 0; i < group->n_entries; i++)
804 if (group->entries[i].short_name == 'h')
812 * g_option_context_get_help:
813 * @context: a #GOptionContext
814 * @main_help: if %TRUE, only include the main group
815 * @group: (nullable): the #GOptionGroup to create help for, or %NULL
817 * Returns a formatted, translated help text for the given context.
818 * To obtain the text produced by `--help`, call
819 * `g_option_context_get_help (context, TRUE, NULL)`.
820 * To obtain the text produced by `--help-all`, call
821 * `g_option_context_get_help (context, FALSE, NULL)`.
822 * To obtain the help text for an option group, call
823 * `g_option_context_get_help (context, FALSE, group)`.
825 * Returns: A newly allocated string containing the help text
830 g_option_context_get_help (GOptionContext *context,
835 gint max_length = 0, len;
838 GHashTable *shadow_map;
841 const gchar *rest_description;
845 g_return_val_if_fail (context != NULL, NULL);
847 string = g_string_sized_new (1024);
849 rest_description = NULL;
850 if (context->main_group)
853 for (i = 0; i < context->main_group->n_entries; i++)
855 entry = &context->main_group->entries[i];
856 if (entry->long_name[0] == 0)
858 rest_description = TRANSLATE (context->main_group, entry->arg_description);
864 g_string_append_printf (string, "%s\n %s", _("Usage:"), g_get_prgname ());
865 if (context->help_enabled ||
866 (context->main_group && context->main_group->n_entries > 0) ||
867 context->groups != NULL)
868 g_string_append_printf (string, " %s", _("[OPTION…]"));
870 if (rest_description)
872 g_string_append (string, " ");
873 g_string_append (string, rest_description);
876 if (context->parameter_string)
878 g_string_append (string, " ");
879 g_string_append (string, TRANSLATE (context, context->parameter_string));
882 g_string_append (string, "\n\n");
884 if (context->summary)
886 g_string_append (string, TRANSLATE (context, context->summary));
887 g_string_append (string, "\n\n");
890 memset (seen, 0, sizeof (gboolean) * 256);
891 shadow_map = g_hash_table_new (g_str_hash, g_str_equal);
892 aliases = g_hash_table_new_full (NULL, NULL, NULL, g_free);
894 if (context->main_group)
896 for (i = 0; i < context->main_group->n_entries; i++)
898 entry = &context->main_group->entries[i];
899 g_hash_table_insert (shadow_map,
900 (gpointer)entry->long_name,
903 if (seen[(guchar)entry->short_name])
904 entry->short_name = 0;
906 seen[(guchar)entry->short_name] = TRUE;
910 list = context->groups;
913 GOptionGroup *g = list->data;
914 for (i = 0; i < g->n_entries; i++)
916 entry = &g->entries[i];
917 if (g_hash_table_lookup (shadow_map, entry->long_name) &&
918 !(entry->flags & G_OPTION_FLAG_NOALIAS))
920 g_hash_table_insert (aliases, &entry->long_name,
921 g_strdup_printf ("%s-%s", g->name, entry->long_name));
924 g_hash_table_insert (shadow_map, (gpointer)entry->long_name, entry);
926 if (seen[(guchar)entry->short_name] &&
927 !(entry->flags & G_OPTION_FLAG_NOALIAS))
928 entry->short_name = 0;
930 seen[(guchar)entry->short_name] = TRUE;
935 g_hash_table_destroy (shadow_map);
937 list = context->groups;
939 if (context->help_enabled)
941 max_length = _g_utf8_strwidth ("-?, --help");
945 len = _g_utf8_strwidth ("--help-all");
946 max_length = MAX (max_length, len);
950 if (context->main_group)
952 len = calculate_max_length (context->main_group, aliases);
953 max_length = MAX (max_length, len);
958 GOptionGroup *g = list->data;
960 if (context->help_enabled)
962 /* First, we check the --help-<groupname> options */
963 len = _g_utf8_strwidth ("--help-") + _g_utf8_strwidth (g->name);
964 max_length = MAX (max_length, len);
967 /* Then we go through the entries */
968 len = calculate_max_length (g, aliases);
969 max_length = MAX (max_length, len);
974 /* Add a bit of padding */
977 if (!group && context->help_enabled)
979 list = context->groups;
981 token = context_has_h_entry (context) ? '?' : 'h';
983 g_string_append_printf (string, "%s\n -%c, --%-*s %s\n",
984 _("Help Options:"), token, max_length - 4, "help",
985 _("Show help options"));
987 /* We only want --help-all when there are groups */
989 g_string_append_printf (string, " --%-*s %s\n",
990 max_length, "help-all",
991 _("Show all help options"));
995 GOptionGroup *g = list->data;
997 if (group_has_visible_entries (context, g, FALSE))
998 g_string_append_printf (string, " --help-%-*s %s\n",
999 max_length - 5, g->name,
1000 TRANSLATE (g, g->help_description));
1005 g_string_append (string, "\n");
1010 /* Print a certain group */
1012 if (group_has_visible_entries (context, group, FALSE))
1014 g_string_append (string, TRANSLATE (group, group->description));
1015 g_string_append (string, "\n");
1016 for (i = 0; i < group->n_entries; i++)
1017 print_entry (group, max_length, &group->entries[i], string, aliases);
1018 g_string_append (string, "\n");
1021 else if (!main_help)
1023 /* Print all groups */
1025 list = context->groups;
1029 GOptionGroup *g = list->data;
1031 if (group_has_visible_entries (context, g, FALSE))
1033 g_string_append (string, g->description);
1034 g_string_append (string, "\n");
1035 for (i = 0; i < g->n_entries; i++)
1036 if (!(g->entries[i].flags & G_OPTION_FLAG_IN_MAIN))
1037 print_entry (g, max_length, &g->entries[i], string, aliases);
1039 g_string_append (string, "\n");
1046 /* Print application options if --help or --help-all has been specified */
1047 if ((main_help || !group) &&
1048 (group_has_visible_entries (context, context->main_group, TRUE) ||
1049 group_list_has_visible_entries (context, context->groups, TRUE)))
1051 list = context->groups;
1053 if (context->help_enabled || list)
1054 g_string_append (string, _("Application Options:"));
1056 g_string_append (string, _("Options:"));
1057 g_string_append (string, "\n");
1058 if (context->main_group)
1059 for (i = 0; i < context->main_group->n_entries; i++)
1060 print_entry (context->main_group, max_length,
1061 &context->main_group->entries[i], string, aliases);
1063 while (list != NULL)
1065 GOptionGroup *g = list->data;
1067 /* Print main entries from other groups */
1068 for (i = 0; i < g->n_entries; i++)
1069 if (g->entries[i].flags & G_OPTION_FLAG_IN_MAIN)
1070 print_entry (g, max_length, &g->entries[i], string, aliases);
1075 g_string_append (string, "\n");
1078 if (context->description)
1080 g_string_append (string, TRANSLATE (context, context->description));
1081 g_string_append (string, "\n");
1084 g_hash_table_destroy (aliases);
1086 return g_string_free (string, FALSE);
1091 print_help (GOptionContext *context,
1093 GOptionGroup *group)
1097 help = g_option_context_get_help (context, main_help, group);
1098 g_print ("%s", help);
1105 parse_int (const gchar *arg_name,
1114 tmp = strtol (arg, &end, 0);
1116 if (*arg == '\0' || *end != '\0')
1119 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1120 _("Cannot parse integer value “%s” for %s"),
1126 if (*result != tmp || errno == ERANGE)
1129 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1130 _("Integer value “%s” for %s out of range"),
1140 parse_double (const gchar *arg_name,
1149 tmp = g_strtod (arg, &end);
1151 if (*arg == '\0' || *end != '\0')
1154 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1155 _("Cannot parse double value “%s” for %s"),
1159 if (errno == ERANGE)
1162 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1163 _("Double value “%s” for %s out of range"),
1175 parse_int64 (const gchar *arg_name,
1184 tmp = g_ascii_strtoll (arg, &end, 0);
1186 if (*arg == '\0' || *end != '\0')
1189 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1190 _("Cannot parse integer value “%s” for %s"),
1194 if (errno == ERANGE)
1197 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1198 _("Integer value “%s” for %s out of range"),
1210 get_change (GOptionContext *context,
1211 GOptionArg arg_type,
1215 Change *change = NULL;
1217 for (list = context->changes; list != NULL; list = list->next)
1219 change = list->data;
1221 if (change->arg_data == arg_data)
1225 change = g_new0 (Change, 1);
1226 change->arg_type = arg_type;
1227 change->arg_data = arg_data;
1229 context->changes = g_list_prepend (context->changes, change);
1237 add_pending_null (GOptionContext *context,
1243 n = g_new0 (PendingNull, 1);
1247 context->pending_nulls = g_list_prepend (context->pending_nulls, n);
1251 parse_arg (GOptionContext *context,
1252 GOptionGroup *group,
1253 GOptionEntry *entry,
1255 const gchar *option_name,
1261 g_assert (value || OPTIONAL_ARG (entry) || NO_ARG (entry));
1265 case G_OPTION_ARG_NONE:
1267 (void) get_change (context, G_OPTION_ARG_NONE,
1270 *(gboolean *)entry->arg_data = !(entry->flags & G_OPTION_FLAG_REVERSE);
1273 case G_OPTION_ARG_STRING:
1278 if (!context->strv_mode)
1279 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1281 data = g_strdup (value);
1283 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1289 change = get_change (context, G_OPTION_ARG_STRING,
1292 if (!change->allocated.str)
1293 change->prev.str = *(gchar **)entry->arg_data;
1295 g_free (change->allocated.str);
1297 change->allocated.str = data;
1299 *(gchar **)entry->arg_data = data;
1302 case G_OPTION_ARG_STRING_ARRAY:
1307 if (!context->strv_mode)
1308 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1310 data = g_strdup (value);
1312 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1318 change = get_change (context, G_OPTION_ARG_STRING_ARRAY,
1321 if (change->allocated.array.len == 0)
1323 change->prev.array = *(gchar ***)entry->arg_data;
1324 change->allocated.array.data = g_new (gchar *, 2);
1327 change->allocated.array.data =
1328 g_renew (gchar *, change->allocated.array.data,
1329 change->allocated.array.len + 2);
1331 change->allocated.array.data[change->allocated.array.len] = data;
1332 change->allocated.array.data[change->allocated.array.len + 1] = NULL;
1334 change->allocated.array.len ++;
1336 *(gchar ***)entry->arg_data = change->allocated.array.data;
1341 case G_OPTION_ARG_FILENAME:
1346 if (!context->strv_mode)
1347 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1349 data = g_strdup (value);
1354 data = g_strdup (value);
1356 change = get_change (context, G_OPTION_ARG_FILENAME,
1359 if (!change->allocated.str)
1360 change->prev.str = *(gchar **)entry->arg_data;
1362 g_free (change->allocated.str);
1364 change->allocated.str = data;
1366 *(gchar **)entry->arg_data = data;
1370 case G_OPTION_ARG_FILENAME_ARRAY:
1375 if (!context->strv_mode)
1376 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1378 data = g_strdup (value);
1383 data = g_strdup (value);
1385 change = get_change (context, G_OPTION_ARG_STRING_ARRAY,
1388 if (change->allocated.array.len == 0)
1390 change->prev.array = *(gchar ***)entry->arg_data;
1391 change->allocated.array.data = g_new (gchar *, 2);
1394 change->allocated.array.data =
1395 g_renew (gchar *, change->allocated.array.data,
1396 change->allocated.array.len + 2);
1398 change->allocated.array.data[change->allocated.array.len] = data;
1399 change->allocated.array.data[change->allocated.array.len + 1] = NULL;
1401 change->allocated.array.len ++;
1403 *(gchar ***)entry->arg_data = change->allocated.array.data;
1408 case G_OPTION_ARG_INT:
1412 if (!parse_int (option_name, value,
1417 change = get_change (context, G_OPTION_ARG_INT,
1419 change->prev.integer = *(gint *)entry->arg_data;
1420 *(gint *)entry->arg_data = data;
1423 case G_OPTION_ARG_CALLBACK:
1428 if (!value && entry->flags & G_OPTION_FLAG_OPTIONAL_ARG)
1430 else if (entry->flags & G_OPTION_FLAG_NO_ARG)
1432 else if (entry->flags & G_OPTION_FLAG_FILENAME)
1435 if (!context->strv_mode)
1436 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1438 data = g_strdup (value);
1440 data = g_strdup (value);
1444 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1446 if (!(entry->flags & (G_OPTION_FLAG_NO_ARG|G_OPTION_FLAG_OPTIONAL_ARG)) &&
1450 retval = (* (GOptionArgFunc) entry->arg_data) (option_name, data, group->user_data, error);
1452 if (!retval && error != NULL && *error == NULL)
1454 G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
1455 _("Error parsing option %s"), option_name);
1463 case G_OPTION_ARG_DOUBLE:
1467 if (!parse_double (option_name, value,
1474 change = get_change (context, G_OPTION_ARG_DOUBLE,
1476 change->prev.dbl = *(gdouble *)entry->arg_data;
1477 *(gdouble *)entry->arg_data = data;
1480 case G_OPTION_ARG_INT64:
1484 if (!parse_int64 (option_name, value,
1491 change = get_change (context, G_OPTION_ARG_INT64,
1493 change->prev.int64 = *(gint64 *)entry->arg_data;
1494 *(gint64 *)entry->arg_data = data;
1498 g_assert_not_reached ();
1505 parse_short_option (GOptionContext *context,
1506 GOptionGroup *group,
1517 for (j = 0; j < group->n_entries; j++)
1519 if (arg == group->entries[j].short_name)
1522 gchar *value = NULL;
1524 option_name = g_strdup_printf ("-%c", group->entries[j].short_name);
1526 if (NO_ARG (&group->entries[j]))
1533 G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
1534 _("Error parsing option %s"), option_name);
1535 g_free (option_name);
1539 if (idx < *argc - 1)
1541 if (!OPTIONAL_ARG (&group->entries[j]))
1543 value = (*argv)[idx + 1];
1544 add_pending_null (context, &((*argv)[idx + 1]), NULL);
1549 if ((*argv)[idx + 1][0] == '-')
1553 value = (*argv)[idx + 1];
1554 add_pending_null (context, &((*argv)[idx + 1]), NULL);
1559 else if (idx >= *argc - 1 && OPTIONAL_ARG (&group->entries[j]))
1564 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1565 _("Missing argument for %s"), option_name);
1566 g_free (option_name);
1571 if (!parse_arg (context, group, &group->entries[j],
1572 value, option_name, error))
1574 g_free (option_name);
1578 g_free (option_name);
1587 parse_long_option (GOptionContext *context,
1588 GOptionGroup *group,
1599 for (j = 0; j < group->n_entries; j++)
1604 if (aliased && (group->entries[j].flags & G_OPTION_FLAG_NOALIAS))
1607 if (NO_ARG (&group->entries[j]) &&
1608 strcmp (arg, group->entries[j].long_name) == 0)
1613 option_name = g_strconcat ("--", group->entries[j].long_name, NULL);
1614 retval = parse_arg (context, group, &group->entries[j],
1615 NULL, option_name, error);
1616 g_free (option_name);
1618 add_pending_null (context, &((*argv)[*idx]), NULL);
1625 gint len = strlen (group->entries[j].long_name);
1627 if (strncmp (arg, group->entries[j].long_name, len) == 0 &&
1628 (arg[len] == '=' || arg[len] == 0))
1630 gchar *value = NULL;
1633 add_pending_null (context, &((*argv)[*idx]), NULL);
1634 option_name = g_strconcat ("--", group->entries[j].long_name, NULL);
1636 if (arg[len] == '=')
1637 value = arg + len + 1;
1638 else if (*idx < *argc - 1)
1640 if (!OPTIONAL_ARG (&group->entries[j]))
1642 value = (*argv)[*idx + 1];
1643 add_pending_null (context, &((*argv)[*idx + 1]), NULL);
1648 if ((*argv)[*idx + 1][0] == '-')
1651 retval = parse_arg (context, group, &group->entries[j],
1652 NULL, option_name, error);
1654 g_free (option_name);
1659 value = (*argv)[*idx + 1];
1660 add_pending_null (context, &((*argv)[*idx + 1]), NULL);
1665 else if (*idx >= *argc - 1 && OPTIONAL_ARG (&group->entries[j]))
1668 retval = parse_arg (context, group, &group->entries[j],
1669 NULL, option_name, error);
1671 g_free (option_name);
1677 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1678 _("Missing argument for %s"), option_name);
1679 g_free (option_name);
1683 if (!parse_arg (context, group, &group->entries[j],
1684 value, option_name, error))
1686 g_free (option_name);
1690 g_free (option_name);
1700 parse_remaining_arg (GOptionContext *context,
1701 GOptionGroup *group,
1710 for (j = 0; j < group->n_entries; j++)
1715 if (group->entries[j].long_name[0])
1718 g_return_val_if_fail (group->entries[j].arg == G_OPTION_ARG_CALLBACK ||
1719 group->entries[j].arg == G_OPTION_ARG_STRING_ARRAY ||
1720 group->entries[j].arg == G_OPTION_ARG_FILENAME_ARRAY, FALSE);
1722 add_pending_null (context, &((*argv)[*idx]), NULL);
1724 if (!parse_arg (context, group, &group->entries[j], (*argv)[*idx], "", error))
1735 free_changes_list (GOptionContext *context,
1740 for (list = context->changes; list != NULL; list = list->next)
1742 Change *change = list->data;
1746 switch (change->arg_type)
1748 case G_OPTION_ARG_NONE:
1749 *(gboolean *)change->arg_data = change->prev.bool;
1751 case G_OPTION_ARG_INT:
1752 *(gint *)change->arg_data = change->prev.integer;
1754 case G_OPTION_ARG_STRING:
1755 case G_OPTION_ARG_FILENAME:
1756 g_free (change->allocated.str);
1757 *(gchar **)change->arg_data = change->prev.str;
1759 case G_OPTION_ARG_STRING_ARRAY:
1760 case G_OPTION_ARG_FILENAME_ARRAY:
1761 g_strfreev (change->allocated.array.data);
1762 *(gchar ***)change->arg_data = change->prev.array;
1764 case G_OPTION_ARG_DOUBLE:
1765 *(gdouble *)change->arg_data = change->prev.dbl;
1767 case G_OPTION_ARG_INT64:
1768 *(gint64 *)change->arg_data = change->prev.int64;
1771 g_assert_not_reached ();
1778 g_list_free (context->changes);
1779 context->changes = NULL;
1783 free_pending_nulls (GOptionContext *context,
1784 gboolean perform_nulls)
1788 for (list = context->pending_nulls; list != NULL; list = list->next)
1790 PendingNull *n = list->data;
1796 /* Copy back the short options */
1798 strcpy (*n->ptr + 1, n->value);
1802 if (context->strv_mode)
1813 g_list_free (context->pending_nulls);
1814 context->pending_nulls = NULL;
1817 /* Use a platform-specific mechanism to look up the first argument to
1818 * the current process.
1819 * Note if you implement this for other platforms, also add it to
1820 * tests/option-argv0.c
1823 platform_get_argv0 (void)
1825 #ifdef HAVE_PROC_SELF_CMDLINE
1830 if (!g_file_get_contents ("/proc/self/cmdline",
1836 /* Sanity check for a NUL terminator. */
1837 g_assert (memchr (cmdline, 0, len));
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_newa (gboolean, arg_length);
2119 memset (nulled_out, 0, arg_length * sizeof (gboolean));
2120 for (j = 0; j < arg_length; j++)
2122 if (context->help_enabled && (arg[j] == '?' ||
2123 (arg[j] == 'h' && !has_h_entry)))
2124 print_help (context, TRUE, NULL);
2126 if (context->main_group &&
2127 !parse_short_option (context, context->main_group,
2129 argc, argv, error, &parsed))
2133 /* Try the groups */
2134 list = context->groups;
2137 GOptionGroup *group = list->data;
2138 if (!parse_short_option (context, group, i, &new_i, arg[j],
2139 argc, argv, error, &parsed))
2147 if (context->ignore_unknown && parsed)
2148 nulled_out[j] = TRUE;
2149 else if (context->ignore_unknown)
2153 /* !context->ignore_unknown && parsed */
2155 if (context->ignore_unknown)
2157 gchar *new_arg = NULL;
2159 for (j = 0; j < arg_length; j++)
2164 new_arg = g_malloc (arg_length + 1);
2165 new_arg[arg_index++] = arg[j];
2169 new_arg[arg_index] = '\0';
2170 add_pending_null (context, &((*argv)[i]), new_arg);
2175 add_pending_null (context, &((*argv)[i]), NULL);
2183 if (!parsed && !context->ignore_unknown)
2186 G_OPTION_ERROR, G_OPTION_ERROR_UNKNOWN_OPTION,
2187 _("Unknown option %s"), (*argv)[i]);
2193 if (context->strict_posix)
2194 stop_parsing = TRUE;
2196 /* Collect remaining args */
2197 if (context->main_group &&
2198 !parse_remaining_arg (context, context->main_group, &i,
2199 argc, argv, error, &parsed))
2202 if (!parsed && (has_unknown || (*argv)[i][0] == '-'))
2207 if (separator_pos > 0)
2208 add_pending_null (context, &((*argv)[separator_pos]), NULL);
2212 /* Call post-parse hooks */
2213 list = context->groups;
2216 GOptionGroup *group = list->data;
2218 if (group->post_parse_func)
2220 if (!(* group->post_parse_func) (context, group,
2221 group->user_data, error))
2228 if (context->main_group && context->main_group->post_parse_func)
2230 if (!(* context->main_group->post_parse_func) (context, context->main_group,
2231 context->main_group->user_data, error))
2237 free_pending_nulls (context, TRUE);
2239 for (i = 1; i < *argc; i++)
2241 for (k = i; k < *argc; k++)
2242 if ((*argv)[k] != NULL)
2248 for (j = i + k; j < *argc; j++)
2250 (*argv)[j-k] = (*argv)[j];
2262 /* Call error hooks */
2263 list = context->groups;
2266 GOptionGroup *group = list->data;
2268 if (group->error_func)
2269 (* group->error_func) (context, group,
2270 group->user_data, error);
2275 if (context->main_group && context->main_group->error_func)
2276 (* context->main_group->error_func) (context, context->main_group,
2277 context->main_group->user_data, error);
2279 free_changes_list (context, TRUE);
2280 free_pending_nulls (context, FALSE);
2286 * g_option_group_new:
2287 * @name: the name for the option group, this is used to provide
2288 * help for the options in this group with `--help-`@name
2289 * @description: a description for this group to be shown in
2290 * `--help`. This string is translated using the translation
2291 * domain or translation function of the group
2292 * @help_description: a description for the `--help-`@name option.
2293 * This string is translated using the translation domain or translation function
2295 * @user_data: (nullable): user data that will be passed to the pre- and post-parse hooks,
2296 * the error hook and to callbacks of %G_OPTION_ARG_CALLBACK options, or %NULL
2297 * @destroy: (nullable): a function that will be called to free @user_data, or %NULL
2299 * Creates a new #GOptionGroup.
2301 * Returns: a newly created option group. It should be added
2302 * to a #GOptionContext or freed with g_option_group_unref().
2307 g_option_group_new (const gchar *name,
2308 const gchar *description,
2309 const gchar *help_description,
2311 GDestroyNotify destroy)
2314 GOptionGroup *group;
2316 group = g_new0 (GOptionGroup, 1);
2317 group->ref_count = 1;
2318 group->name = g_strdup (name);
2319 group->description = g_strdup (description);
2320 group->help_description = g_strdup (help_description);
2321 group->user_data = user_data;
2322 group->destroy_notify = destroy;
2329 * g_option_group_free:
2330 * @group: a #GOptionGroup
2332 * Frees a #GOptionGroup. Note that you must not free groups
2333 * which have been added to a #GOptionContext.
2337 * Deprecated: 2.44: Use g_option_group_unref() instead.
2340 g_option_group_free (GOptionGroup *group)
2342 g_option_group_unref (group);
2346 * g_option_group_ref:
2347 * @group: a #GOptionGroup
2349 * Increments the reference count of @group by one.
2351 * Returns: a #GOptionGroup
2356 g_option_group_ref (GOptionGroup *group)
2358 g_return_val_if_fail (group != NULL, NULL);
2366 * g_option_group_unref:
2367 * @group: a #GOptionGroup
2369 * Decrements the reference count of @group by one.
2370 * If the reference count drops to 0, the @group will be freed.
2371 * and all memory allocated by the @group is released.
2376 g_option_group_unref (GOptionGroup *group)
2378 g_return_if_fail (group != NULL);
2380 if (--group->ref_count == 0)
2382 g_free (group->name);
2383 g_free (group->description);
2384 g_free (group->help_description);
2386 g_free (group->entries);
2388 if (group->destroy_notify)
2389 (* group->destroy_notify) (group->user_data);
2391 if (group->translate_notify)
2392 (* group->translate_notify) (group->translate_data);
2399 * g_option_group_add_entries:
2400 * @group: a #GOptionGroup
2401 * @entries: a %NULL-terminated array of #GOptionEntrys
2403 * Adds the options specified in @entries to @group.
2408 g_option_group_add_entries (GOptionGroup *group,
2409 const GOptionEntry *entries)
2413 g_return_if_fail (group != NULL);
2414 g_return_if_fail (entries != NULL);
2416 for (n_entries = 0; entries[n_entries].long_name != NULL; n_entries++) ;
2418 group->entries = g_renew (GOptionEntry, group->entries, group->n_entries + n_entries);
2420 /* group->entries could be NULL in the trivial case where we add no
2421 * entries to no entries */
2423 memcpy (group->entries + group->n_entries, entries, sizeof (GOptionEntry) * n_entries);
2425 for (i = group->n_entries; i < group->n_entries + n_entries; i++)
2427 gchar c = group->entries[i].short_name;
2429 if (c == '-' || (c != 0 && !g_ascii_isprint (c)))
2431 g_warning (G_STRLOC ": ignoring invalid short option '%c' (%d) in entry %s:%s",
2432 c, c, group->name, group->entries[i].long_name);
2433 group->entries[i].short_name = '\0';
2436 if (group->entries[i].arg != G_OPTION_ARG_NONE &&
2437 (group->entries[i].flags & G_OPTION_FLAG_REVERSE) != 0)
2439 g_warning (G_STRLOC ": ignoring reverse flag on option of arg-type %d in entry %s:%s",
2440 group->entries[i].arg, group->name, group->entries[i].long_name);
2442 group->entries[i].flags &= ~G_OPTION_FLAG_REVERSE;
2445 if (group->entries[i].arg != G_OPTION_ARG_CALLBACK &&
2446 (group->entries[i].flags & (G_OPTION_FLAG_NO_ARG|G_OPTION_FLAG_OPTIONAL_ARG|G_OPTION_FLAG_FILENAME)) != 0)
2448 g_warning (G_STRLOC ": ignoring no-arg, optional-arg or filename flags (%d) on option of arg-type %d in entry %s:%s",
2449 group->entries[i].flags, group->entries[i].arg, group->name, group->entries[i].long_name);
2451 group->entries[i].flags &= ~(G_OPTION_FLAG_NO_ARG|G_OPTION_FLAG_OPTIONAL_ARG|G_OPTION_FLAG_FILENAME);
2455 group->n_entries += n_entries;
2459 * g_option_group_set_parse_hooks:
2460 * @group: a #GOptionGroup
2461 * @pre_parse_func: (nullable): a function to call before parsing, or %NULL
2462 * @post_parse_func: (nullable): a function to call after parsing, or %NULL
2464 * Associates two functions with @group which will be called
2465 * from g_option_context_parse() before the first option is parsed
2466 * and after the last option has been parsed, respectively.
2468 * Note that the user data to be passed to @pre_parse_func and
2469 * @post_parse_func can be specified when constructing the group
2470 * with g_option_group_new().
2475 g_option_group_set_parse_hooks (GOptionGroup *group,
2476 GOptionParseFunc pre_parse_func,
2477 GOptionParseFunc post_parse_func)
2479 g_return_if_fail (group != NULL);
2481 group->pre_parse_func = pre_parse_func;
2482 group->post_parse_func = post_parse_func;
2486 * g_option_group_set_error_hook:
2487 * @group: a #GOptionGroup
2488 * @error_func: a function to call when an error occurs
2490 * Associates a function with @group which will be called
2491 * from g_option_context_parse() when an error occurs.
2493 * Note that the user data to be passed to @error_func can be
2494 * specified when constructing the group with g_option_group_new().
2499 g_option_group_set_error_hook (GOptionGroup *group,
2500 GOptionErrorFunc error_func)
2502 g_return_if_fail (group != NULL);
2504 group->error_func = error_func;
2509 * g_option_group_set_translate_func:
2510 * @group: a #GOptionGroup
2511 * @func: (nullable): the #GTranslateFunc, or %NULL
2512 * @data: (nullable): user data to pass to @func, or %NULL
2513 * @destroy_notify: (nullable): a function which gets called to free @data, or %NULL
2515 * Sets the function which is used to translate user-visible strings,
2516 * for `--help` output. Different groups can use different
2517 * #GTranslateFuncs. If @func is %NULL, strings are not translated.
2519 * If you are using gettext(), you only need to set the translation
2520 * domain, see g_option_group_set_translation_domain().
2525 g_option_group_set_translate_func (GOptionGroup *group,
2526 GTranslateFunc func,
2528 GDestroyNotify destroy_notify)
2530 g_return_if_fail (group != NULL);
2532 if (group->translate_notify)
2533 group->translate_notify (group->translate_data);
2535 group->translate_func = func;
2536 group->translate_data = data;
2537 group->translate_notify = destroy_notify;
2540 static const gchar *
2541 dgettext_swapped (const gchar *msgid,
2542 const gchar *domainname)
2544 return g_dgettext (domainname, msgid);
2548 * g_option_group_set_translation_domain:
2549 * @group: a #GOptionGroup
2550 * @domain: the domain to use
2552 * A convenience function to use gettext() for translating
2553 * user-visible strings.
2558 g_option_group_set_translation_domain (GOptionGroup *group,
2559 const gchar *domain)
2561 g_return_if_fail (group != NULL);
2563 g_option_group_set_translate_func (group,
2564 (GTranslateFunc)dgettext_swapped,
2570 * g_option_context_set_translate_func:
2571 * @context: a #GOptionContext
2572 * @func: (nullable): the #GTranslateFunc, or %NULL
2573 * @data: (nullable): user data to pass to @func, or %NULL
2574 * @destroy_notify: (nullable): a function which gets called to free @data, or %NULL
2576 * Sets the function which is used to translate the contexts
2577 * user-visible strings, for `--help` output. If @func is %NULL,
2578 * strings are not translated.
2580 * Note that option groups have their own translation functions,
2581 * this function only affects the @parameter_string (see g_option_context_new()),
2582 * the summary (see g_option_context_set_summary()) and the description
2583 * (see g_option_context_set_description()).
2585 * If you are using gettext(), you only need to set the translation
2586 * domain, see g_option_context_set_translation_domain().
2591 g_option_context_set_translate_func (GOptionContext *context,
2592 GTranslateFunc func,
2594 GDestroyNotify destroy_notify)
2596 g_return_if_fail (context != NULL);
2598 if (context->translate_notify)
2599 context->translate_notify (context->translate_data);
2601 context->translate_func = func;
2602 context->translate_data = data;
2603 context->translate_notify = destroy_notify;
2607 * g_option_context_set_translation_domain:
2608 * @context: a #GOptionContext
2609 * @domain: the domain to use
2611 * A convenience function to use gettext() for translating
2612 * user-visible strings.
2617 g_option_context_set_translation_domain (GOptionContext *context,
2618 const gchar *domain)
2620 g_return_if_fail (context != NULL);
2622 g_option_context_set_translate_func (context,
2623 (GTranslateFunc)dgettext_swapped,
2629 * g_option_context_set_summary:
2630 * @context: a #GOptionContext
2631 * @summary: (nullable): a string to be shown in `--help` output
2632 * before the list of options, or %NULL
2634 * Adds a string to be displayed in `--help` output before the list
2635 * of options. This is typically a summary of the program functionality.
2637 * Note that the summary is translated (see
2638 * g_option_context_set_translate_func() and
2639 * g_option_context_set_translation_domain()).
2644 g_option_context_set_summary (GOptionContext *context,
2645 const gchar *summary)
2647 g_return_if_fail (context != NULL);
2649 g_free (context->summary);
2650 context->summary = g_strdup (summary);
2655 * g_option_context_get_summary:
2656 * @context: a #GOptionContext
2658 * Returns the summary. See g_option_context_set_summary().
2660 * Returns: the summary
2665 g_option_context_get_summary (GOptionContext *context)
2667 g_return_val_if_fail (context != NULL, NULL);
2669 return context->summary;
2673 * g_option_context_set_description:
2674 * @context: a #GOptionContext
2675 * @description: (nullable): a string to be shown in `--help` output
2676 * after the list of options, or %NULL
2678 * Adds a string to be displayed in `--help` output after the list
2679 * of options. This text often includes a bug reporting address.
2681 * Note that the summary is translated (see
2682 * g_option_context_set_translate_func()).
2687 g_option_context_set_description (GOptionContext *context,
2688 const gchar *description)
2690 g_return_if_fail (context != NULL);
2692 g_free (context->description);
2693 context->description = g_strdup (description);
2698 * g_option_context_get_description:
2699 * @context: a #GOptionContext
2701 * Returns the description. See g_option_context_set_description().
2703 * Returns: the description
2708 g_option_context_get_description (GOptionContext *context)
2710 g_return_val_if_fail (context != NULL, NULL);
2712 return context->description;
2716 * g_option_context_parse_strv:
2717 * @context: a #GOptionContext
2718 * @arguments: (inout) (array null-terminated=1) (optional): a pointer
2719 * to the command line arguments (which must be in UTF-8 on Windows).
2720 * Starting with GLib 2.62, @arguments can be %NULL, which matches
2721 * g_option_context_parse().
2722 * @error: a return location for errors
2724 * Parses the command line arguments.
2726 * This function is similar to g_option_context_parse() except that it
2727 * respects the normal memory rules when dealing with a strv instead of
2728 * assuming that the passed-in array is the argv of the main function.
2730 * In particular, strings that are removed from the arguments list will
2731 * be freed using g_free().
2733 * On Windows, the strings are expected to be in UTF-8. This is in
2734 * contrast to g_option_context_parse() which expects them to be in the
2735 * system codepage, which is how they are passed as @argv to main().
2736 * See g_win32_get_command_line() for a solution.
2738 * This function is useful if you are trying to use #GOptionContext with
2741 * Returns: %TRUE if the parsing was successful,
2742 * %FALSE if an error occurred
2747 g_option_context_parse_strv (GOptionContext *context,
2754 g_return_val_if_fail (context != NULL, FALSE);
2756 context->strv_mode = TRUE;
2757 argc = arguments && *arguments ? g_strv_length (*arguments) : 0;
2758 success = g_option_context_parse (context, &argc, arguments, error);
2759 context->strv_mode = FALSE;