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 Library General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 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 * Library General Public License for more details.
16 * You should have received a copy of the GNU Library General Public
17 * License 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 #define TRANSLATE(group, str) (((group)->translate_func ? (* (group)->translate_func) ((str), (group)->translate_data) : (str)))
199 #define NO_ARG(entry) ((entry)->arg == G_OPTION_ARG_NONE || \
200 ((entry)->arg == G_OPTION_ARG_CALLBACK && \
201 ((entry)->flags & G_OPTION_FLAG_NO_ARG)))
203 #define OPTIONAL_ARG(entry) ((entry)->arg == G_OPTION_ARG_CALLBACK && \
204 (entry)->flags & G_OPTION_FLAG_OPTIONAL_ARG)
236 struct _GOptionContext
240 gchar *parameter_string;
244 GTranslateFunc translate_func;
245 GDestroyNotify translate_notify;
246 gpointer translate_data;
248 guint help_enabled : 1;
249 guint ignore_unknown : 1;
252 GOptionGroup *main_group;
254 /* We keep a list of change so we can revert them */
257 /* We also keep track of all argv elements
258 * that should be NULLed or modified.
260 GList *pending_nulls;
267 gchar *help_description;
269 GDestroyNotify destroy_notify;
272 GTranslateFunc translate_func;
273 GDestroyNotify translate_notify;
274 gpointer translate_data;
276 GOptionEntry *entries;
279 GOptionParseFunc pre_parse_func;
280 GOptionParseFunc post_parse_func;
281 GOptionErrorFunc error_func;
284 static void free_changes_list (GOptionContext *context,
286 static void free_pending_nulls (GOptionContext *context,
287 gboolean perform_nulls);
291 _g_unichar_get_width (gunichar c)
293 if (G_UNLIKELY (g_unichar_iszerowidth (c)))
296 /* we ignore the fact that we should call g_unichar_iswide_cjk() under
297 * some locales (legacy East Asian ones) */
298 if (g_unichar_iswide (c))
305 _g_utf8_strwidth (const gchar *p)
308 g_return_val_if_fail (p != NULL, 0);
312 len += _g_unichar_get_width (g_utf8_get_char (p));
313 p = g_utf8_next_char (p);
319 G_DEFINE_QUARK (g-option-context-error-quark, g_option_error)
322 * g_option_context_new:
323 * @parameter_string: (allow-none): a string which is displayed in
324 * the first line of `--help` output, after the usage summary
325 * `programname [OPTION...]`
327 * Creates a new option context.
329 * The @parameter_string can serve multiple purposes. It can be used
330 * to add descriptions for "rest" arguments, which are not parsed by
331 * the #GOptionContext, typically something like "FILES" or
332 * "FILE1 FILE2...". If you are using #G_OPTION_REMAINING for
333 * collecting "rest" arguments, GLib handles this automatically by
334 * using the @arg_description of the corresponding #GOptionEntry in
337 * Another usage is to give a short summary of the program
338 * functionality, like " - frob the strings", which will be displayed
339 * in the same line as the usage. For a longer description of the
340 * program functionality that should be displayed as a paragraph
341 * below the usage line, use g_option_context_set_summary().
343 * Note that the @parameter_string is translated using the
344 * function set with g_option_context_set_translate_func(), so
345 * it should normally be passed untranslated.
347 * Returns: a newly created #GOptionContext, which must be
348 * freed with g_option_context_free() after use.
353 g_option_context_new (const gchar *parameter_string)
356 GOptionContext *context;
358 context = g_new0 (GOptionContext, 1);
360 context->parameter_string = g_strdup (parameter_string);
361 context->help_enabled = TRUE;
362 context->ignore_unknown = FALSE;
368 * g_option_context_free:
369 * @context: a #GOptionContext
371 * Frees context and all the groups which have been
374 * Please note that parsed arguments need to be freed separately (see
379 void g_option_context_free (GOptionContext *context)
381 g_return_if_fail (context != NULL);
383 g_list_free_full (context->groups, (GDestroyNotify) g_option_group_free);
385 if (context->main_group)
386 g_option_group_free (context->main_group);
388 free_changes_list (context, FALSE);
389 free_pending_nulls (context, FALSE);
391 g_free (context->parameter_string);
392 g_free (context->summary);
393 g_free (context->description);
395 if (context->translate_notify)
396 (* context->translate_notify) (context->translate_data);
403 * g_option_context_set_help_enabled:
404 * @context: a #GOptionContext
405 * @help_enabled: %TRUE to enable `--help`, %FALSE to disable it
407 * Enables or disables automatic generation of `--help` output.
408 * By default, g_option_context_parse() recognizes `--help`, `-h`,
409 * `-?`, `--help-all` and `--help-groupname` and creates suitable
414 void g_option_context_set_help_enabled (GOptionContext *context,
415 gboolean help_enabled)
418 g_return_if_fail (context != NULL);
420 context->help_enabled = help_enabled;
424 * g_option_context_get_help_enabled:
425 * @context: a #GOptionContext
427 * Returns whether automatic `--help` generation
428 * is turned on for @context. See g_option_context_set_help_enabled().
430 * Returns: %TRUE if automatic help generation is turned on.
435 g_option_context_get_help_enabled (GOptionContext *context)
437 g_return_val_if_fail (context != NULL, FALSE);
439 return context->help_enabled;
443 * g_option_context_set_ignore_unknown_options:
444 * @context: a #GOptionContext
445 * @ignore_unknown: %TRUE to ignore unknown options, %FALSE to produce
446 * an error when unknown options are met
448 * Sets whether to ignore unknown options or not. If an argument is
449 * ignored, it is left in the @argv array after parsing. By default,
450 * g_option_context_parse() treats unknown options as error.
452 * This setting does not affect non-option arguments (i.e. arguments
453 * which don't start with a dash). But note that GOption cannot reliably
454 * determine whether a non-option belongs to a preceding unknown option.
459 g_option_context_set_ignore_unknown_options (GOptionContext *context,
460 gboolean ignore_unknown)
462 g_return_if_fail (context != NULL);
464 context->ignore_unknown = ignore_unknown;
468 * g_option_context_get_ignore_unknown_options:
469 * @context: a #GOptionContext
471 * Returns whether unknown options are ignored or not. See
472 * g_option_context_set_ignore_unknown_options().
474 * Returns: %TRUE if unknown options are ignored.
479 g_option_context_get_ignore_unknown_options (GOptionContext *context)
481 g_return_val_if_fail (context != NULL, FALSE);
483 return context->ignore_unknown;
487 * g_option_context_add_group:
488 * @context: a #GOptionContext
489 * @group: the group to add
491 * Adds a #GOptionGroup to the @context, so that parsing with @context
492 * will recognize the options in the group. Note that the group will
493 * be freed together with the context when g_option_context_free() is
494 * called, so you must not free the group yourself after adding it
500 g_option_context_add_group (GOptionContext *context,
505 g_return_if_fail (context != NULL);
506 g_return_if_fail (group != NULL);
507 g_return_if_fail (group->name != NULL);
508 g_return_if_fail (group->description != NULL);
509 g_return_if_fail (group->help_description != NULL);
511 for (list = context->groups; list; list = list->next)
513 GOptionGroup *g = (GOptionGroup *)list->data;
515 if ((group->name == NULL && g->name == NULL) ||
516 (group->name && g->name && strcmp (group->name, g->name) == 0))
517 g_warning ("A group named \"%s\" is already part of this GOptionContext",
521 context->groups = g_list_append (context->groups, group);
525 * g_option_context_set_main_group:
526 * @context: a #GOptionContext
527 * @group: the group to set as main group
529 * Sets a #GOptionGroup as main group of the @context.
530 * This has the same effect as calling g_option_context_add_group(),
531 * the only difference is that the options in the main group are
532 * treated differently when generating `--help` output.
537 g_option_context_set_main_group (GOptionContext *context,
540 g_return_if_fail (context != NULL);
541 g_return_if_fail (group != NULL);
543 if (context->main_group)
545 g_warning ("This GOptionContext already has a main group");
550 context->main_group = group;
554 * g_option_context_get_main_group:
555 * @context: a #GOptionContext
557 * Returns a pointer to the main group of @context.
559 * Returns: the main group of @context, or %NULL if @context doesn't
560 * have a main group. Note that group belongs to @context and should
561 * not be modified or freed.
566 g_option_context_get_main_group (GOptionContext *context)
568 g_return_val_if_fail (context != NULL, NULL);
570 return context->main_group;
574 * g_option_context_add_main_entries:
575 * @context: a #GOptionContext
576 * @entries: a %NULL-terminated array of #GOptionEntrys
577 * @translation_domain: (allow-none): a translation domain to use for translating
578 * the `--help` output for the options in @entries
579 * with gettext(), or %NULL
581 * A convenience function which creates a main group if it doesn't
582 * exist, adds the @entries to it and sets the translation domain.
587 g_option_context_add_main_entries (GOptionContext *context,
588 const GOptionEntry *entries,
589 const gchar *translation_domain)
591 g_return_if_fail (entries != NULL);
593 if (!context->main_group)
594 context->main_group = g_option_group_new (NULL, NULL, NULL, NULL, NULL);
596 g_option_group_add_entries (context->main_group, entries);
597 g_option_group_set_translation_domain (context->main_group, translation_domain);
601 calculate_max_length (GOptionGroup *group,
605 gint i, len, max_length;
606 const gchar *long_name;
610 for (i = 0; i < group->n_entries; i++)
612 entry = &group->entries[i];
614 if (entry->flags & G_OPTION_FLAG_HIDDEN)
617 long_name = g_hash_table_lookup (aliases, &entry->long_name);
619 long_name = entry->long_name;
620 len = _g_utf8_strwidth (long_name);
622 if (entry->short_name)
625 if (!NO_ARG (entry) && entry->arg_description)
626 len += 1 + _g_utf8_strwidth (TRANSLATE (group, entry->arg_description));
628 max_length = MAX (max_length, len);
635 print_entry (GOptionGroup *group,
637 const GOptionEntry *entry,
642 const gchar *long_name;
644 if (entry->flags & G_OPTION_FLAG_HIDDEN)
647 if (entry->long_name[0] == 0)
650 long_name = g_hash_table_lookup (aliases, &entry->long_name);
652 long_name = entry->long_name;
654 str = g_string_new (NULL);
656 if (entry->short_name)
657 g_string_append_printf (str, " -%c, --%s", entry->short_name, long_name);
659 g_string_append_printf (str, " --%s", long_name);
661 if (entry->arg_description)
662 g_string_append_printf (str, "=%s", TRANSLATE (group, entry->arg_description));
664 g_string_append_printf (string, "%s%*s %s\n", str->str,
665 (int) (max_length + 4 - _g_utf8_strwidth (str->str)), "",
666 entry->description ? TRANSLATE (group, entry->description) : "");
667 g_string_free (str, TRUE);
671 group_has_visible_entries (GOptionContext *context,
673 gboolean main_entries)
675 GOptionFlags reject_filter = G_OPTION_FLAG_HIDDEN;
678 gboolean main_group = group == context->main_group;
681 reject_filter |= G_OPTION_FLAG_IN_MAIN;
683 for (i = 0, l = (group ? group->n_entries : 0); i < l; i++)
685 entry = &group->entries[i];
687 if (main_entries && !main_group && !(entry->flags & G_OPTION_FLAG_IN_MAIN))
689 if (entry->long_name[0] == 0) /* ignore rest entry */
691 if (!(entry->flags & reject_filter))
699 group_list_has_visible_entries (GOptionContext *context,
701 gboolean main_entries)
705 if (group_has_visible_entries (context, group_list->data, main_entries))
708 group_list = group_list->next;
715 context_has_h_entry (GOptionContext *context)
720 if (context->main_group)
722 for (i = 0; i < context->main_group->n_entries; i++)
724 if (context->main_group->entries[i].short_name == 'h')
729 for (list = context->groups; list != NULL; list = g_list_next (list))
733 group = (GOptionGroup*)list->data;
734 for (i = 0; i < group->n_entries; i++)
736 if (group->entries[i].short_name == 'h')
744 * g_option_context_get_help:
745 * @context: a #GOptionContext
746 * @main_help: if %TRUE, only include the main group
747 * @group: (allow-none): the #GOptionGroup to create help for, or %NULL
749 * Returns a formatted, translated help text for the given context.
750 * To obtain the text produced by `--help`, call
751 * `g_option_context_get_help (context, TRUE, NULL)`.
752 * To obtain the text produced by `--help-all`, call
753 * `g_option_context_get_help (context, FALSE, NULL)`.
754 * To obtain the help text for an option group, call
755 * `g_option_context_get_help (context, FALSE, group)`.
757 * Returns: A newly allocated string containing the help text
762 g_option_context_get_help (GOptionContext *context,
767 gint max_length = 0, len;
770 GHashTable *shadow_map;
773 const gchar *rest_description;
777 string = g_string_sized_new (1024);
779 rest_description = NULL;
780 if (context->main_group)
783 for (i = 0; i < context->main_group->n_entries; i++)
785 entry = &context->main_group->entries[i];
786 if (entry->long_name[0] == 0)
788 rest_description = TRANSLATE (context->main_group, entry->arg_description);
794 g_string_append_printf (string, "%s\n %s %s",
795 _("Usage:"), g_get_prgname(), _("[OPTION...]"));
797 if (rest_description)
799 g_string_append (string, " ");
800 g_string_append (string, rest_description);
803 if (context->parameter_string)
805 g_string_append (string, " ");
806 g_string_append (string, TRANSLATE (context, context->parameter_string));
809 g_string_append (string, "\n\n");
811 if (context->summary)
813 g_string_append (string, TRANSLATE (context, context->summary));
814 g_string_append (string, "\n\n");
817 memset (seen, 0, sizeof (gboolean) * 256);
818 shadow_map = g_hash_table_new (g_str_hash, g_str_equal);
819 aliases = g_hash_table_new_full (NULL, NULL, NULL, g_free);
821 if (context->main_group)
823 for (i = 0; i < context->main_group->n_entries; i++)
825 entry = &context->main_group->entries[i];
826 g_hash_table_insert (shadow_map,
827 (gpointer)entry->long_name,
830 if (seen[(guchar)entry->short_name])
831 entry->short_name = 0;
833 seen[(guchar)entry->short_name] = TRUE;
837 list = context->groups;
840 GOptionGroup *g = list->data;
841 for (i = 0; i < g->n_entries; i++)
843 entry = &g->entries[i];
844 if (g_hash_table_lookup (shadow_map, entry->long_name) &&
845 !(entry->flags & G_OPTION_FLAG_NOALIAS))
847 g_hash_table_insert (aliases, &entry->long_name,
848 g_strdup_printf ("%s-%s", g->name, entry->long_name));
851 g_hash_table_insert (shadow_map, (gpointer)entry->long_name, entry);
853 if (seen[(guchar)entry->short_name] &&
854 !(entry->flags & G_OPTION_FLAG_NOALIAS))
855 entry->short_name = 0;
857 seen[(guchar)entry->short_name] = TRUE;
862 g_hash_table_destroy (shadow_map);
864 list = context->groups;
866 if (context->help_enabled)
868 max_length = _g_utf8_strwidth ("-?, --help");
872 len = _g_utf8_strwidth ("--help-all");
873 max_length = MAX (max_length, len);
877 if (context->main_group)
879 len = calculate_max_length (context->main_group, aliases);
880 max_length = MAX (max_length, len);
885 GOptionGroup *g = list->data;
887 if (context->help_enabled)
889 /* First, we check the --help-<groupname> options */
890 len = _g_utf8_strwidth ("--help-") + _g_utf8_strwidth (g->name);
891 max_length = MAX (max_length, len);
894 /* Then we go through the entries */
895 len = calculate_max_length (g, aliases);
896 max_length = MAX (max_length, len);
901 /* Add a bit of padding */
904 if (!group && context->help_enabled)
906 list = context->groups;
908 token = context_has_h_entry (context) ? '?' : 'h';
910 g_string_append_printf (string, "%s\n -%c, --%-*s %s\n",
911 _("Help Options:"), token, max_length - 4, "help",
912 _("Show help options"));
914 /* We only want --help-all when there are groups */
916 g_string_append_printf (string, " --%-*s %s\n",
917 max_length, "help-all",
918 _("Show all help options"));
922 GOptionGroup *g = list->data;
924 if (group_has_visible_entries (context, g, FALSE))
925 g_string_append_printf (string, " --help-%-*s %s\n",
926 max_length - 5, g->name,
927 TRANSLATE (g, g->help_description));
932 g_string_append (string, "\n");
937 /* Print a certain group */
939 if (group_has_visible_entries (context, group, FALSE))
941 g_string_append (string, TRANSLATE (group, group->description));
942 g_string_append (string, "\n");
943 for (i = 0; i < group->n_entries; i++)
944 print_entry (group, max_length, &group->entries[i], string, aliases);
945 g_string_append (string, "\n");
950 /* Print all groups */
952 list = context->groups;
956 GOptionGroup *g = list->data;
958 if (group_has_visible_entries (context, g, FALSE))
960 g_string_append (string, g->description);
961 g_string_append (string, "\n");
962 for (i = 0; i < g->n_entries; i++)
963 if (!(g->entries[i].flags & G_OPTION_FLAG_IN_MAIN))
964 print_entry (g, max_length, &g->entries[i], string, aliases);
966 g_string_append (string, "\n");
973 /* Print application options if --help or --help-all has been specified */
974 if ((main_help || !group) &&
975 (group_has_visible_entries (context, context->main_group, TRUE) ||
976 group_list_has_visible_entries (context, context->groups, TRUE)))
978 list = context->groups;
980 g_string_append (string, _("Application Options:"));
981 g_string_append (string, "\n");
982 if (context->main_group)
983 for (i = 0; i < context->main_group->n_entries; i++)
984 print_entry (context->main_group, max_length,
985 &context->main_group->entries[i], string, aliases);
989 GOptionGroup *g = list->data;
991 /* Print main entries from other groups */
992 for (i = 0; i < g->n_entries; i++)
993 if (g->entries[i].flags & G_OPTION_FLAG_IN_MAIN)
994 print_entry (g, max_length, &g->entries[i], string, aliases);
999 g_string_append (string, "\n");
1002 if (context->description)
1004 g_string_append (string, TRANSLATE (context, context->description));
1005 g_string_append (string, "\n");
1008 g_hash_table_destroy (aliases);
1010 return g_string_free (string, FALSE);
1015 print_help (GOptionContext *context,
1017 GOptionGroup *group)
1021 help = g_option_context_get_help (context, main_help, group);
1022 g_print ("%s", help);
1029 parse_int (const gchar *arg_name,
1038 tmp = strtol (arg, &end, 0);
1040 if (*arg == '\0' || *end != '\0')
1043 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1044 _("Cannot parse integer value '%s' for %s"),
1050 if (*result != tmp || errno == ERANGE)
1053 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1054 _("Integer value '%s' for %s out of range"),
1064 parse_double (const gchar *arg_name,
1073 tmp = g_strtod (arg, &end);
1075 if (*arg == '\0' || *end != '\0')
1078 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1079 _("Cannot parse double value '%s' for %s"),
1083 if (errno == ERANGE)
1086 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1087 _("Double value '%s' for %s out of range"),
1099 parse_int64 (const gchar *arg_name,
1108 tmp = g_ascii_strtoll (arg, &end, 0);
1110 if (*arg == '\0' || *end != '\0')
1113 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1114 _("Cannot parse integer value '%s' for %s"),
1118 if (errno == ERANGE)
1121 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1122 _("Integer value '%s' for %s out of range"),
1134 get_change (GOptionContext *context,
1135 GOptionArg arg_type,
1139 Change *change = NULL;
1141 for (list = context->changes; list != NULL; list = list->next)
1143 change = list->data;
1145 if (change->arg_data == arg_data)
1149 change = g_new0 (Change, 1);
1150 change->arg_type = arg_type;
1151 change->arg_data = arg_data;
1153 context->changes = g_list_prepend (context->changes, change);
1161 add_pending_null (GOptionContext *context,
1167 n = g_new0 (PendingNull, 1);
1171 context->pending_nulls = g_list_prepend (context->pending_nulls, n);
1175 parse_arg (GOptionContext *context,
1176 GOptionGroup *group,
1177 GOptionEntry *entry,
1179 const gchar *option_name,
1185 g_assert (value || OPTIONAL_ARG (entry) || NO_ARG (entry));
1189 case G_OPTION_ARG_NONE:
1191 (void) get_change (context, G_OPTION_ARG_NONE,
1194 *(gboolean *)entry->arg_data = !(entry->flags & G_OPTION_FLAG_REVERSE);
1197 case G_OPTION_ARG_STRING:
1202 if (!context->strv_mode)
1203 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1205 data = g_strdup (value);
1207 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1213 change = get_change (context, G_OPTION_ARG_STRING,
1215 g_free (change->allocated.str);
1217 change->prev.str = *(gchar **)entry->arg_data;
1218 change->allocated.str = data;
1220 *(gchar **)entry->arg_data = data;
1223 case G_OPTION_ARG_STRING_ARRAY:
1228 if (!context->strv_mode)
1229 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1231 data = g_strdup (value);
1233 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1239 change = get_change (context, G_OPTION_ARG_STRING_ARRAY,
1242 if (change->allocated.array.len == 0)
1244 change->prev.array = *(gchar ***)entry->arg_data;
1245 change->allocated.array.data = g_new (gchar *, 2);
1248 change->allocated.array.data =
1249 g_renew (gchar *, change->allocated.array.data,
1250 change->allocated.array.len + 2);
1252 change->allocated.array.data[change->allocated.array.len] = data;
1253 change->allocated.array.data[change->allocated.array.len + 1] = NULL;
1255 change->allocated.array.len ++;
1257 *(gchar ***)entry->arg_data = change->allocated.array.data;
1262 case G_OPTION_ARG_FILENAME:
1267 if (!context->strv_mode)
1268 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1270 data = g_strdup (value);
1275 data = g_strdup (value);
1277 change = get_change (context, G_OPTION_ARG_FILENAME,
1279 g_free (change->allocated.str);
1281 change->prev.str = *(gchar **)entry->arg_data;
1282 change->allocated.str = data;
1284 *(gchar **)entry->arg_data = data;
1288 case G_OPTION_ARG_FILENAME_ARRAY:
1293 if (!context->strv_mode)
1294 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1296 data = g_strdup (value);
1301 data = g_strdup (value);
1303 change = get_change (context, G_OPTION_ARG_STRING_ARRAY,
1306 if (change->allocated.array.len == 0)
1308 change->prev.array = *(gchar ***)entry->arg_data;
1309 change->allocated.array.data = g_new (gchar *, 2);
1312 change->allocated.array.data =
1313 g_renew (gchar *, change->allocated.array.data,
1314 change->allocated.array.len + 2);
1316 change->allocated.array.data[change->allocated.array.len] = data;
1317 change->allocated.array.data[change->allocated.array.len + 1] = NULL;
1319 change->allocated.array.len ++;
1321 *(gchar ***)entry->arg_data = change->allocated.array.data;
1326 case G_OPTION_ARG_INT:
1330 if (!parse_int (option_name, value,
1335 change = get_change (context, G_OPTION_ARG_INT,
1337 change->prev.integer = *(gint *)entry->arg_data;
1338 *(gint *)entry->arg_data = data;
1341 case G_OPTION_ARG_CALLBACK:
1346 if (!value && entry->flags & G_OPTION_FLAG_OPTIONAL_ARG)
1348 else if (entry->flags & G_OPTION_FLAG_NO_ARG)
1350 else if (entry->flags & G_OPTION_FLAG_FILENAME)
1353 if (!context->strv_mode)
1354 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1356 data = g_strdup (value);
1358 data = g_strdup (value);
1362 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1364 if (!(entry->flags & (G_OPTION_FLAG_NO_ARG|G_OPTION_FLAG_OPTIONAL_ARG)) &&
1368 retval = (* (GOptionArgFunc) entry->arg_data) (option_name, data, group->user_data, error);
1370 if (!retval && error != NULL && *error == NULL)
1372 G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
1373 _("Error parsing option %s"), option_name);
1381 case G_OPTION_ARG_DOUBLE:
1385 if (!parse_double (option_name, value,
1392 change = get_change (context, G_OPTION_ARG_DOUBLE,
1394 change->prev.dbl = *(gdouble *)entry->arg_data;
1395 *(gdouble *)entry->arg_data = data;
1398 case G_OPTION_ARG_INT64:
1402 if (!parse_int64 (option_name, value,
1409 change = get_change (context, G_OPTION_ARG_INT64,
1411 change->prev.int64 = *(gint64 *)entry->arg_data;
1412 *(gint64 *)entry->arg_data = data;
1416 g_assert_not_reached ();
1423 parse_short_option (GOptionContext *context,
1424 GOptionGroup *group,
1435 for (j = 0; j < group->n_entries; j++)
1437 if (arg == group->entries[j].short_name)
1440 gchar *value = NULL;
1442 option_name = g_strdup_printf ("-%c", group->entries[j].short_name);
1444 if (NO_ARG (&group->entries[j]))
1451 G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
1452 _("Error parsing option %s"), option_name);
1453 g_free (option_name);
1457 if (idx < *argc - 1)
1459 if (!OPTIONAL_ARG (&group->entries[j]))
1461 value = (*argv)[idx + 1];
1462 add_pending_null (context, &((*argv)[idx + 1]), NULL);
1467 if ((*argv)[idx + 1][0] == '-')
1471 value = (*argv)[idx + 1];
1472 add_pending_null (context, &((*argv)[idx + 1]), NULL);
1477 else if (idx >= *argc - 1 && OPTIONAL_ARG (&group->entries[j]))
1482 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1483 _("Missing argument for %s"), option_name);
1484 g_free (option_name);
1489 if (!parse_arg (context, group, &group->entries[j],
1490 value, option_name, error))
1492 g_free (option_name);
1496 g_free (option_name);
1505 parse_long_option (GOptionContext *context,
1506 GOptionGroup *group,
1517 for (j = 0; j < group->n_entries; j++)
1522 if (aliased && (group->entries[j].flags & G_OPTION_FLAG_NOALIAS))
1525 if (NO_ARG (&group->entries[j]) &&
1526 strcmp (arg, group->entries[j].long_name) == 0)
1531 option_name = g_strconcat ("--", group->entries[j].long_name, NULL);
1532 retval = parse_arg (context, group, &group->entries[j],
1533 NULL, option_name, error);
1534 g_free (option_name);
1536 add_pending_null (context, &((*argv)[*idx]), NULL);
1543 gint len = strlen (group->entries[j].long_name);
1545 if (strncmp (arg, group->entries[j].long_name, len) == 0 &&
1546 (arg[len] == '=' || arg[len] == 0))
1548 gchar *value = NULL;
1551 add_pending_null (context, &((*argv)[*idx]), NULL);
1552 option_name = g_strconcat ("--", group->entries[j].long_name, NULL);
1554 if (arg[len] == '=')
1555 value = arg + len + 1;
1556 else if (*idx < *argc - 1)
1558 if (!OPTIONAL_ARG (&group->entries[j]))
1560 value = (*argv)[*idx + 1];
1561 add_pending_null (context, &((*argv)[*idx + 1]), NULL);
1566 if ((*argv)[*idx + 1][0] == '-')
1569 retval = parse_arg (context, group, &group->entries[j],
1570 NULL, option_name, error);
1572 g_free (option_name);
1577 value = (*argv)[*idx + 1];
1578 add_pending_null (context, &((*argv)[*idx + 1]), NULL);
1583 else if (*idx >= *argc - 1 && OPTIONAL_ARG (&group->entries[j]))
1586 retval = parse_arg (context, group, &group->entries[j],
1587 NULL, option_name, error);
1589 g_free (option_name);
1595 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1596 _("Missing argument for %s"), option_name);
1597 g_free (option_name);
1601 if (!parse_arg (context, group, &group->entries[j],
1602 value, option_name, error))
1604 g_free (option_name);
1608 g_free (option_name);
1618 parse_remaining_arg (GOptionContext *context,
1619 GOptionGroup *group,
1628 for (j = 0; j < group->n_entries; j++)
1633 if (group->entries[j].long_name[0])
1636 g_return_val_if_fail (group->entries[j].arg == G_OPTION_ARG_CALLBACK ||
1637 group->entries[j].arg == G_OPTION_ARG_STRING_ARRAY ||
1638 group->entries[j].arg == G_OPTION_ARG_FILENAME_ARRAY, FALSE);
1640 add_pending_null (context, &((*argv)[*idx]), NULL);
1642 if (!parse_arg (context, group, &group->entries[j], (*argv)[*idx], "", error))
1653 free_changes_list (GOptionContext *context,
1658 for (list = context->changes; list != NULL; list = list->next)
1660 Change *change = list->data;
1664 switch (change->arg_type)
1666 case G_OPTION_ARG_NONE:
1667 *(gboolean *)change->arg_data = change->prev.bool;
1669 case G_OPTION_ARG_INT:
1670 *(gint *)change->arg_data = change->prev.integer;
1672 case G_OPTION_ARG_STRING:
1673 case G_OPTION_ARG_FILENAME:
1674 g_free (change->allocated.str);
1675 *(gchar **)change->arg_data = change->prev.str;
1677 case G_OPTION_ARG_STRING_ARRAY:
1678 case G_OPTION_ARG_FILENAME_ARRAY:
1679 g_strfreev (change->allocated.array.data);
1680 *(gchar ***)change->arg_data = change->prev.array;
1682 case G_OPTION_ARG_DOUBLE:
1683 *(gdouble *)change->arg_data = change->prev.dbl;
1685 case G_OPTION_ARG_INT64:
1686 *(gint64 *)change->arg_data = change->prev.int64;
1689 g_assert_not_reached ();
1696 g_list_free (context->changes);
1697 context->changes = NULL;
1701 free_pending_nulls (GOptionContext *context,
1702 gboolean perform_nulls)
1706 for (list = context->pending_nulls; list != NULL; list = list->next)
1708 PendingNull *n = list->data;
1714 /* Copy back the short options */
1716 strcpy (*n->ptr + 1, n->value);
1720 if (context->strv_mode)
1731 g_list_free (context->pending_nulls);
1732 context->pending_nulls = NULL;
1735 /* Use a platform-specific mechanism to look up the first argument to
1736 * the current process.
1737 * Note if you implement this for other platforms, also add it to
1738 * tests/option-argv0.c
1741 platform_get_argv0 (void)
1748 if (!g_file_get_contents ("/proc/self/cmdline",
1753 /* Sanity check for a NUL terminator. */
1754 if (!memchr (cmdline, 0, len))
1756 /* We could just return cmdline, but I think it's better
1757 * to hold on to a smaller malloc block; the arguments
1760 base_arg0 = g_path_get_basename (cmdline);
1763 #elif defined __OpenBSD__
1768 int mib[] = { CTL_KERN, KERN_PROC_ARGS, getpid(), KERN_PROC_ARGV };
1770 if (sysctl (mib, G_N_ELEMENTS (mib), NULL, &len, NULL, 0) == -1)
1773 cmdline = g_malloc0 (len);
1775 if (sysctl (mib, G_N_ELEMENTS (mib), cmdline, &len, NULL, 0) == -1)
1781 /* We could just return cmdline, but I think it's better
1782 * to hold on to a smaller malloc block; the arguments
1785 base_arg0 = g_path_get_basename (*cmdline);
1794 * g_option_context_parse:
1795 * @context: a #GOptionContext
1796 * @argc: (inout) (allow-none): a pointer to the number of command line arguments
1797 * @argv: (inout) (array length=argc) (allow-none): a pointer to the array of command line arguments
1798 * @error: a return location for errors
1800 * Parses the command line arguments, recognizing options
1801 * which have been added to @context. A side-effect of
1802 * calling this function is that g_set_prgname() will be
1805 * If the parsing is successful, any parsed arguments are
1806 * removed from the array and @argc and @argv are updated
1807 * accordingly. A '--' option is stripped from @argv
1808 * unless there are unparsed options before and after it,
1809 * or some of the options after it start with '-'. In case
1810 * of an error, @argc and @argv are left unmodified.
1812 * If automatic `--help` support is enabled
1813 * (see g_option_context_set_help_enabled()), and the
1814 * @argv array contains one of the recognized help options,
1815 * this function will produce help output to stdout and
1818 * Note that function depends on the [current locale][setlocale] for
1819 * automatic character set conversion of string and filename
1822 * Returns: %TRUE if the parsing was successful,
1823 * %FALSE if an error occurred
1828 g_option_context_parse (GOptionContext *context,
1836 /* Set program name */
1837 if (!g_get_prgname())
1841 if (argc && argv && *argc)
1842 prgname = g_path_get_basename ((*argv)[0]);
1844 prgname = platform_get_argv0 ();
1847 g_set_prgname (prgname);
1849 g_set_prgname ("<unknown>");
1854 /* Call pre-parse hooks */
1855 list = context->groups;
1858 GOptionGroup *group = list->data;
1860 if (group->pre_parse_func)
1862 if (!(* group->pre_parse_func) (context, group,
1863 group->user_data, error))
1870 if (context->main_group && context->main_group->pre_parse_func)
1872 if (!(* context->main_group->pre_parse_func) (context, context->main_group,
1873 context->main_group->user_data, error))
1879 gboolean stop_parsing = FALSE;
1880 gboolean has_unknown = FALSE;
1881 gint separator_pos = 0;
1883 for (i = 1; i < *argc; i++)
1886 gboolean parsed = FALSE;
1888 if ((*argv)[i][0] == '-' && (*argv)[i][1] != '\0' && !stop_parsing)
1890 if ((*argv)[i][1] == '-')
1894 arg = (*argv)[i] + 2;
1896 /* '--' terminates list of arguments */
1900 stop_parsing = TRUE;
1904 /* Handle help options */
1905 if (context->help_enabled)
1907 if (strcmp (arg, "help") == 0)
1908 print_help (context, TRUE, NULL);
1909 else if (strcmp (arg, "help-all") == 0)
1910 print_help (context, FALSE, NULL);
1911 else if (strncmp (arg, "help-", 5) == 0)
1913 list = context->groups;
1917 GOptionGroup *group = list->data;
1919 if (strcmp (arg + 5, group->name) == 0)
1920 print_help (context, FALSE, group);
1927 if (context->main_group &&
1928 !parse_long_option (context, context->main_group, &i, arg,
1929 FALSE, argc, argv, error, &parsed))
1935 /* Try the groups */
1936 list = context->groups;
1939 GOptionGroup *group = list->data;
1941 if (!parse_long_option (context, group, &i, arg,
1942 FALSE, argc, argv, error, &parsed))
1954 /* Now look for --<group>-<option> */
1955 dash = strchr (arg, '-');
1958 /* Try the groups */
1959 list = context->groups;
1962 GOptionGroup *group = list->data;
1964 if (strncmp (group->name, arg, dash - arg) == 0)
1966 if (!parse_long_option (context, group, &i, dash + 1,
1967 TRUE, argc, argv, error, &parsed))
1978 if (context->ignore_unknown)
1982 { /* short option */
1983 gint new_i = i, arg_length;
1984 gboolean *nulled_out = NULL;
1985 gboolean has_h_entry = context_has_h_entry (context);
1986 arg = (*argv)[i] + 1;
1987 arg_length = strlen (arg);
1988 nulled_out = g_newa (gboolean, arg_length);
1989 memset (nulled_out, 0, arg_length * sizeof (gboolean));
1990 for (j = 0; j < arg_length; j++)
1992 if (context->help_enabled && (arg[j] == '?' ||
1993 (arg[j] == 'h' && !has_h_entry)))
1994 print_help (context, TRUE, NULL);
1996 if (context->main_group &&
1997 !parse_short_option (context, context->main_group,
1999 argc, argv, error, &parsed))
2003 /* Try the groups */
2004 list = context->groups;
2007 GOptionGroup *group = list->data;
2008 if (!parse_short_option (context, group, i, &new_i, arg[j],
2009 argc, argv, error, &parsed))
2017 if (context->ignore_unknown && parsed)
2018 nulled_out[j] = TRUE;
2019 else if (context->ignore_unknown)
2023 /* !context->ignore_unknown && parsed */
2025 if (context->ignore_unknown)
2027 gchar *new_arg = NULL;
2029 for (j = 0; j < arg_length; j++)
2034 new_arg = g_malloc (arg_length + 1);
2035 new_arg[arg_index++] = arg[j];
2039 new_arg[arg_index] = '\0';
2040 add_pending_null (context, &((*argv)[i]), new_arg);
2045 add_pending_null (context, &((*argv)[i]), NULL);
2053 if (!parsed && !context->ignore_unknown)
2056 G_OPTION_ERROR, G_OPTION_ERROR_UNKNOWN_OPTION,
2057 _("Unknown option %s"), (*argv)[i]);
2063 /* Collect remaining args */
2064 if (context->main_group &&
2065 !parse_remaining_arg (context, context->main_group, &i,
2066 argc, argv, error, &parsed))
2069 if (!parsed && (has_unknown || (*argv)[i][0] == '-'))
2074 if (separator_pos > 0)
2075 add_pending_null (context, &((*argv)[separator_pos]), NULL);
2079 /* Call post-parse hooks */
2080 list = context->groups;
2083 GOptionGroup *group = list->data;
2085 if (group->post_parse_func)
2087 if (!(* group->post_parse_func) (context, group,
2088 group->user_data, error))
2095 if (context->main_group && context->main_group->post_parse_func)
2097 if (!(* context->main_group->post_parse_func) (context, context->main_group,
2098 context->main_group->user_data, error))
2104 free_pending_nulls (context, TRUE);
2106 for (i = 1; i < *argc; i++)
2108 for (k = i; k < *argc; k++)
2109 if ((*argv)[k] != NULL)
2115 for (j = i + k; j < *argc; j++)
2117 (*argv)[j-k] = (*argv)[j];
2129 /* Call error hooks */
2130 list = context->groups;
2133 GOptionGroup *group = list->data;
2135 if (group->error_func)
2136 (* group->error_func) (context, group,
2137 group->user_data, error);
2142 if (context->main_group && context->main_group->error_func)
2143 (* context->main_group->error_func) (context, context->main_group,
2144 context->main_group->user_data, error);
2146 free_changes_list (context, TRUE);
2147 free_pending_nulls (context, FALSE);
2153 * g_option_group_new:
2154 * @name: the name for the option group, this is used to provide
2155 * help for the options in this group with `--help-`@name
2156 * @description: a description for this group to be shown in
2157 * `--help`. This string is translated using the translation
2158 * domain or translation function of the group
2159 * @help_description: a description for the `--help-`@name option.
2160 * This string is translated using the translation domain or translation function
2162 * @user_data: (allow-none): user data that will be passed to the pre- and post-parse hooks,
2163 * the error hook and to callbacks of %G_OPTION_ARG_CALLBACK options, or %NULL
2164 * @destroy: (allow-none): a function that will be called to free @user_data, or %NULL
2166 * Creates a new #GOptionGroup.
2168 * Returns: a newly created option group. It should be added
2169 * to a #GOptionContext or freed with g_option_group_free().
2174 g_option_group_new (const gchar *name,
2175 const gchar *description,
2176 const gchar *help_description,
2178 GDestroyNotify destroy)
2181 GOptionGroup *group;
2183 group = g_new0 (GOptionGroup, 1);
2184 group->name = g_strdup (name);
2185 group->description = g_strdup (description);
2186 group->help_description = g_strdup (help_description);
2187 group->user_data = user_data;
2188 group->destroy_notify = destroy;
2195 * g_option_group_free:
2196 * @group: a #GOptionGroup
2198 * Frees a #GOptionGroup. Note that you must not free groups
2199 * which have been added to a #GOptionContext.
2204 g_option_group_free (GOptionGroup *group)
2206 g_return_if_fail (group != NULL);
2208 g_free (group->name);
2209 g_free (group->description);
2210 g_free (group->help_description);
2212 g_free (group->entries);
2214 if (group->destroy_notify)
2215 (* group->destroy_notify) (group->user_data);
2217 if (group->translate_notify)
2218 (* group->translate_notify) (group->translate_data);
2225 * g_option_group_add_entries:
2226 * @group: a #GOptionGroup
2227 * @entries: a %NULL-terminated array of #GOptionEntrys
2229 * Adds the options specified in @entries to @group.
2234 g_option_group_add_entries (GOptionGroup *group,
2235 const GOptionEntry *entries)
2239 g_return_if_fail (entries != NULL);
2241 for (n_entries = 0; entries[n_entries].long_name != NULL; n_entries++) ;
2243 group->entries = g_renew (GOptionEntry, group->entries, group->n_entries + n_entries);
2245 memcpy (group->entries + group->n_entries, entries, sizeof (GOptionEntry) * n_entries);
2247 for (i = group->n_entries; i < group->n_entries + n_entries; i++)
2249 gchar c = group->entries[i].short_name;
2251 if (c == '-' || (c != 0 && !g_ascii_isprint (c)))
2253 g_warning (G_STRLOC ": ignoring invalid short option '%c' (%d) in entry %s:%s",
2254 c, c, group->name, group->entries[i].long_name);
2255 group->entries[i].short_name = '\0';
2258 if (group->entries[i].arg != G_OPTION_ARG_NONE &&
2259 (group->entries[i].flags & G_OPTION_FLAG_REVERSE) != 0)
2261 g_warning (G_STRLOC ": ignoring reverse flag on option of arg-type %d in entry %s:%s",
2262 group->entries[i].arg, group->name, group->entries[i].long_name);
2264 group->entries[i].flags &= ~G_OPTION_FLAG_REVERSE;
2267 if (group->entries[i].arg != G_OPTION_ARG_CALLBACK &&
2268 (group->entries[i].flags & (G_OPTION_FLAG_NO_ARG|G_OPTION_FLAG_OPTIONAL_ARG|G_OPTION_FLAG_FILENAME)) != 0)
2270 g_warning (G_STRLOC ": ignoring no-arg, optional-arg or filename flags (%d) on option of arg-type %d in entry %s:%s",
2271 group->entries[i].flags, group->entries[i].arg, group->name, group->entries[i].long_name);
2273 group->entries[i].flags &= ~(G_OPTION_FLAG_NO_ARG|G_OPTION_FLAG_OPTIONAL_ARG|G_OPTION_FLAG_FILENAME);
2277 group->n_entries += n_entries;
2281 * g_option_group_set_parse_hooks:
2282 * @group: a #GOptionGroup
2283 * @pre_parse_func: (allow-none): a function to call before parsing, or %NULL
2284 * @post_parse_func: (allow-none): a function to call after parsing, or %NULL
2286 * Associates two functions with @group which will be called
2287 * from g_option_context_parse() before the first option is parsed
2288 * and after the last option has been parsed, respectively.
2290 * Note that the user data to be passed to @pre_parse_func and
2291 * @post_parse_func can be specified when constructing the group
2292 * with g_option_group_new().
2297 g_option_group_set_parse_hooks (GOptionGroup *group,
2298 GOptionParseFunc pre_parse_func,
2299 GOptionParseFunc post_parse_func)
2301 g_return_if_fail (group != NULL);
2303 group->pre_parse_func = pre_parse_func;
2304 group->post_parse_func = post_parse_func;
2308 * g_option_group_set_error_hook:
2309 * @group: a #GOptionGroup
2310 * @error_func: a function to call when an error occurs
2312 * Associates a function with @group which will be called
2313 * from g_option_context_parse() when an error occurs.
2315 * Note that the user data to be passed to @error_func can be
2316 * specified when constructing the group with g_option_group_new().
2321 g_option_group_set_error_hook (GOptionGroup *group,
2322 GOptionErrorFunc error_func)
2324 g_return_if_fail (group != NULL);
2326 group->error_func = error_func;
2331 * g_option_group_set_translate_func:
2332 * @group: a #GOptionGroup
2333 * @func: (allow-none): the #GTranslateFunc, or %NULL
2334 * @data: (allow-none): user data to pass to @func, or %NULL
2335 * @destroy_notify: (allow-none): a function which gets called to free @data, or %NULL
2337 * Sets the function which is used to translate user-visible strings,
2338 * for `--help` output. Different groups can use different
2339 * #GTranslateFuncs. If @func is %NULL, strings are not translated.
2341 * If you are using gettext(), you only need to set the translation
2342 * domain, see g_option_group_set_translation_domain().
2347 g_option_group_set_translate_func (GOptionGroup *group,
2348 GTranslateFunc func,
2350 GDestroyNotify destroy_notify)
2352 g_return_if_fail (group != NULL);
2354 if (group->translate_notify)
2355 group->translate_notify (group->translate_data);
2357 group->translate_func = func;
2358 group->translate_data = data;
2359 group->translate_notify = destroy_notify;
2362 static const gchar *
2363 dgettext_swapped (const gchar *msgid,
2364 const gchar *domainname)
2366 return g_dgettext (domainname, msgid);
2370 * g_option_group_set_translation_domain:
2371 * @group: a #GOptionGroup
2372 * @domain: the domain to use
2374 * A convenience function to use gettext() for translating
2375 * user-visible strings.
2380 g_option_group_set_translation_domain (GOptionGroup *group,
2381 const gchar *domain)
2383 g_return_if_fail (group != NULL);
2385 g_option_group_set_translate_func (group,
2386 (GTranslateFunc)dgettext_swapped,
2392 * g_option_context_set_translate_func:
2393 * @context: a #GOptionContext
2394 * @func: (allow-none): the #GTranslateFunc, or %NULL
2395 * @data: (allow-none): user data to pass to @func, or %NULL
2396 * @destroy_notify: (allow-none): a function which gets called to free @data, or %NULL
2398 * Sets the function which is used to translate the contexts
2399 * user-visible strings, for `--help` output. If @func is %NULL,
2400 * strings are not translated.
2402 * Note that option groups have their own translation functions,
2403 * this function only affects the @parameter_string (see g_option_context_new()),
2404 * the summary (see g_option_context_set_summary()) and the description
2405 * (see g_option_context_set_description()).
2407 * If you are using gettext(), you only need to set the translation
2408 * domain, see g_option_context_set_translation_domain().
2413 g_option_context_set_translate_func (GOptionContext *context,
2414 GTranslateFunc func,
2416 GDestroyNotify destroy_notify)
2418 g_return_if_fail (context != NULL);
2420 if (context->translate_notify)
2421 context->translate_notify (context->translate_data);
2423 context->translate_func = func;
2424 context->translate_data = data;
2425 context->translate_notify = destroy_notify;
2429 * g_option_context_set_translation_domain:
2430 * @context: a #GOptionContext
2431 * @domain: the domain to use
2433 * A convenience function to use gettext() for translating
2434 * user-visible strings.
2439 g_option_context_set_translation_domain (GOptionContext *context,
2440 const gchar *domain)
2442 g_return_if_fail (context != NULL);
2444 g_option_context_set_translate_func (context,
2445 (GTranslateFunc)dgettext_swapped,
2451 * g_option_context_set_summary:
2452 * @context: a #GOptionContext
2453 * @summary: (allow-none): a string to be shown in `--help` output
2454 * before the list of options, or %NULL
2456 * Adds a string to be displayed in `--help` output before the list
2457 * of options. This is typically a summary of the program functionality.
2459 * Note that the summary is translated (see
2460 * g_option_context_set_translate_func() and
2461 * g_option_context_set_translation_domain()).
2466 g_option_context_set_summary (GOptionContext *context,
2467 const gchar *summary)
2469 g_return_if_fail (context != NULL);
2471 g_free (context->summary);
2472 context->summary = g_strdup (summary);
2477 * g_option_context_get_summary:
2478 * @context: a #GOptionContext
2480 * Returns the summary. See g_option_context_set_summary().
2482 * Returns: the summary
2487 g_option_context_get_summary (GOptionContext *context)
2489 g_return_val_if_fail (context != NULL, NULL);
2491 return context->summary;
2495 * g_option_context_set_description:
2496 * @context: a #GOptionContext
2497 * @description: (allow-none): a string to be shown in `--help` output
2498 * after the list of options, or %NULL
2500 * Adds a string to be displayed in `--help` output after the list
2501 * of options. This text often includes a bug reporting address.
2503 * Note that the summary is translated (see
2504 * g_option_context_set_translate_func()).
2509 g_option_context_set_description (GOptionContext *context,
2510 const gchar *description)
2512 g_return_if_fail (context != NULL);
2514 g_free (context->description);
2515 context->description = g_strdup (description);
2520 * g_option_context_get_description:
2521 * @context: a #GOptionContext
2523 * Returns the description. See g_option_context_set_description().
2525 * Returns: the description
2530 g_option_context_get_description (GOptionContext *context)
2532 g_return_val_if_fail (context != NULL, NULL);
2534 return context->description;
2538 * g_option_context_parse_strv:
2539 * @context: a #GOptionContext
2540 * @arguments: (inout) (array null-terminated=1): a pointer to the
2541 * command line arguments (which must be in UTF-8 on Windows)
2542 * @error: a return location for errors
2544 * Parses the command line arguments.
2546 * This function is similar to g_option_context_parse() except that it
2547 * respects the normal memory rules when dealing with a strv instead of
2548 * assuming that the passed-in array is the argv of the main function.
2550 * In particular, strings that are removed from the arguments list will
2551 * be freed using g_free().
2553 * On Windows, the strings are expected to be in UTF-8. This is in
2554 * contrast to g_option_context_parse() which expects them to be in the
2555 * system codepage, which is how they are passed as @argv to main().
2556 * See g_win32_get_command_line() for a solution.
2558 * This function is useful if you are trying to use #GOptionContext with
2561 * Returns: %TRUE if the parsing was successful,
2562 * %FALSE if an error occurred
2567 g_option_context_parse_strv (GOptionContext *context,
2574 context->strv_mode = TRUE;
2575 argc = g_strv_length (*arguments);
2576 success = g_option_context_parse (context, &argc, arguments, error);
2577 context->strv_mode = FALSE;