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
56 * `--help-`<replaceable>groupname</replaceable> options
57 * (where <replaceable>groupname</replaceable> is the name of a
58 * #GOptionGroup) and write a text similar to the one shown in the
59 * following example to stdout.
63 * testtreemodel [OPTION...] - test tree model performance
66 * -h, --help Show help options
67 * --help-all Show all help options
68 * --help-gtk Show GTK+ Options
70 * Application Options:
71 * -r, --repeats=N Average over N repetitions
72 * -m, --max-size=M Test up to 2^M items
73 * --display=DISPLAY X display to use
74 * -v, --verbose Be verbose
75 * -b, --beep Beep when done
76 * --rand Randomize the data
79 * GOption groups options in #GOptionGroups, which makes it easy to
80 * incorporate options from multiple sources. The intended use for this is
81 * to let applications collect option groups from the libraries it uses,
82 * add them to their #GOptionContext, and parse all options by a single call
83 * to g_option_context_parse(). See gtk_get_option_group() for an example.
85 * If an option is declared to be of type string or filename, GOption takes
86 * care of converting it to the right encoding; strings are returned in
87 * UTF-8, filenames are returned in the GLib filename encoding. Note that
88 * this only works if setlocale() has been called before
89 * g_option_context_parse().
91 * Here is a complete example of setting up GOption to parse the example
92 * commandline above and produce the example help output.
93 * |[<!-- language="C" -->
94 * static gint repeats = 2;
95 * static gint max_size = 8;
96 * static gboolean verbose = FALSE;
97 * static gboolean beep = FALSE;
98 * static gboolean randomize = FALSE;
100 * static GOptionEntry entries[] =
102 * { "repeats", 'r', 0, G_OPTION_ARG_INT, &repeats, "Average over N repetitions", "N" },
103 * { "max-size", 'm', 0, G_OPTION_ARG_INT, &max_size, "Test up to 2^M items", "M" },
104 * { "verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose, "Be verbose", NULL },
105 * { "beep", 'b', 0, G_OPTION_ARG_NONE, &beep, "Beep when done", NULL },
106 * { "rand", 0, 0, G_OPTION_ARG_NONE, &randomize, "Randomize the data", NULL },
111 * main (int argc, char *argv[])
113 * GError *error = NULL;
114 * GOptionContext *context;
116 * context = g_option_context_new ("- test tree model performance");
117 * g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
118 * g_option_context_add_group (context, gtk_get_option_group (TRUE));
119 * if (!g_option_context_parse (context, &argc, &argv, &error))
121 * g_print ("option parsing failed: %s\n", error->message);
130 * On UNIX systems, the argv that is passed to main() has no particular
131 * encoding, even to the extent that different parts of it may have
132 * different encodings. In general, normal arguments and flags will be
133 * in the current locale and filenames should be considered to be opaque
134 * byte strings. Proper use of %G_OPTION_ARG_FILENAME vs
135 * %G_OPTION_ARG_STRING is therefore important.
137 * Note that on Windows, filenames do have an encoding, but using
138 * #GOptionContext with the argv as passed to main() will result in a
139 * program that can only accept commandline arguments with characters
140 * from the system codepage. This can cause problems when attempting to
141 * deal with filenames containing Unicode characters that fall outside
144 * A solution to this is to use g_win32_get_command_line() and
145 * g_option_context_parse_strv() which will properly handle full Unicode
146 * filenames. If you are using #GApplication, this is done
147 * automatically for you.
149 * The following example shows how you can use #GOptionContext directly
150 * in order to correctly deal with Unicode filenames on Windows:
152 * |[<!-- language="C" -->
154 * main (int argc, char **argv)
156 * GError *error = NULL;
157 * GOptionContext *context;
161 * args = g_win32_get_command_line ();
163 * args = g_strdupv (argv);
166 * /* ... setup context ... */
168 * if (!g_option_context_parse_strv (context, &args, &error))
170 * /* ... error ... */
189 #if defined __OpenBSD__
190 #include <sys/types.h>
192 #include <sys/param.h>
193 #include <sys/sysctl.h>
199 #include "glibintl.h"
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;
256 GOptionGroup *main_group;
258 /* We keep a list of change so we can revert them */
261 /* We also keep track of all argv elements
262 * that should be NULLed or modified.
264 GList *pending_nulls;
271 gchar *help_description;
273 GDestroyNotify destroy_notify;
276 GTranslateFunc translate_func;
277 GDestroyNotify translate_notify;
278 gpointer translate_data;
280 GOptionEntry *entries;
283 GOptionParseFunc pre_parse_func;
284 GOptionParseFunc post_parse_func;
285 GOptionErrorFunc error_func;
288 static void free_changes_list (GOptionContext *context,
290 static void free_pending_nulls (GOptionContext *context,
291 gboolean perform_nulls);
295 _g_unichar_get_width (gunichar c)
297 if (G_UNLIKELY (g_unichar_iszerowidth (c)))
300 /* we ignore the fact that we should call g_unichar_iswide_cjk() under
301 * some locales (legacy East Asian ones) */
302 if (g_unichar_iswide (c))
309 _g_utf8_strwidth (const gchar *p)
312 g_return_val_if_fail (p != NULL, 0);
316 len += _g_unichar_get_width (g_utf8_get_char (p));
317 p = g_utf8_next_char (p);
323 G_DEFINE_QUARK (g-option-context-error-quark, g_option_error)
326 * g_option_context_new:
327 * @parameter_string: (allow-none): a string which is displayed in
328 * the first line of `--help` output, after the
330 * `<replaceable>programname</replaceable> [OPTION...]`
332 * Creates a new option context.
334 * The @parameter_string can serve multiple purposes. It can be used
335 * to add descriptions for "rest" arguments, which are not parsed by
336 * the #GOptionContext, typically something like "FILES" or
337 * "FILE1 FILE2...". If you are using #G_OPTION_REMAINING for
338 * collecting "rest" arguments, GLib handles this automatically by
339 * using the @arg_description of the corresponding #GOptionEntry in
342 * Another usage is to give a short summary of the program
343 * functionality, like " - frob the strings", which will be displayed
344 * in the same line as the usage. For a longer description of the
345 * program functionality that should be displayed as a paragraph
346 * below the usage line, use g_option_context_set_summary().
348 * Note that the @parameter_string is translated using the
349 * function set with g_option_context_set_translate_func(), so
350 * it should normally be passed untranslated.
352 * Returns: a newly created #GOptionContext, which must be
353 * freed with g_option_context_free() after use.
358 g_option_context_new (const gchar *parameter_string)
361 GOptionContext *context;
363 context = g_new0 (GOptionContext, 1);
365 context->parameter_string = g_strdup (parameter_string);
366 context->help_enabled = TRUE;
367 context->ignore_unknown = FALSE;
373 * g_option_context_free:
374 * @context: a #GOptionContext
376 * Frees context and all the groups which have been
379 * Please note that parsed arguments need to be freed separately (see
384 void g_option_context_free (GOptionContext *context)
386 g_return_if_fail (context != NULL);
388 g_list_free_full (context->groups, (GDestroyNotify) g_option_group_free);
390 if (context->main_group)
391 g_option_group_free (context->main_group);
393 free_changes_list (context, FALSE);
394 free_pending_nulls (context, FALSE);
396 g_free (context->parameter_string);
397 g_free (context->summary);
398 g_free (context->description);
400 if (context->translate_notify)
401 (* context->translate_notify) (context->translate_data);
408 * g_option_context_set_help_enabled:
409 * @context: a #GOptionContext
410 * @help_enabled: %TRUE to enable `--help`, %FALSE to disable it
412 * Enables or disables automatic generation of `--help`
413 * output. By default, g_option_context_parse() recognizes
414 * `--help`, `-h`, `-?`, `--help-all`
415 * and `--help-`<replaceable>groupname</replaceable> and creates
416 * suitable output to stdout.
420 void g_option_context_set_help_enabled (GOptionContext *context,
421 gboolean help_enabled)
424 g_return_if_fail (context != NULL);
426 context->help_enabled = help_enabled;
430 * g_option_context_get_help_enabled:
431 * @context: a #GOptionContext
433 * Returns whether automatic `--help` generation
434 * is turned on for @context. See g_option_context_set_help_enabled().
436 * Returns: %TRUE if automatic help generation is turned on.
441 g_option_context_get_help_enabled (GOptionContext *context)
443 g_return_val_if_fail (context != NULL, FALSE);
445 return context->help_enabled;
449 * g_option_context_set_ignore_unknown_options:
450 * @context: a #GOptionContext
451 * @ignore_unknown: %TRUE to ignore unknown options, %FALSE to produce
452 * an error when unknown options are met
454 * Sets whether to ignore unknown options or not. If an argument is
455 * ignored, it is left in the @argv array after parsing. By default,
456 * g_option_context_parse() treats unknown options as error.
458 * This setting does not affect non-option arguments (i.e. arguments
459 * which don't start with a dash). But note that GOption cannot reliably
460 * determine whether a non-option belongs to a preceding unknown option.
465 g_option_context_set_ignore_unknown_options (GOptionContext *context,
466 gboolean ignore_unknown)
468 g_return_if_fail (context != NULL);
470 context->ignore_unknown = ignore_unknown;
474 * g_option_context_get_ignore_unknown_options:
475 * @context: a #GOptionContext
477 * Returns whether unknown options are ignored or not. See
478 * g_option_context_set_ignore_unknown_options().
480 * Returns: %TRUE if unknown options are ignored.
485 g_option_context_get_ignore_unknown_options (GOptionContext *context)
487 g_return_val_if_fail (context != NULL, FALSE);
489 return context->ignore_unknown;
493 * g_option_context_add_group:
494 * @context: a #GOptionContext
495 * @group: the group to add
497 * Adds a #GOptionGroup to the @context, so that parsing with @context
498 * will recognize the options in the group. Note that the group will
499 * be freed together with the context when g_option_context_free() is
500 * called, so you must not free the group yourself after adding it
506 g_option_context_add_group (GOptionContext *context,
511 g_return_if_fail (context != NULL);
512 g_return_if_fail (group != NULL);
513 g_return_if_fail (group->name != NULL);
514 g_return_if_fail (group->description != NULL);
515 g_return_if_fail (group->help_description != NULL);
517 for (list = context->groups; list; list = list->next)
519 GOptionGroup *g = (GOptionGroup *)list->data;
521 if ((group->name == NULL && g->name == NULL) ||
522 (group->name && g->name && strcmp (group->name, g->name) == 0))
523 g_warning ("A group named \"%s\" is already part of this GOptionContext",
527 context->groups = g_list_append (context->groups, group);
531 * g_option_context_set_main_group:
532 * @context: a #GOptionContext
533 * @group: the group to set as main group
535 * Sets a #GOptionGroup as main group of the @context.
536 * This has the same effect as calling g_option_context_add_group(),
537 * the only difference is that the options in the main group are
538 * treated differently when generating `--help` output.
543 g_option_context_set_main_group (GOptionContext *context,
546 g_return_if_fail (context != NULL);
547 g_return_if_fail (group != NULL);
549 if (context->main_group)
551 g_warning ("This GOptionContext already has a main group");
556 context->main_group = group;
560 * g_option_context_get_main_group:
561 * @context: a #GOptionContext
563 * Returns a pointer to the main group of @context.
565 * Return value: the main group of @context, or %NULL if @context doesn't
566 * have a main group. Note that group belongs to @context and should
567 * not be modified or freed.
572 g_option_context_get_main_group (GOptionContext *context)
574 g_return_val_if_fail (context != NULL, NULL);
576 return context->main_group;
580 * g_option_context_add_main_entries:
581 * @context: a #GOptionContext
582 * @entries: a %NULL-terminated array of #GOptionEntrys
583 * @translation_domain: (allow-none): a translation domain to use for translating
584 * the `--help` output for the options in @entries
585 * with gettext(), or %NULL
587 * A convenience function which creates a main group if it doesn't
588 * exist, adds the @entries to it and sets the translation domain.
593 g_option_context_add_main_entries (GOptionContext *context,
594 const GOptionEntry *entries,
595 const gchar *translation_domain)
597 g_return_if_fail (entries != NULL);
599 if (!context->main_group)
600 context->main_group = g_option_group_new (NULL, NULL, NULL, NULL, NULL);
602 g_option_group_add_entries (context->main_group, entries);
603 g_option_group_set_translation_domain (context->main_group, translation_domain);
607 calculate_max_length (GOptionGroup *group,
611 gint i, len, max_length;
612 const gchar *long_name;
616 for (i = 0; i < group->n_entries; i++)
618 entry = &group->entries[i];
620 if (entry->flags & G_OPTION_FLAG_HIDDEN)
623 long_name = g_hash_table_lookup (aliases, &entry->long_name);
625 long_name = entry->long_name;
626 len = _g_utf8_strwidth (long_name);
628 if (entry->short_name)
631 if (!NO_ARG (entry) && entry->arg_description)
632 len += 1 + _g_utf8_strwidth (TRANSLATE (group, entry->arg_description));
634 max_length = MAX (max_length, len);
641 print_entry (GOptionGroup *group,
643 const GOptionEntry *entry,
648 const gchar *long_name;
650 if (entry->flags & G_OPTION_FLAG_HIDDEN)
653 if (entry->long_name[0] == 0)
656 long_name = g_hash_table_lookup (aliases, &entry->long_name);
658 long_name = entry->long_name;
660 str = g_string_new (NULL);
662 if (entry->short_name)
663 g_string_append_printf (str, " -%c, --%s", entry->short_name, long_name);
665 g_string_append_printf (str, " --%s", long_name);
667 if (entry->arg_description)
668 g_string_append_printf (str, "=%s", TRANSLATE (group, entry->arg_description));
670 g_string_append_printf (string, "%s%*s %s\n", str->str,
671 (int) (max_length + 4 - _g_utf8_strwidth (str->str)), "",
672 entry->description ? TRANSLATE (group, entry->description) : "");
673 g_string_free (str, TRUE);
677 group_has_visible_entries (GOptionContext *context,
679 gboolean main_entries)
681 GOptionFlags reject_filter = G_OPTION_FLAG_HIDDEN;
684 gboolean main_group = group == context->main_group;
687 reject_filter |= G_OPTION_FLAG_IN_MAIN;
689 for (i = 0, l = (group ? group->n_entries : 0); i < l; i++)
691 entry = &group->entries[i];
693 if (main_entries && !main_group && !(entry->flags & G_OPTION_FLAG_IN_MAIN))
695 if (entry->long_name[0] == 0) /* ignore rest entry */
697 if (!(entry->flags & reject_filter))
705 group_list_has_visible_entries (GOptionContext *context,
707 gboolean main_entries)
711 if (group_has_visible_entries (context, group_list->data, main_entries))
714 group_list = group_list->next;
721 context_has_h_entry (GOptionContext *context)
726 if (context->main_group)
728 for (i = 0; i < context->main_group->n_entries; i++)
730 if (context->main_group->entries[i].short_name == 'h')
735 for (list = context->groups; list != NULL; list = g_list_next (list))
739 group = (GOptionGroup*)list->data;
740 for (i = 0; i < group->n_entries; i++)
742 if (group->entries[i].short_name == 'h')
750 * g_option_context_get_help:
751 * @context: a #GOptionContext
752 * @main_help: if %TRUE, only include the main group
753 * @group: (allow-none): the #GOptionGroup to create help for, or %NULL
755 * Returns a formatted, translated help text for the given context.
756 * To obtain the text produced by `--help`, call
757 * `g_option_context_get_help (context, TRUE, NULL)`.
758 * To obtain the text produced by `--help-all`, call
759 * `g_option_context_get_help (context, FALSE, NULL)`.
760 * To obtain the help text for an option group, call
761 * `g_option_context_get_help (context, FALSE, group)`.
763 * Returns: A newly allocated string containing the help text
768 g_option_context_get_help (GOptionContext *context,
773 gint max_length = 0, len;
776 GHashTable *shadow_map;
779 const gchar *rest_description;
783 string = g_string_sized_new (1024);
785 rest_description = NULL;
786 if (context->main_group)
789 for (i = 0; i < context->main_group->n_entries; i++)
791 entry = &context->main_group->entries[i];
792 if (entry->long_name[0] == 0)
794 rest_description = TRANSLATE (context->main_group, entry->arg_description);
800 g_string_append_printf (string, "%s\n %s %s",
801 _("Usage:"), g_get_prgname(), _("[OPTION...]"));
803 if (rest_description)
805 g_string_append (string, " ");
806 g_string_append (string, rest_description);
809 if (context->parameter_string)
811 g_string_append (string, " ");
812 g_string_append (string, TRANSLATE (context, context->parameter_string));
815 g_string_append (string, "\n\n");
817 if (context->summary)
819 g_string_append (string, TRANSLATE (context, context->summary));
820 g_string_append (string, "\n\n");
823 memset (seen, 0, sizeof (gboolean) * 256);
824 shadow_map = g_hash_table_new (g_str_hash, g_str_equal);
825 aliases = g_hash_table_new_full (NULL, NULL, NULL, g_free);
827 if (context->main_group)
829 for (i = 0; i < context->main_group->n_entries; i++)
831 entry = &context->main_group->entries[i];
832 g_hash_table_insert (shadow_map,
833 (gpointer)entry->long_name,
836 if (seen[(guchar)entry->short_name])
837 entry->short_name = 0;
839 seen[(guchar)entry->short_name] = TRUE;
843 list = context->groups;
846 GOptionGroup *g = list->data;
847 for (i = 0; i < g->n_entries; i++)
849 entry = &g->entries[i];
850 if (g_hash_table_lookup (shadow_map, entry->long_name) &&
851 !(entry->flags & G_OPTION_FLAG_NOALIAS))
853 g_hash_table_insert (aliases, &entry->long_name,
854 g_strdup_printf ("%s-%s", g->name, entry->long_name));
857 g_hash_table_insert (shadow_map, (gpointer)entry->long_name, entry);
859 if (seen[(guchar)entry->short_name] &&
860 !(entry->flags & G_OPTION_FLAG_NOALIAS))
861 entry->short_name = 0;
863 seen[(guchar)entry->short_name] = TRUE;
868 g_hash_table_destroy (shadow_map);
870 list = context->groups;
872 if (context->help_enabled)
874 max_length = _g_utf8_strwidth ("-?, --help");
878 len = _g_utf8_strwidth ("--help-all");
879 max_length = MAX (max_length, len);
883 if (context->main_group)
885 len = calculate_max_length (context->main_group, aliases);
886 max_length = MAX (max_length, len);
891 GOptionGroup *g = list->data;
893 if (context->help_enabled)
895 /* First, we check the --help-<groupname> options */
896 len = _g_utf8_strwidth ("--help-") + _g_utf8_strwidth (g->name);
897 max_length = MAX (max_length, len);
900 /* Then we go through the entries */
901 len = calculate_max_length (g, aliases);
902 max_length = MAX (max_length, len);
907 /* Add a bit of padding */
910 if (!group && context->help_enabled)
912 list = context->groups;
914 token = context_has_h_entry (context) ? '?' : 'h';
916 g_string_append_printf (string, "%s\n -%c, --%-*s %s\n",
917 _("Help Options:"), token, max_length - 4, "help",
918 _("Show help options"));
920 /* We only want --help-all when there are groups */
922 g_string_append_printf (string, " --%-*s %s\n",
923 max_length, "help-all",
924 _("Show all help options"));
928 GOptionGroup *g = list->data;
930 if (group_has_visible_entries (context, g, FALSE))
931 g_string_append_printf (string, " --help-%-*s %s\n",
932 max_length - 5, g->name,
933 TRANSLATE (g, g->help_description));
938 g_string_append (string, "\n");
943 /* Print a certain group */
945 if (group_has_visible_entries (context, group, FALSE))
947 g_string_append (string, TRANSLATE (group, group->description));
948 g_string_append (string, "\n");
949 for (i = 0; i < group->n_entries; i++)
950 print_entry (group, max_length, &group->entries[i], string, aliases);
951 g_string_append (string, "\n");
956 /* Print all groups */
958 list = context->groups;
962 GOptionGroup *g = list->data;
964 if (group_has_visible_entries (context, g, FALSE))
966 g_string_append (string, g->description);
967 g_string_append (string, "\n");
968 for (i = 0; i < g->n_entries; i++)
969 if (!(g->entries[i].flags & G_OPTION_FLAG_IN_MAIN))
970 print_entry (g, max_length, &g->entries[i], string, aliases);
972 g_string_append (string, "\n");
979 /* Print application options if --help or --help-all has been specified */
980 if ((main_help || !group) &&
981 (group_has_visible_entries (context, context->main_group, TRUE) ||
982 group_list_has_visible_entries (context, context->groups, TRUE)))
984 list = context->groups;
986 g_string_append (string, _("Application Options:"));
987 g_string_append (string, "\n");
988 if (context->main_group)
989 for (i = 0; i < context->main_group->n_entries; i++)
990 print_entry (context->main_group, max_length,
991 &context->main_group->entries[i], string, aliases);
995 GOptionGroup *g = list->data;
997 /* Print main entries from other groups */
998 for (i = 0; i < g->n_entries; i++)
999 if (g->entries[i].flags & G_OPTION_FLAG_IN_MAIN)
1000 print_entry (g, max_length, &g->entries[i], string, aliases);
1005 g_string_append (string, "\n");
1008 if (context->description)
1010 g_string_append (string, TRANSLATE (context, context->description));
1011 g_string_append (string, "\n");
1014 g_hash_table_destroy (aliases);
1016 return g_string_free (string, FALSE);
1021 print_help (GOptionContext *context,
1023 GOptionGroup *group)
1027 help = g_option_context_get_help (context, main_help, group);
1028 g_print ("%s", help);
1035 parse_int (const gchar *arg_name,
1044 tmp = strtol (arg, &end, 0);
1046 if (*arg == '\0' || *end != '\0')
1049 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1050 _("Cannot parse integer value '%s' for %s"),
1056 if (*result != tmp || errno == ERANGE)
1059 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1060 _("Integer value '%s' for %s out of range"),
1070 parse_double (const gchar *arg_name,
1079 tmp = g_strtod (arg, &end);
1081 if (*arg == '\0' || *end != '\0')
1084 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1085 _("Cannot parse double value '%s' for %s"),
1089 if (errno == ERANGE)
1092 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1093 _("Double value '%s' for %s out of range"),
1105 parse_int64 (const gchar *arg_name,
1114 tmp = g_ascii_strtoll (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"),
1124 if (errno == ERANGE)
1127 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1128 _("Integer value '%s' for %s out of range"),
1140 get_change (GOptionContext *context,
1141 GOptionArg arg_type,
1145 Change *change = NULL;
1147 for (list = context->changes; list != NULL; list = list->next)
1149 change = list->data;
1151 if (change->arg_data == arg_data)
1155 change = g_new0 (Change, 1);
1156 change->arg_type = arg_type;
1157 change->arg_data = arg_data;
1159 context->changes = g_list_prepend (context->changes, change);
1167 add_pending_null (GOptionContext *context,
1173 n = g_new0 (PendingNull, 1);
1177 context->pending_nulls = g_list_prepend (context->pending_nulls, n);
1181 parse_arg (GOptionContext *context,
1182 GOptionGroup *group,
1183 GOptionEntry *entry,
1185 const gchar *option_name,
1191 g_assert (value || OPTIONAL_ARG (entry) || NO_ARG (entry));
1195 case G_OPTION_ARG_NONE:
1197 change = get_change (context, G_OPTION_ARG_NONE,
1200 *(gboolean *)entry->arg_data = !(entry->flags & G_OPTION_FLAG_REVERSE);
1203 case G_OPTION_ARG_STRING:
1208 if (!context->strv_mode)
1209 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1211 data = g_strdup (value);
1213 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1219 change = get_change (context, G_OPTION_ARG_STRING,
1221 g_free (change->allocated.str);
1223 change->prev.str = *(gchar **)entry->arg_data;
1224 change->allocated.str = data;
1226 *(gchar **)entry->arg_data = data;
1229 case G_OPTION_ARG_STRING_ARRAY:
1234 if (!context->strv_mode)
1235 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1237 data = g_strdup (value);
1239 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1245 change = get_change (context, G_OPTION_ARG_STRING_ARRAY,
1248 if (change->allocated.array.len == 0)
1250 change->prev.array = *(gchar ***)entry->arg_data;
1251 change->allocated.array.data = g_new (gchar *, 2);
1254 change->allocated.array.data =
1255 g_renew (gchar *, change->allocated.array.data,
1256 change->allocated.array.len + 2);
1258 change->allocated.array.data[change->allocated.array.len] = data;
1259 change->allocated.array.data[change->allocated.array.len + 1] = NULL;
1261 change->allocated.array.len ++;
1263 *(gchar ***)entry->arg_data = change->allocated.array.data;
1268 case G_OPTION_ARG_FILENAME:
1273 if (!context->strv_mode)
1274 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1276 data = g_strdup (value);
1281 data = g_strdup (value);
1283 change = get_change (context, G_OPTION_ARG_FILENAME,
1285 g_free (change->allocated.str);
1287 change->prev.str = *(gchar **)entry->arg_data;
1288 change->allocated.str = data;
1290 *(gchar **)entry->arg_data = data;
1294 case G_OPTION_ARG_FILENAME_ARRAY:
1299 if (!context->strv_mode)
1300 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1302 data = g_strdup (value);
1307 data = g_strdup (value);
1309 change = get_change (context, G_OPTION_ARG_STRING_ARRAY,
1312 if (change->allocated.array.len == 0)
1314 change->prev.array = *(gchar ***)entry->arg_data;
1315 change->allocated.array.data = g_new (gchar *, 2);
1318 change->allocated.array.data =
1319 g_renew (gchar *, change->allocated.array.data,
1320 change->allocated.array.len + 2);
1322 change->allocated.array.data[change->allocated.array.len] = data;
1323 change->allocated.array.data[change->allocated.array.len + 1] = NULL;
1325 change->allocated.array.len ++;
1327 *(gchar ***)entry->arg_data = change->allocated.array.data;
1332 case G_OPTION_ARG_INT:
1336 if (!parse_int (option_name, value,
1341 change = get_change (context, G_OPTION_ARG_INT,
1343 change->prev.integer = *(gint *)entry->arg_data;
1344 *(gint *)entry->arg_data = data;
1347 case G_OPTION_ARG_CALLBACK:
1352 if (!value && entry->flags & G_OPTION_FLAG_OPTIONAL_ARG)
1354 else if (entry->flags & G_OPTION_FLAG_NO_ARG)
1356 else if (entry->flags & G_OPTION_FLAG_FILENAME)
1359 if (!context->strv_mode)
1360 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1362 data = g_strdup (value);
1364 data = g_strdup (value);
1368 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1370 if (!(entry->flags & (G_OPTION_FLAG_NO_ARG|G_OPTION_FLAG_OPTIONAL_ARG)) &&
1374 retval = (* (GOptionArgFunc) entry->arg_data) (option_name, data, group->user_data, error);
1376 if (!retval && error != NULL && *error == NULL)
1378 G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
1379 _("Error parsing option %s"), option_name);
1387 case G_OPTION_ARG_DOUBLE:
1391 if (!parse_double (option_name, value,
1398 change = get_change (context, G_OPTION_ARG_DOUBLE,
1400 change->prev.dbl = *(gdouble *)entry->arg_data;
1401 *(gdouble *)entry->arg_data = data;
1404 case G_OPTION_ARG_INT64:
1408 if (!parse_int64 (option_name, value,
1415 change = get_change (context, G_OPTION_ARG_INT64,
1417 change->prev.int64 = *(gint64 *)entry->arg_data;
1418 *(gint64 *)entry->arg_data = data;
1422 g_assert_not_reached ();
1429 parse_short_option (GOptionContext *context,
1430 GOptionGroup *group,
1441 for (j = 0; j < group->n_entries; j++)
1443 if (arg == group->entries[j].short_name)
1446 gchar *value = NULL;
1448 option_name = g_strdup_printf ("-%c", group->entries[j].short_name);
1450 if (NO_ARG (&group->entries[j]))
1457 G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
1458 _("Error parsing option %s"), option_name);
1459 g_free (option_name);
1463 if (idx < *argc - 1)
1465 if (!OPTIONAL_ARG (&group->entries[j]))
1467 value = (*argv)[idx + 1];
1468 add_pending_null (context, &((*argv)[idx + 1]), NULL);
1473 if ((*argv)[idx + 1][0] == '-')
1477 value = (*argv)[idx + 1];
1478 add_pending_null (context, &((*argv)[idx + 1]), NULL);
1483 else if (idx >= *argc - 1 && OPTIONAL_ARG (&group->entries[j]))
1488 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1489 _("Missing argument for %s"), option_name);
1490 g_free (option_name);
1495 if (!parse_arg (context, group, &group->entries[j],
1496 value, option_name, error))
1498 g_free (option_name);
1502 g_free (option_name);
1511 parse_long_option (GOptionContext *context,
1512 GOptionGroup *group,
1523 for (j = 0; j < group->n_entries; j++)
1528 if (aliased && (group->entries[j].flags & G_OPTION_FLAG_NOALIAS))
1531 if (NO_ARG (&group->entries[j]) &&
1532 strcmp (arg, group->entries[j].long_name) == 0)
1537 option_name = g_strconcat ("--", group->entries[j].long_name, NULL);
1538 retval = parse_arg (context, group, &group->entries[j],
1539 NULL, option_name, error);
1540 g_free (option_name);
1542 add_pending_null (context, &((*argv)[*idx]), NULL);
1549 gint len = strlen (group->entries[j].long_name);
1551 if (strncmp (arg, group->entries[j].long_name, len) == 0 &&
1552 (arg[len] == '=' || arg[len] == 0))
1554 gchar *value = NULL;
1557 add_pending_null (context, &((*argv)[*idx]), NULL);
1558 option_name = g_strconcat ("--", group->entries[j].long_name, NULL);
1560 if (arg[len] == '=')
1561 value = arg + len + 1;
1562 else if (*idx < *argc - 1)
1564 if (!OPTIONAL_ARG (&group->entries[j]))
1566 value = (*argv)[*idx + 1];
1567 add_pending_null (context, &((*argv)[*idx + 1]), NULL);
1572 if ((*argv)[*idx + 1][0] == '-')
1575 retval = parse_arg (context, group, &group->entries[j],
1576 NULL, option_name, error);
1578 g_free (option_name);
1583 value = (*argv)[*idx + 1];
1584 add_pending_null (context, &((*argv)[*idx + 1]), NULL);
1589 else if (*idx >= *argc - 1 && OPTIONAL_ARG (&group->entries[j]))
1592 retval = parse_arg (context, group, &group->entries[j],
1593 NULL, option_name, error);
1595 g_free (option_name);
1601 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1602 _("Missing argument for %s"), option_name);
1603 g_free (option_name);
1607 if (!parse_arg (context, group, &group->entries[j],
1608 value, option_name, error))
1610 g_free (option_name);
1614 g_free (option_name);
1624 parse_remaining_arg (GOptionContext *context,
1625 GOptionGroup *group,
1634 for (j = 0; j < group->n_entries; j++)
1639 if (group->entries[j].long_name[0])
1642 g_return_val_if_fail (group->entries[j].arg == G_OPTION_ARG_CALLBACK ||
1643 group->entries[j].arg == G_OPTION_ARG_STRING_ARRAY ||
1644 group->entries[j].arg == G_OPTION_ARG_FILENAME_ARRAY, FALSE);
1646 add_pending_null (context, &((*argv)[*idx]), NULL);
1648 if (!parse_arg (context, group, &group->entries[j], (*argv)[*idx], "", error))
1659 free_changes_list (GOptionContext *context,
1664 for (list = context->changes; list != NULL; list = list->next)
1666 Change *change = list->data;
1670 switch (change->arg_type)
1672 case G_OPTION_ARG_NONE:
1673 *(gboolean *)change->arg_data = change->prev.bool;
1675 case G_OPTION_ARG_INT:
1676 *(gint *)change->arg_data = change->prev.integer;
1678 case G_OPTION_ARG_STRING:
1679 case G_OPTION_ARG_FILENAME:
1680 g_free (change->allocated.str);
1681 *(gchar **)change->arg_data = change->prev.str;
1683 case G_OPTION_ARG_STRING_ARRAY:
1684 case G_OPTION_ARG_FILENAME_ARRAY:
1685 g_strfreev (change->allocated.array.data);
1686 *(gchar ***)change->arg_data = change->prev.array;
1688 case G_OPTION_ARG_DOUBLE:
1689 *(gdouble *)change->arg_data = change->prev.dbl;
1691 case G_OPTION_ARG_INT64:
1692 *(gint64 *)change->arg_data = change->prev.int64;
1695 g_assert_not_reached ();
1702 g_list_free (context->changes);
1703 context->changes = NULL;
1707 free_pending_nulls (GOptionContext *context,
1708 gboolean perform_nulls)
1712 for (list = context->pending_nulls; list != NULL; list = list->next)
1714 PendingNull *n = list->data;
1720 /* Copy back the short options */
1722 strcpy (*n->ptr + 1, n->value);
1726 if (context->strv_mode)
1737 g_list_free (context->pending_nulls);
1738 context->pending_nulls = NULL;
1741 /* Use a platform-specific mechanism to look up the first argument to
1742 * the current process.
1743 * Note if you implement this for other platforms, also add it to
1744 * tests/option-argv0.c
1747 platform_get_argv0 (void)
1754 if (!g_file_get_contents ("/proc/self/cmdline",
1759 /* Sanity check for a NUL terminator. */
1760 if (!memchr (cmdline, 0, len))
1762 /* We could just return cmdline, but I think it's better
1763 * to hold on to a smaller malloc block; the arguments
1766 base_arg0 = g_path_get_basename (cmdline);
1769 #elif defined __OpenBSD__
1770 char **cmdline = NULL;
1772 gsize len = PATH_MAX;
1774 int mib[] = { CTL_KERN, KERN_PROC_ARGS, getpid(), KERN_PROC_ARGV };
1776 cmdline = (char **) realloc (cmdline, len);
1778 if (sysctl (mib, G_N_ELEMENTS (mib), cmdline, &len, NULL, 0) == -1)
1784 /* We could just return cmdline, but I think it's better
1785 * to hold on to a smaller malloc block; the arguments
1788 base_arg0 = g_path_get_basename (*cmdline);
1797 * g_option_context_parse:
1798 * @context: a #GOptionContext
1799 * @argc: (inout) (allow-none): a pointer to the number of command line arguments
1800 * @argv: (inout) (array length=argc) (allow-none): a pointer to the array of command line arguments
1801 * @error: a return location for errors
1803 * Parses the command line arguments, recognizing options
1804 * which have been added to @context. A side-effect of
1805 * calling this function is that g_set_prgname() will be
1808 * If the parsing is successful, any parsed arguments are
1809 * removed from the array and @argc and @argv are updated
1810 * accordingly. A '--' option is stripped from @argv
1811 * unless there are unparsed options before and after it,
1812 * or some of the options after it start with '-'. In case
1813 * of an error, @argc and @argv are left unmodified.
1815 * If automatic `--help` support is enabled
1816 * (see g_option_context_set_help_enabled()), and the
1817 * @argv array contains one of the recognized help options,
1818 * this function will produce help output to stdout and
1821 * Note that function depends on the
1822 * <link linkend="setlocale">current locale</link> for
1823 * automatic character set conversion of string and filename
1826 * Return value: %TRUE if the parsing was successful,
1827 * %FALSE if an error occurred
1832 g_option_context_parse (GOptionContext *context,
1840 /* Set program name */
1841 if (!g_get_prgname())
1845 if (argc && argv && *argc)
1846 prgname = g_path_get_basename ((*argv)[0]);
1848 prgname = platform_get_argv0 ();
1851 g_set_prgname (prgname);
1853 g_set_prgname ("<unknown>");
1858 /* Call pre-parse hooks */
1859 list = context->groups;
1862 GOptionGroup *group = list->data;
1864 if (group->pre_parse_func)
1866 if (!(* group->pre_parse_func) (context, group,
1867 group->user_data, error))
1874 if (context->main_group && context->main_group->pre_parse_func)
1876 if (!(* context->main_group->pre_parse_func) (context, context->main_group,
1877 context->main_group->user_data, error))
1883 gboolean stop_parsing = FALSE;
1884 gboolean has_unknown = FALSE;
1885 gint separator_pos = 0;
1887 for (i = 1; i < *argc; i++)
1890 gboolean parsed = FALSE;
1892 if ((*argv)[i][0] == '-' && (*argv)[i][1] != '\0' && !stop_parsing)
1894 if ((*argv)[i][1] == '-')
1898 arg = (*argv)[i] + 2;
1900 /* '--' terminates list of arguments */
1904 stop_parsing = TRUE;
1908 /* Handle help options */
1909 if (context->help_enabled)
1911 if (strcmp (arg, "help") == 0)
1912 print_help (context, TRUE, NULL);
1913 else if (strcmp (arg, "help-all") == 0)
1914 print_help (context, FALSE, NULL);
1915 else if (strncmp (arg, "help-", 5) == 0)
1917 list = context->groups;
1921 GOptionGroup *group = list->data;
1923 if (strcmp (arg + 5, group->name) == 0)
1924 print_help (context, FALSE, group);
1931 if (context->main_group &&
1932 !parse_long_option (context, context->main_group, &i, arg,
1933 FALSE, argc, argv, error, &parsed))
1939 /* Try the groups */
1940 list = context->groups;
1943 GOptionGroup *group = list->data;
1945 if (!parse_long_option (context, group, &i, arg,
1946 FALSE, argc, argv, error, &parsed))
1958 /* Now look for --<group>-<option> */
1959 dash = strchr (arg, '-');
1962 /* Try the groups */
1963 list = context->groups;
1966 GOptionGroup *group = list->data;
1968 if (strncmp (group->name, arg, dash - arg) == 0)
1970 if (!parse_long_option (context, group, &i, dash + 1,
1971 TRUE, argc, argv, error, &parsed))
1982 if (context->ignore_unknown)
1986 { /* short option */
1987 gint new_i = i, arg_length;
1988 gboolean *nulled_out = NULL;
1989 gboolean has_h_entry = context_has_h_entry (context);
1990 arg = (*argv)[i] + 1;
1991 arg_length = strlen (arg);
1992 nulled_out = g_newa (gboolean, arg_length);
1993 memset (nulled_out, 0, arg_length * sizeof (gboolean));
1994 for (j = 0; j < arg_length; j++)
1996 if (context->help_enabled && (arg[j] == '?' ||
1997 (arg[j] == 'h' && !has_h_entry)))
1998 print_help (context, TRUE, NULL);
2000 if (context->main_group &&
2001 !parse_short_option (context, context->main_group,
2003 argc, argv, error, &parsed))
2007 /* Try the groups */
2008 list = context->groups;
2011 GOptionGroup *group = list->data;
2012 if (!parse_short_option (context, group, i, &new_i, arg[j],
2013 argc, argv, error, &parsed))
2021 if (context->ignore_unknown && parsed)
2022 nulled_out[j] = TRUE;
2023 else if (context->ignore_unknown)
2027 /* !context->ignore_unknown && parsed */
2029 if (context->ignore_unknown)
2031 gchar *new_arg = NULL;
2033 for (j = 0; j < arg_length; j++)
2038 new_arg = g_malloc (arg_length + 1);
2039 new_arg[arg_index++] = arg[j];
2043 new_arg[arg_index] = '\0';
2044 add_pending_null (context, &((*argv)[i]), new_arg);
2048 add_pending_null (context, &((*argv)[i]), NULL);
2056 if (!parsed && !context->ignore_unknown)
2059 G_OPTION_ERROR, G_OPTION_ERROR_UNKNOWN_OPTION,
2060 _("Unknown option %s"), (*argv)[i]);
2066 /* Collect remaining args */
2067 if (context->main_group &&
2068 !parse_remaining_arg (context, context->main_group, &i,
2069 argc, argv, error, &parsed))
2072 if (!parsed && (has_unknown || (*argv)[i][0] == '-'))
2077 if (separator_pos > 0)
2078 add_pending_null (context, &((*argv)[separator_pos]), NULL);
2082 /* Call post-parse hooks */
2083 list = context->groups;
2086 GOptionGroup *group = list->data;
2088 if (group->post_parse_func)
2090 if (!(* group->post_parse_func) (context, group,
2091 group->user_data, error))
2098 if (context->main_group && context->main_group->post_parse_func)
2100 if (!(* context->main_group->post_parse_func) (context, context->main_group,
2101 context->main_group->user_data, error))
2107 free_pending_nulls (context, TRUE);
2109 for (i = 1; i < *argc; i++)
2111 for (k = i; k < *argc; k++)
2112 if ((*argv)[k] != NULL)
2118 for (j = i + k; j < *argc; j++)
2120 (*argv)[j-k] = (*argv)[j];
2132 /* Call error hooks */
2133 list = context->groups;
2136 GOptionGroup *group = list->data;
2138 if (group->error_func)
2139 (* group->error_func) (context, group,
2140 group->user_data, error);
2145 if (context->main_group && context->main_group->error_func)
2146 (* context->main_group->error_func) (context, context->main_group,
2147 context->main_group->user_data, error);
2149 free_changes_list (context, TRUE);
2150 free_pending_nulls (context, FALSE);
2156 * g_option_group_new:
2157 * @name: the name for the option group, this is used to provide
2158 * help for the options in this group with `--help-`@name
2159 * @description: a description for this group to be shown in
2160 * `--help`. This string is translated using the translation
2161 * domain or translation function of the group
2162 * @help_description: a description for the `--help-`@name option.
2163 * This string is translated using the translation domain or translation function
2165 * @user_data: (allow-none): user data that will be passed to the pre- and post-parse hooks,
2166 * the error hook and to callbacks of %G_OPTION_ARG_CALLBACK options, or %NULL
2167 * @destroy: (allow-none): a function that will be called to free @user_data, or %NULL
2169 * Creates a new #GOptionGroup.
2171 * Return value: a newly created option group. It should be added
2172 * to a #GOptionContext or freed with g_option_group_free().
2177 g_option_group_new (const gchar *name,
2178 const gchar *description,
2179 const gchar *help_description,
2181 GDestroyNotify destroy)
2184 GOptionGroup *group;
2186 group = g_new0 (GOptionGroup, 1);
2187 group->name = g_strdup (name);
2188 group->description = g_strdup (description);
2189 group->help_description = g_strdup (help_description);
2190 group->user_data = user_data;
2191 group->destroy_notify = destroy;
2198 * g_option_group_free:
2199 * @group: a #GOptionGroup
2201 * Frees a #GOptionGroup. Note that you must not free groups
2202 * which have been added to a #GOptionContext.
2207 g_option_group_free (GOptionGroup *group)
2209 g_return_if_fail (group != NULL);
2211 g_free (group->name);
2212 g_free (group->description);
2213 g_free (group->help_description);
2215 g_free (group->entries);
2217 if (group->destroy_notify)
2218 (* group->destroy_notify) (group->user_data);
2220 if (group->translate_notify)
2221 (* group->translate_notify) (group->translate_data);
2228 * g_option_group_add_entries:
2229 * @group: a #GOptionGroup
2230 * @entries: a %NULL-terminated array of #GOptionEntrys
2232 * Adds the options specified in @entries to @group.
2237 g_option_group_add_entries (GOptionGroup *group,
2238 const GOptionEntry *entries)
2242 g_return_if_fail (entries != NULL);
2244 for (n_entries = 0; entries[n_entries].long_name != NULL; n_entries++) ;
2246 group->entries = g_renew (GOptionEntry, group->entries, group->n_entries + n_entries);
2248 memcpy (group->entries + group->n_entries, entries, sizeof (GOptionEntry) * n_entries);
2250 for (i = group->n_entries; i < group->n_entries + n_entries; i++)
2252 gchar c = group->entries[i].short_name;
2254 if (c == '-' || (c != 0 && !g_ascii_isprint (c)))
2256 g_warning (G_STRLOC ": ignoring invalid short option '%c' (%d) in entry %s:%s",
2257 c, c, group->name, group->entries[i].long_name);
2258 group->entries[i].short_name = '\0';
2261 if (group->entries[i].arg != G_OPTION_ARG_NONE &&
2262 (group->entries[i].flags & G_OPTION_FLAG_REVERSE) != 0)
2264 g_warning (G_STRLOC ": ignoring reverse flag on option of arg-type %d in entry %s:%s",
2265 group->entries[i].arg, group->name, group->entries[i].long_name);
2267 group->entries[i].flags &= ~G_OPTION_FLAG_REVERSE;
2270 if (group->entries[i].arg != G_OPTION_ARG_CALLBACK &&
2271 (group->entries[i].flags & (G_OPTION_FLAG_NO_ARG|G_OPTION_FLAG_OPTIONAL_ARG|G_OPTION_FLAG_FILENAME)) != 0)
2273 g_warning (G_STRLOC ": ignoring no-arg, optional-arg or filename flags (%d) on option of arg-type %d in entry %s:%s",
2274 group->entries[i].flags, group->entries[i].arg, group->name, group->entries[i].long_name);
2276 group->entries[i].flags &= ~(G_OPTION_FLAG_NO_ARG|G_OPTION_FLAG_OPTIONAL_ARG|G_OPTION_FLAG_FILENAME);
2280 group->n_entries += n_entries;
2284 * g_option_group_set_parse_hooks:
2285 * @group: a #GOptionGroup
2286 * @pre_parse_func: (allow-none): a function to call before parsing, or %NULL
2287 * @post_parse_func: (allow-none): a function to call after parsing, or %NULL
2289 * Associates two functions with @group which will be called
2290 * from g_option_context_parse() before the first option is parsed
2291 * and after the last option has been parsed, respectively.
2293 * Note that the user data to be passed to @pre_parse_func and
2294 * @post_parse_func can be specified when constructing the group
2295 * with g_option_group_new().
2300 g_option_group_set_parse_hooks (GOptionGroup *group,
2301 GOptionParseFunc pre_parse_func,
2302 GOptionParseFunc post_parse_func)
2304 g_return_if_fail (group != NULL);
2306 group->pre_parse_func = pre_parse_func;
2307 group->post_parse_func = post_parse_func;
2311 * g_option_group_set_error_hook:
2312 * @group: a #GOptionGroup
2313 * @error_func: a function to call when an error occurs
2315 * Associates a function with @group which will be called
2316 * from g_option_context_parse() when an error occurs.
2318 * Note that the user data to be passed to @error_func can be
2319 * specified when constructing the group with g_option_group_new().
2324 g_option_group_set_error_hook (GOptionGroup *group,
2325 GOptionErrorFunc error_func)
2327 g_return_if_fail (group != NULL);
2329 group->error_func = error_func;
2334 * g_option_group_set_translate_func:
2335 * @group: a #GOptionGroup
2336 * @func: (allow-none): the #GTranslateFunc, or %NULL
2337 * @data: (allow-none): user data to pass to @func, or %NULL
2338 * @destroy_notify: (allow-none): a function which gets called to free @data, or %NULL
2340 * Sets the function which is used to translate user-visible strings,
2341 * for `--help` output. Different groups can use different
2342 * #GTranslateFuncs. If @func is %NULL, strings are not translated.
2344 * If you are using gettext(), you only need to set the translation
2345 * domain, see g_option_group_set_translation_domain().
2350 g_option_group_set_translate_func (GOptionGroup *group,
2351 GTranslateFunc func,
2353 GDestroyNotify destroy_notify)
2355 g_return_if_fail (group != NULL);
2357 if (group->translate_notify)
2358 group->translate_notify (group->translate_data);
2360 group->translate_func = func;
2361 group->translate_data = data;
2362 group->translate_notify = destroy_notify;
2365 static const gchar *
2366 dgettext_swapped (const gchar *msgid,
2367 const gchar *domainname)
2369 return g_dgettext (domainname, msgid);
2373 * g_option_group_set_translation_domain:
2374 * @group: a #GOptionGroup
2375 * @domain: the domain to use
2377 * A convenience function to use gettext() for translating
2378 * user-visible strings.
2383 g_option_group_set_translation_domain (GOptionGroup *group,
2384 const gchar *domain)
2386 g_return_if_fail (group != NULL);
2388 g_option_group_set_translate_func (group,
2389 (GTranslateFunc)dgettext_swapped,
2395 * g_option_context_set_translate_func:
2396 * @context: a #GOptionContext
2397 * @func: (allow-none): the #GTranslateFunc, or %NULL
2398 * @data: (allow-none): user data to pass to @func, or %NULL
2399 * @destroy_notify: (allow-none): a function which gets called to free @data, or %NULL
2401 * Sets the function which is used to translate the contexts
2402 * user-visible strings, for `--help` output. If @func is %NULL,
2403 * strings are not translated.
2405 * Note that option groups have their own translation functions,
2406 * this function only affects the @parameter_string (see g_option_context_new()),
2407 * the summary (see g_option_context_set_summary()) and the description
2408 * (see g_option_context_set_description()).
2410 * If you are using gettext(), you only need to set the translation
2411 * domain, see g_option_context_set_translation_domain().
2416 g_option_context_set_translate_func (GOptionContext *context,
2417 GTranslateFunc func,
2419 GDestroyNotify destroy_notify)
2421 g_return_if_fail (context != NULL);
2423 if (context->translate_notify)
2424 context->translate_notify (context->translate_data);
2426 context->translate_func = func;
2427 context->translate_data = data;
2428 context->translate_notify = destroy_notify;
2432 * g_option_context_set_translation_domain:
2433 * @context: a #GOptionContext
2434 * @domain: the domain to use
2436 * A convenience function to use gettext() for translating
2437 * user-visible strings.
2442 g_option_context_set_translation_domain (GOptionContext *context,
2443 const gchar *domain)
2445 g_return_if_fail (context != NULL);
2447 g_option_context_set_translate_func (context,
2448 (GTranslateFunc)dgettext_swapped,
2454 * g_option_context_set_summary:
2455 * @context: a #GOptionContext
2456 * @summary: (allow-none): a string to be shown in `--help` output
2457 * before the list of options, or %NULL
2459 * Adds a string to be displayed in `--help` output before the list
2460 * of options. This is typically a summary of the program functionality.
2462 * Note that the summary is translated (see
2463 * g_option_context_set_translate_func() and
2464 * g_option_context_set_translation_domain()).
2469 g_option_context_set_summary (GOptionContext *context,
2470 const gchar *summary)
2472 g_return_if_fail (context != NULL);
2474 g_free (context->summary);
2475 context->summary = g_strdup (summary);
2480 * g_option_context_get_summary:
2481 * @context: a #GOptionContext
2483 * Returns the summary. See g_option_context_set_summary().
2485 * Returns: the summary
2490 g_option_context_get_summary (GOptionContext *context)
2492 g_return_val_if_fail (context != NULL, NULL);
2494 return context->summary;
2498 * g_option_context_set_description:
2499 * @context: a #GOptionContext
2500 * @description: (allow-none): a string to be shown in `--help` output
2501 * after the list of options, or %NULL
2503 * Adds a string to be displayed in `--help` output after the list
2504 * of options. This text often includes a bug reporting address.
2506 * Note that the summary is translated (see
2507 * g_option_context_set_translate_func()).
2512 g_option_context_set_description (GOptionContext *context,
2513 const gchar *description)
2515 g_return_if_fail (context != NULL);
2517 g_free (context->description);
2518 context->description = g_strdup (description);
2523 * g_option_context_get_description:
2524 * @context: a #GOptionContext
2526 * Returns the description. See g_option_context_set_description().
2528 * Returns: the description
2533 g_option_context_get_description (GOptionContext *context)
2535 g_return_val_if_fail (context != NULL, NULL);
2537 return context->description;
2541 * g_option_context_parse_strv:
2542 * @context: a #GOptionContext
2543 * @arguments: (inout) (array null-terminated=1): a pointer to the
2544 * command line arguments (which must be in UTF-8 on Windows)
2545 * @error: a return location for errors
2547 * Parses the command line arguments.
2549 * This function is similar to g_option_context_parse() except that it
2550 * respects the normal memory rules when dealing with a strv instead of
2551 * assuming that the passed-in array is the argv of the main function.
2553 * In particular, strings that are removed from the arguments list will
2554 * be freed using g_free().
2556 * On Windows, the strings are expected to be in UTF-8. This is in
2557 * contrast to g_option_context_parse() which expects them to be in the
2558 * system codepage, which is how they are passed as @argv to main().
2559 * See g_win32_get_command_line() for a solution.
2561 * This function is useful if you are trying to use #GOptionContext with
2564 * Returns: %TRUE if the parsing was successful,
2565 * %FALSE if an error occurred
2570 g_option_context_parse_strv (GOptionContext *context,
2577 context->strv_mode = TRUE;
2578 argc = g_strv_length (*arguments);
2579 success = g_option_context_parse (context, &argc, arguments, error);
2580 context->strv_mode = FALSE;