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, write to the
18 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 * Boston, MA 02111-1307, USA.
24 * @Short_description: parses commandline options
25 * @Title: Commandline option parser
27 * The GOption commandline parser is intended to be a simpler replacement
28 * for the popt library. It supports short and long commandline options,
29 * as shown in the following example:
31 * <literal>testtreemodel -r 1 --max-size 20 --rand --display=:1.0 -vb -- file1 file2</literal>
33 * The example demonstrates a number of features of the GOption
35 * <itemizedlist><listitem><para>
36 * Options can be single letters, prefixed by a single dash. Multiple
37 * short options can be grouped behind a single dash.
38 * </para></listitem><listitem><para>
39 * Long options are prefixed by two consecutive dashes.
40 * </para></listitem><listitem><para>
41 * Options can have an extra argument, which can be a number, a string or
42 * a filename. For long options, the extra argument can be appended with
43 * an equals sign after the option name, which is useful if the extra
44 * argument starts with a dash, which would otherwise cause it to be
45 * interpreted as another option.
46 * </para></listitem><listitem><para>
47 * Non-option arguments are returned to the application as rest arguments.
48 * </para></listitem><listitem><para>
49 * An argument consisting solely of two dashes turns off further parsing,
50 * any remaining arguments (even those starting with a dash) are returned
51 * to the application as rest arguments.
52 * </para></listitem></itemizedlist>
54 * Another important feature of GOption is that it can automatically
55 * generate nicely formatted help output. Unless it is explicitly turned
56 * off with g_option_context_set_help_enabled(), GOption will recognize
57 * the <option>--help</option>, <option>-?</option>,
58 * <option>--help-all</option> and
59 * <option>--help-</option><replaceable>groupname</replaceable> options
60 * (where <replaceable>groupname</replaceable> is the name of a
61 * #GOptionGroup) and write a text similar to the one shown in the
62 * following example to stdout.
64 * <informalexample><screen>
66 * testtreemodel [OPTION...] - test tree model performance
69 * -h, --help Show help options
70 * --help-all Show all help options
71 * --help-gtk Show GTK+ Options
73 * Application Options:
74 * -r, --repeats=N Average over N repetitions
75 * -m, --max-size=M Test up to 2^M items
76 * --display=DISPLAY X display to use
77 * -v, --verbose Be verbose
78 * -b, --beep Beep when done
79 * --rand Randomize the data
80 * </screen></informalexample>
82 * GOption groups options in #GOptionGroup<!-- -->s, which makes it easy to
83 * incorporate options from multiple sources. The intended use for this is
84 * to let applications collect option groups from the libraries it uses,
85 * add them to their #GOptionContext, and parse all options by a single call
86 * to g_option_context_parse(). See gtk_get_option_group() for an example.
88 * If an option is declared to be of type string or filename, GOption takes
89 * care of converting it to the right encoding; strings are returned in
90 * UTF-8, filenames are returned in the GLib filename encoding. Note that
91 * this only works if setlocale() has been called before
92 * g_option_context_parse().
94 * Here is a complete example of setting up GOption to parse the example
95 * commandline above and produce the example help output.
97 * <informalexample><programlisting>
98 * static gint repeats = 2;
99 * static gint max_size = 8;
100 * static gboolean verbose = FALSE;
101 * static gboolean beep = FALSE;
102 * static gboolean randomize = FALSE;
104 * static GOptionEntry entries[] =
106 * { "repeats", 'r', 0, G_OPTION_ARG_INT, &repeats, "Average over N repetitions", "N" },
107 * { "max-size", 'm', 0, G_OPTION_ARG_INT, &max_size, "Test up to 2^M items", "M" },
108 * { "verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose, "Be verbose", NULL },
109 * { "beep", 'b', 0, G_OPTION_ARG_NONE, &beep, "Beep when done", NULL },
110 * { "rand", 0, 0, G_OPTION_ARG_NONE, &randomize, "Randomize the data", NULL },
115 * main (int argc, char *argv[])
117 * GError *error = NULL;
118 * GOptionContext *context;
120 * context = g_option_context_new ("- test tree model performance");
121 * g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
122 * g_option_context_add_group (context, gtk_get_option_group (TRUE));
123 * if (!g_option_context_parse (context, &argc, &argv, &error))
125 * g_print ("option parsing failed: %s\n", error->message);
132 * </programlisting></informalexample>
134 * On UNIX systems, the argv that is passed to main() has no particular
135 * encoding, even to the extent that different parts of it may have
136 * different encodings. In general, normal arguments and flags will be
137 * in the current locale and filenames should be considered to be opaque
138 * byte strings. Proper use of %G_OPTION_ARG_FILENAME vs
139 * %G_OPTION_ARG_STRING is therefore important.
141 * Note that on Windows, filenames do have an encoding, but using
142 * #GOptionContext with the argv as passed to main() will result in a
143 * program that can only accept commandline arguments with characters
144 * from the system codepage. This can cause problems when attempting to
145 * deal with filenames containing Unicode characters that fall outside
148 * A solution to this is to use g_win32_get_command_line() and
149 * g_option_context_parse_strv() which will properly handle full Unicode
150 * filenames. If you are using #GApplication, this is done
151 * automatically for you.
153 * The following example shows how you can use #GOptionContext directly
154 * in order to correctly deal with Unicode filenames on Windows:
158 * main (int argc, char **argv)
160 * GError *error = NULL;
161 * GOptionContext *context;
165 * args = g_win32_get_command_line ();
167 * args = g_strdupv (argv);
170 * /* ... setup context ... */
172 * if (!g_option_context_parse_strv (context, &args, &error))
174 * /* ... error ... */
193 #if defined __OpenBSD__
194 #include <sys/types.h>
196 #include <sys/param.h>
197 #include <sys/sysctl.h>
203 #include "glibintl.h"
205 #define TRANSLATE(group, str) (((group)->translate_func ? (* (group)->translate_func) ((str), (group)->translate_data) : (str)))
207 #define NO_ARG(entry) ((entry)->arg == G_OPTION_ARG_NONE || \
208 ((entry)->arg == G_OPTION_ARG_CALLBACK && \
209 ((entry)->flags & G_OPTION_FLAG_NO_ARG)))
211 #define OPTIONAL_ARG(entry) ((entry)->arg == G_OPTION_ARG_CALLBACK && \
212 (entry)->flags & G_OPTION_FLAG_OPTIONAL_ARG)
244 struct _GOptionContext
248 gchar *parameter_string;
252 GTranslateFunc translate_func;
253 GDestroyNotify translate_notify;
254 gpointer translate_data;
256 guint help_enabled : 1;
257 guint ignore_unknown : 1;
260 GOptionGroup *main_group;
262 /* We keep a list of change so we can revert them */
265 /* We also keep track of all argv elements
266 * that should be NULLed or modified.
268 GList *pending_nulls;
275 gchar *help_description;
277 GDestroyNotify destroy_notify;
280 GTranslateFunc translate_func;
281 GDestroyNotify translate_notify;
282 gpointer translate_data;
284 GOptionEntry *entries;
287 GOptionParseFunc pre_parse_func;
288 GOptionParseFunc post_parse_func;
289 GOptionErrorFunc error_func;
292 static void free_changes_list (GOptionContext *context,
294 static void free_pending_nulls (GOptionContext *context,
295 gboolean perform_nulls);
299 _g_unichar_get_width (gunichar c)
301 if (G_UNLIKELY (g_unichar_iszerowidth (c)))
304 /* we ignore the fact that we should call g_unichar_iswide_cjk() under
305 * some locales (legacy East Asian ones) */
306 if (g_unichar_iswide (c))
313 _g_utf8_strwidth (const gchar *p)
316 g_return_val_if_fail (p != NULL, 0);
320 len += _g_unichar_get_width (g_utf8_get_char (p));
321 p = g_utf8_next_char (p);
327 G_DEFINE_QUARK (g-option-context-error-quark, g_option_error)
330 * g_option_context_new:
331 * @parameter_string: (allow-none): a string which is displayed in
332 * the first line of <option>--help</option> output, after the
334 * <literal><replaceable>programname</replaceable> [OPTION...]</literal>
336 * Creates a new option context.
338 * The @parameter_string can serve multiple purposes. It can be used
339 * to add descriptions for "rest" arguments, which are not parsed by
340 * the #GOptionContext, typically something like "FILES" or
341 * "FILE1 FILE2...". If you are using #G_OPTION_REMAINING for
342 * collecting "rest" arguments, GLib handles this automatically by
343 * using the @arg_description of the corresponding #GOptionEntry in
346 * Another usage is to give a short summary of the program
347 * functionality, like " - frob the strings", which will be displayed
348 * in the same line as the usage. For a longer description of the
349 * program functionality that should be displayed as a paragraph
350 * below the usage line, use g_option_context_set_summary().
352 * Note that the @parameter_string is translated using the
353 * function set with g_option_context_set_translate_func(), so
354 * it should normally be passed untranslated.
356 * Returns: a newly created #GOptionContext, which must be
357 * freed with g_option_context_free() after use.
362 g_option_context_new (const gchar *parameter_string)
365 GOptionContext *context;
367 context = g_new0 (GOptionContext, 1);
369 context->parameter_string = g_strdup (parameter_string);
370 context->help_enabled = TRUE;
371 context->ignore_unknown = FALSE;
377 * g_option_context_free:
378 * @context: a #GOptionContext
380 * Frees context and all the groups which have been
383 * Please note that parsed arguments need to be freed separately (see
388 void g_option_context_free (GOptionContext *context)
390 g_return_if_fail (context != NULL);
392 g_list_free_full (context->groups, (GDestroyNotify) g_option_group_free);
394 if (context->main_group)
395 g_option_group_free (context->main_group);
397 free_changes_list (context, FALSE);
398 free_pending_nulls (context, FALSE);
400 g_free (context->parameter_string);
401 g_free (context->summary);
402 g_free (context->description);
404 if (context->translate_notify)
405 (* context->translate_notify) (context->translate_data);
412 * g_option_context_set_help_enabled:
413 * @context: a #GOptionContext
414 * @help_enabled: %TRUE to enable <option>--help</option>, %FALSE to disable it
416 * Enables or disables automatic generation of <option>--help</option>
417 * output. By default, g_option_context_parse() recognizes
418 * <option>--help</option>, <option>-h</option>,
419 * <option>-?</option>, <option>--help-all</option>
420 * and <option>--help-</option><replaceable>groupname</replaceable> and creates
421 * suitable output to stdout.
425 void g_option_context_set_help_enabled (GOptionContext *context,
426 gboolean help_enabled)
429 g_return_if_fail (context != NULL);
431 context->help_enabled = help_enabled;
435 * g_option_context_get_help_enabled:
436 * @context: a #GOptionContext
438 * Returns whether automatic <option>--help</option> generation
439 * is turned on for @context. See g_option_context_set_help_enabled().
441 * Returns: %TRUE if automatic help generation is turned on.
446 g_option_context_get_help_enabled (GOptionContext *context)
448 g_return_val_if_fail (context != NULL, FALSE);
450 return context->help_enabled;
454 * g_option_context_set_ignore_unknown_options:
455 * @context: a #GOptionContext
456 * @ignore_unknown: %TRUE to ignore unknown options, %FALSE to produce
457 * an error when unknown options are met
459 * Sets whether to ignore unknown options or not. If an argument is
460 * ignored, it is left in the @argv array after parsing. By default,
461 * g_option_context_parse() treats unknown options as error.
463 * This setting does not affect non-option arguments (i.e. arguments
464 * which don't start with a dash). But note that GOption cannot reliably
465 * determine whether a non-option belongs to a preceding unknown option.
470 g_option_context_set_ignore_unknown_options (GOptionContext *context,
471 gboolean ignore_unknown)
473 g_return_if_fail (context != NULL);
475 context->ignore_unknown = ignore_unknown;
479 * g_option_context_get_ignore_unknown_options:
480 * @context: a #GOptionContext
482 * Returns whether unknown options are ignored or not. See
483 * g_option_context_set_ignore_unknown_options().
485 * Returns: %TRUE if unknown options are ignored.
490 g_option_context_get_ignore_unknown_options (GOptionContext *context)
492 g_return_val_if_fail (context != NULL, FALSE);
494 return context->ignore_unknown;
498 * g_option_context_add_group:
499 * @context: a #GOptionContext
500 * @group: the group to add
502 * Adds a #GOptionGroup to the @context, so that parsing with @context
503 * will recognize the options in the group. Note that the group will
504 * be freed together with the context when g_option_context_free() is
505 * called, so you must not free the group yourself after adding it
511 g_option_context_add_group (GOptionContext *context,
516 g_return_if_fail (context != NULL);
517 g_return_if_fail (group != NULL);
518 g_return_if_fail (group->name != NULL);
519 g_return_if_fail (group->description != NULL);
520 g_return_if_fail (group->help_description != NULL);
522 for (list = context->groups; list; list = list->next)
524 GOptionGroup *g = (GOptionGroup *)list->data;
526 if ((group->name == NULL && g->name == NULL) ||
527 (group->name && g->name && strcmp (group->name, g->name) == 0))
528 g_warning ("A group named \"%s\" is already part of this GOptionContext",
532 context->groups = g_list_append (context->groups, group);
536 * g_option_context_set_main_group:
537 * @context: a #GOptionContext
538 * @group: the group to set as main group
540 * Sets a #GOptionGroup as main group of the @context.
541 * This has the same effect as calling g_option_context_add_group(),
542 * the only difference is that the options in the main group are
543 * treated differently when generating <option>--help</option> output.
548 g_option_context_set_main_group (GOptionContext *context,
551 g_return_if_fail (context != NULL);
552 g_return_if_fail (group != NULL);
554 if (context->main_group)
556 g_warning ("This GOptionContext already has a main group");
561 context->main_group = group;
565 * g_option_context_get_main_group:
566 * @context: a #GOptionContext
568 * Returns a pointer to the main group of @context.
570 * Return value: the main group of @context, or %NULL if @context doesn't
571 * have a main group. Note that group belongs to @context and should
572 * not be modified or freed.
577 g_option_context_get_main_group (GOptionContext *context)
579 g_return_val_if_fail (context != NULL, NULL);
581 return context->main_group;
585 * g_option_context_add_main_entries:
586 * @context: a #GOptionContext
587 * @entries: a %NULL-terminated array of #GOptionEntry<!-- -->s
588 * @translation_domain: (allow-none): a translation domain to use for translating
589 * the <option>--help</option> output for the options in @entries
590 * with gettext(), or %NULL
592 * A convenience function which creates a main group if it doesn't
593 * exist, adds the @entries to it and sets the translation domain.
598 g_option_context_add_main_entries (GOptionContext *context,
599 const GOptionEntry *entries,
600 const gchar *translation_domain)
602 g_return_if_fail (entries != NULL);
604 if (!context->main_group)
605 context->main_group = g_option_group_new (NULL, NULL, NULL, NULL, NULL);
607 g_option_group_add_entries (context->main_group, entries);
608 g_option_group_set_translation_domain (context->main_group, translation_domain);
612 calculate_max_length (GOptionGroup *group,
616 gint i, len, max_length;
617 const gchar *long_name;
621 for (i = 0; i < group->n_entries; i++)
623 entry = &group->entries[i];
625 if (entry->flags & G_OPTION_FLAG_HIDDEN)
628 long_name = g_hash_table_lookup (aliases, &entry->long_name);
630 long_name = entry->long_name;
631 len = _g_utf8_strwidth (long_name);
633 if (entry->short_name)
636 if (!NO_ARG (entry) && entry->arg_description)
637 len += 1 + _g_utf8_strwidth (TRANSLATE (group, entry->arg_description));
639 max_length = MAX (max_length, len);
646 print_entry (GOptionGroup *group,
648 const GOptionEntry *entry,
653 const gchar *long_name;
655 if (entry->flags & G_OPTION_FLAG_HIDDEN)
658 if (entry->long_name[0] == 0)
661 long_name = g_hash_table_lookup (aliases, &entry->long_name);
663 long_name = entry->long_name;
665 str = g_string_new (NULL);
667 if (entry->short_name)
668 g_string_append_printf (str, " -%c, --%s", entry->short_name, long_name);
670 g_string_append_printf (str, " --%s", long_name);
672 if (entry->arg_description)
673 g_string_append_printf (str, "=%s", TRANSLATE (group, entry->arg_description));
675 g_string_append_printf (string, "%s%*s %s\n", str->str,
676 (int) (max_length + 4 - _g_utf8_strwidth (str->str)), "",
677 entry->description ? TRANSLATE (group, entry->description) : "");
678 g_string_free (str, TRUE);
682 group_has_visible_entries (GOptionContext *context,
684 gboolean main_entries)
686 GOptionFlags reject_filter = G_OPTION_FLAG_HIDDEN;
689 gboolean main_group = group == context->main_group;
692 reject_filter |= G_OPTION_FLAG_IN_MAIN;
694 for (i = 0, l = (group ? group->n_entries : 0); i < l; i++)
696 entry = &group->entries[i];
698 if (main_entries && !main_group && !(entry->flags & G_OPTION_FLAG_IN_MAIN))
700 if (entry->long_name[0] == 0) /* ignore rest entry */
702 if (!(entry->flags & reject_filter))
710 group_list_has_visible_entries (GOptionContext *context,
712 gboolean main_entries)
716 if (group_has_visible_entries (context, group_list->data, main_entries))
719 group_list = group_list->next;
726 context_has_h_entry (GOptionContext *context)
731 if (context->main_group)
733 for (i = 0; i < context->main_group->n_entries; i++)
735 if (context->main_group->entries[i].short_name == 'h')
740 for (list = context->groups; list != NULL; list = g_list_next (list))
744 group = (GOptionGroup*)list->data;
745 for (i = 0; i < group->n_entries; i++)
747 if (group->entries[i].short_name == 'h')
755 * g_option_context_get_help:
756 * @context: a #GOptionContext
757 * @main_help: if %TRUE, only include the main group
758 * @group: (allow-none): the #GOptionGroup to create help for, or %NULL
760 * Returns a formatted, translated help text for the given context.
761 * To obtain the text produced by <option>--help</option>, call
762 * <literal>g_option_context_get_help (context, TRUE, NULL)</literal>.
763 * To obtain the text produced by <option>--help-all</option>, call
764 * <literal>g_option_context_get_help (context, FALSE, NULL)</literal>.
765 * To obtain the help text for an option group, call
766 * <literal>g_option_context_get_help (context, FALSE, group)</literal>.
768 * Returns: A newly allocated string containing the help text
773 g_option_context_get_help (GOptionContext *context,
778 gint max_length = 0, len;
781 GHashTable *shadow_map;
784 const gchar *rest_description;
788 string = g_string_sized_new (1024);
790 rest_description = NULL;
791 if (context->main_group)
794 for (i = 0; i < context->main_group->n_entries; i++)
796 entry = &context->main_group->entries[i];
797 if (entry->long_name[0] == 0)
799 rest_description = TRANSLATE (context->main_group, entry->arg_description);
805 g_string_append_printf (string, "%s\n %s %s",
806 _("Usage:"), g_get_prgname(), _("[OPTION...]"));
808 if (rest_description)
810 g_string_append (string, " ");
811 g_string_append (string, rest_description);
814 if (context->parameter_string)
816 g_string_append (string, " ");
817 g_string_append (string, TRANSLATE (context, context->parameter_string));
820 g_string_append (string, "\n\n");
822 if (context->summary)
824 g_string_append (string, TRANSLATE (context, context->summary));
825 g_string_append (string, "\n\n");
828 memset (seen, 0, sizeof (gboolean) * 256);
829 shadow_map = g_hash_table_new (g_str_hash, g_str_equal);
830 aliases = g_hash_table_new_full (NULL, NULL, NULL, g_free);
832 if (context->main_group)
834 for (i = 0; i < context->main_group->n_entries; i++)
836 entry = &context->main_group->entries[i];
837 g_hash_table_insert (shadow_map,
838 (gpointer)entry->long_name,
841 if (seen[(guchar)entry->short_name])
842 entry->short_name = 0;
844 seen[(guchar)entry->short_name] = TRUE;
848 list = context->groups;
851 GOptionGroup *g = list->data;
852 for (i = 0; i < g->n_entries; i++)
854 entry = &g->entries[i];
855 if (g_hash_table_lookup (shadow_map, entry->long_name) &&
856 !(entry->flags & G_OPTION_FLAG_NOALIAS))
858 g_hash_table_insert (aliases, &entry->long_name,
859 g_strdup_printf ("%s-%s", g->name, entry->long_name));
862 g_hash_table_insert (shadow_map, (gpointer)entry->long_name, entry);
864 if (seen[(guchar)entry->short_name] &&
865 !(entry->flags & G_OPTION_FLAG_NOALIAS))
866 entry->short_name = 0;
868 seen[(guchar)entry->short_name] = TRUE;
873 g_hash_table_destroy (shadow_map);
875 list = context->groups;
877 if (context->help_enabled)
879 max_length = _g_utf8_strwidth ("-?, --help");
883 len = _g_utf8_strwidth ("--help-all");
884 max_length = MAX (max_length, len);
888 if (context->main_group)
890 len = calculate_max_length (context->main_group, aliases);
891 max_length = MAX (max_length, len);
896 GOptionGroup *g = list->data;
898 if (context->help_enabled)
900 /* First, we check the --help-<groupname> options */
901 len = _g_utf8_strwidth ("--help-") + _g_utf8_strwidth (g->name);
902 max_length = MAX (max_length, len);
905 /* Then we go through the entries */
906 len = calculate_max_length (g, aliases);
907 max_length = MAX (max_length, len);
912 /* Add a bit of padding */
915 if (!group && context->help_enabled)
917 list = context->groups;
919 token = context_has_h_entry (context) ? '?' : 'h';
921 g_string_append_printf (string, "%s\n -%c, --%-*s %s\n",
922 _("Help Options:"), token, max_length - 4, "help",
923 _("Show help options"));
925 /* We only want --help-all when there are groups */
927 g_string_append_printf (string, " --%-*s %s\n",
928 max_length, "help-all",
929 _("Show all help options"));
933 GOptionGroup *g = list->data;
935 if (group_has_visible_entries (context, g, FALSE))
936 g_string_append_printf (string, " --help-%-*s %s\n",
937 max_length - 5, g->name,
938 TRANSLATE (g, g->help_description));
943 g_string_append (string, "\n");
948 /* Print a certain group */
950 if (group_has_visible_entries (context, group, FALSE))
952 g_string_append (string, TRANSLATE (group, group->description));
953 g_string_append (string, "\n");
954 for (i = 0; i < group->n_entries; i++)
955 print_entry (group, max_length, &group->entries[i], string, aliases);
956 g_string_append (string, "\n");
961 /* Print all groups */
963 list = context->groups;
967 GOptionGroup *g = list->data;
969 if (group_has_visible_entries (context, g, FALSE))
971 g_string_append (string, g->description);
972 g_string_append (string, "\n");
973 for (i = 0; i < g->n_entries; i++)
974 if (!(g->entries[i].flags & G_OPTION_FLAG_IN_MAIN))
975 print_entry (g, max_length, &g->entries[i], string, aliases);
977 g_string_append (string, "\n");
984 /* Print application options if --help or --help-all has been specified */
985 if ((main_help || !group) &&
986 (group_has_visible_entries (context, context->main_group, TRUE) ||
987 group_list_has_visible_entries (context, context->groups, TRUE)))
989 list = context->groups;
991 g_string_append (string, _("Application Options:"));
992 g_string_append (string, "\n");
993 if (context->main_group)
994 for (i = 0; i < context->main_group->n_entries; i++)
995 print_entry (context->main_group, max_length,
996 &context->main_group->entries[i], string, aliases);
1000 GOptionGroup *g = list->data;
1002 /* Print main entries from other groups */
1003 for (i = 0; i < g->n_entries; i++)
1004 if (g->entries[i].flags & G_OPTION_FLAG_IN_MAIN)
1005 print_entry (g, max_length, &g->entries[i], string, aliases);
1010 g_string_append (string, "\n");
1013 if (context->description)
1015 g_string_append (string, TRANSLATE (context, context->description));
1016 g_string_append (string, "\n");
1019 g_hash_table_destroy (aliases);
1021 return g_string_free (string, FALSE);
1026 print_help (GOptionContext *context,
1028 GOptionGroup *group)
1032 help = g_option_context_get_help (context, main_help, group);
1033 g_print ("%s", help);
1040 parse_int (const gchar *arg_name,
1049 tmp = strtol (arg, &end, 0);
1051 if (*arg == '\0' || *end != '\0')
1054 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1055 _("Cannot parse integer value '%s' for %s"),
1061 if (*result != tmp || errno == ERANGE)
1064 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1065 _("Integer value '%s' for %s out of range"),
1075 parse_double (const gchar *arg_name,
1084 tmp = g_strtod (arg, &end);
1086 if (*arg == '\0' || *end != '\0')
1089 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1090 _("Cannot parse double value '%s' for %s"),
1094 if (errno == ERANGE)
1097 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1098 _("Double value '%s' for %s out of range"),
1110 parse_int64 (const gchar *arg_name,
1119 tmp = g_ascii_strtoll (arg, &end, 0);
1121 if (*arg == '\0' || *end != '\0')
1124 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1125 _("Cannot parse integer value '%s' for %s"),
1129 if (errno == ERANGE)
1132 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1133 _("Integer value '%s' for %s out of range"),
1145 get_change (GOptionContext *context,
1146 GOptionArg arg_type,
1150 Change *change = NULL;
1152 for (list = context->changes; list != NULL; list = list->next)
1154 change = list->data;
1156 if (change->arg_data == arg_data)
1160 change = g_new0 (Change, 1);
1161 change->arg_type = arg_type;
1162 change->arg_data = arg_data;
1164 context->changes = g_list_prepend (context->changes, change);
1172 add_pending_null (GOptionContext *context,
1178 n = g_new0 (PendingNull, 1);
1182 context->pending_nulls = g_list_prepend (context->pending_nulls, n);
1186 parse_arg (GOptionContext *context,
1187 GOptionGroup *group,
1188 GOptionEntry *entry,
1190 const gchar *option_name,
1196 g_assert (value || OPTIONAL_ARG (entry) || NO_ARG (entry));
1200 case G_OPTION_ARG_NONE:
1202 change = get_change (context, G_OPTION_ARG_NONE,
1205 *(gboolean *)entry->arg_data = !(entry->flags & G_OPTION_FLAG_REVERSE);
1208 case G_OPTION_ARG_STRING:
1213 if (!context->strv_mode)
1214 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1216 data = g_strdup (value);
1218 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1224 change = get_change (context, G_OPTION_ARG_STRING,
1226 g_free (change->allocated.str);
1228 change->prev.str = *(gchar **)entry->arg_data;
1229 change->allocated.str = data;
1231 *(gchar **)entry->arg_data = data;
1234 case G_OPTION_ARG_STRING_ARRAY:
1239 if (!context->strv_mode)
1240 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1242 data = g_strdup (value);
1244 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1250 change = get_change (context, G_OPTION_ARG_STRING_ARRAY,
1253 if (change->allocated.array.len == 0)
1255 change->prev.array = *(gchar ***)entry->arg_data;
1256 change->allocated.array.data = g_new (gchar *, 2);
1259 change->allocated.array.data =
1260 g_renew (gchar *, change->allocated.array.data,
1261 change->allocated.array.len + 2);
1263 change->allocated.array.data[change->allocated.array.len] = data;
1264 change->allocated.array.data[change->allocated.array.len + 1] = NULL;
1266 change->allocated.array.len ++;
1268 *(gchar ***)entry->arg_data = change->allocated.array.data;
1273 case G_OPTION_ARG_FILENAME:
1278 if (!context->strv_mode)
1279 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1281 data = g_strdup (value);
1286 data = g_strdup (value);
1288 change = get_change (context, G_OPTION_ARG_FILENAME,
1290 g_free (change->allocated.str);
1292 change->prev.str = *(gchar **)entry->arg_data;
1293 change->allocated.str = data;
1295 *(gchar **)entry->arg_data = data;
1299 case G_OPTION_ARG_FILENAME_ARRAY:
1304 if (!context->strv_mode)
1305 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1307 data = g_strdup (value);
1312 data = g_strdup (value);
1314 change = get_change (context, G_OPTION_ARG_STRING_ARRAY,
1317 if (change->allocated.array.len == 0)
1319 change->prev.array = *(gchar ***)entry->arg_data;
1320 change->allocated.array.data = g_new (gchar *, 2);
1323 change->allocated.array.data =
1324 g_renew (gchar *, change->allocated.array.data,
1325 change->allocated.array.len + 2);
1327 change->allocated.array.data[change->allocated.array.len] = data;
1328 change->allocated.array.data[change->allocated.array.len + 1] = NULL;
1330 change->allocated.array.len ++;
1332 *(gchar ***)entry->arg_data = change->allocated.array.data;
1337 case G_OPTION_ARG_INT:
1341 if (!parse_int (option_name, value,
1346 change = get_change (context, G_OPTION_ARG_INT,
1348 change->prev.integer = *(gint *)entry->arg_data;
1349 *(gint *)entry->arg_data = data;
1352 case G_OPTION_ARG_CALLBACK:
1357 if (!value && entry->flags & G_OPTION_FLAG_OPTIONAL_ARG)
1359 else if (entry->flags & G_OPTION_FLAG_NO_ARG)
1361 else if (entry->flags & G_OPTION_FLAG_FILENAME)
1364 if (!context->strv_mode)
1365 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1367 data = g_strdup (value);
1369 data = g_strdup (value);
1373 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1375 if (!(entry->flags & (G_OPTION_FLAG_NO_ARG|G_OPTION_FLAG_OPTIONAL_ARG)) &&
1379 retval = (* (GOptionArgFunc) entry->arg_data) (option_name, data, group->user_data, error);
1381 if (!retval && error != NULL && *error == NULL)
1383 G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
1384 _("Error parsing option %s"), option_name);
1392 case G_OPTION_ARG_DOUBLE:
1396 if (!parse_double (option_name, value,
1403 change = get_change (context, G_OPTION_ARG_DOUBLE,
1405 change->prev.dbl = *(gdouble *)entry->arg_data;
1406 *(gdouble *)entry->arg_data = data;
1409 case G_OPTION_ARG_INT64:
1413 if (!parse_int64 (option_name, value,
1420 change = get_change (context, G_OPTION_ARG_INT64,
1422 change->prev.int64 = *(gint64 *)entry->arg_data;
1423 *(gint64 *)entry->arg_data = data;
1427 g_assert_not_reached ();
1434 parse_short_option (GOptionContext *context,
1435 GOptionGroup *group,
1446 for (j = 0; j < group->n_entries; j++)
1448 if (arg == group->entries[j].short_name)
1451 gchar *value = NULL;
1453 option_name = g_strdup_printf ("-%c", group->entries[j].short_name);
1455 if (NO_ARG (&group->entries[j]))
1462 G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
1463 _("Error parsing option %s"), option_name);
1464 g_free (option_name);
1468 if (idx < *argc - 1)
1470 if (!OPTIONAL_ARG (&group->entries[j]))
1472 value = (*argv)[idx + 1];
1473 add_pending_null (context, &((*argv)[idx + 1]), NULL);
1478 if ((*argv)[idx + 1][0] == '-')
1482 value = (*argv)[idx + 1];
1483 add_pending_null (context, &((*argv)[idx + 1]), NULL);
1488 else if (idx >= *argc - 1 && OPTIONAL_ARG (&group->entries[j]))
1493 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1494 _("Missing argument for %s"), option_name);
1495 g_free (option_name);
1500 if (!parse_arg (context, group, &group->entries[j],
1501 value, option_name, error))
1503 g_free (option_name);
1507 g_free (option_name);
1516 parse_long_option (GOptionContext *context,
1517 GOptionGroup *group,
1528 for (j = 0; j < group->n_entries; j++)
1533 if (aliased && (group->entries[j].flags & G_OPTION_FLAG_NOALIAS))
1536 if (NO_ARG (&group->entries[j]) &&
1537 strcmp (arg, group->entries[j].long_name) == 0)
1542 option_name = g_strconcat ("--", group->entries[j].long_name, NULL);
1543 retval = parse_arg (context, group, &group->entries[j],
1544 NULL, option_name, error);
1545 g_free (option_name);
1547 add_pending_null (context, &((*argv)[*idx]), NULL);
1554 gint len = strlen (group->entries[j].long_name);
1556 if (strncmp (arg, group->entries[j].long_name, len) == 0 &&
1557 (arg[len] == '=' || arg[len] == 0))
1559 gchar *value = NULL;
1562 add_pending_null (context, &((*argv)[*idx]), NULL);
1563 option_name = g_strconcat ("--", group->entries[j].long_name, NULL);
1565 if (arg[len] == '=')
1566 value = arg + len + 1;
1567 else if (*idx < *argc - 1)
1569 if (!OPTIONAL_ARG (&group->entries[j]))
1571 value = (*argv)[*idx + 1];
1572 add_pending_null (context, &((*argv)[*idx + 1]), NULL);
1577 if ((*argv)[*idx + 1][0] == '-')
1580 retval = parse_arg (context, group, &group->entries[j],
1581 NULL, option_name, error);
1583 g_free (option_name);
1588 value = (*argv)[*idx + 1];
1589 add_pending_null (context, &((*argv)[*idx + 1]), NULL);
1594 else if (*idx >= *argc - 1 && OPTIONAL_ARG (&group->entries[j]))
1597 retval = parse_arg (context, group, &group->entries[j],
1598 NULL, option_name, error);
1600 g_free (option_name);
1606 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1607 _("Missing argument for %s"), option_name);
1608 g_free (option_name);
1612 if (!parse_arg (context, group, &group->entries[j],
1613 value, option_name, error))
1615 g_free (option_name);
1619 g_free (option_name);
1629 parse_remaining_arg (GOptionContext *context,
1630 GOptionGroup *group,
1639 for (j = 0; j < group->n_entries; j++)
1644 if (group->entries[j].long_name[0])
1647 g_return_val_if_fail (group->entries[j].arg == G_OPTION_ARG_CALLBACK ||
1648 group->entries[j].arg == G_OPTION_ARG_STRING_ARRAY ||
1649 group->entries[j].arg == G_OPTION_ARG_FILENAME_ARRAY, FALSE);
1651 add_pending_null (context, &((*argv)[*idx]), NULL);
1653 if (!parse_arg (context, group, &group->entries[j], (*argv)[*idx], "", error))
1664 free_changes_list (GOptionContext *context,
1669 for (list = context->changes; list != NULL; list = list->next)
1671 Change *change = list->data;
1675 switch (change->arg_type)
1677 case G_OPTION_ARG_NONE:
1678 *(gboolean *)change->arg_data = change->prev.bool;
1680 case G_OPTION_ARG_INT:
1681 *(gint *)change->arg_data = change->prev.integer;
1683 case G_OPTION_ARG_STRING:
1684 case G_OPTION_ARG_FILENAME:
1685 g_free (change->allocated.str);
1686 *(gchar **)change->arg_data = change->prev.str;
1688 case G_OPTION_ARG_STRING_ARRAY:
1689 case G_OPTION_ARG_FILENAME_ARRAY:
1690 g_strfreev (change->allocated.array.data);
1691 *(gchar ***)change->arg_data = change->prev.array;
1693 case G_OPTION_ARG_DOUBLE:
1694 *(gdouble *)change->arg_data = change->prev.dbl;
1696 case G_OPTION_ARG_INT64:
1697 *(gint64 *)change->arg_data = change->prev.int64;
1700 g_assert_not_reached ();
1707 g_list_free (context->changes);
1708 context->changes = NULL;
1712 free_pending_nulls (GOptionContext *context,
1713 gboolean perform_nulls)
1717 for (list = context->pending_nulls; list != NULL; list = list->next)
1719 PendingNull *n = list->data;
1723 if (context->strv_mode)
1728 /* Copy back the short options */
1730 strcpy (*n->ptr + 1, n->value);
1740 g_list_free (context->pending_nulls);
1741 context->pending_nulls = NULL;
1744 /* Use a platform-specific mechanism to look up the first argument to
1745 * the current process.
1746 * Note if you implement this for other platforms, also add it to
1747 * tests/option-argv0.c
1750 platform_get_argv0 (void)
1757 if (!g_file_get_contents ("/proc/self/cmdline",
1762 /* Sanity check for a NUL terminator. */
1763 if (!memchr (cmdline, 0, len))
1765 /* We could just return cmdline, but I think it's better
1766 * to hold on to a smaller malloc block; the arguments
1769 base_arg0 = g_path_get_basename (cmdline);
1772 #elif defined __OpenBSD__
1773 char **cmdline = NULL;
1775 gsize len = PATH_MAX;
1777 int mib[] = { CTL_KERN, KERN_PROC_ARGS, getpid(), KERN_PROC_ARGV };
1779 cmdline = (char **) realloc (cmdline, len);
1781 if (sysctl (mib, G_N_ELEMENTS (mib), cmdline, &len, NULL, 0) == -1)
1787 /* We could just return cmdline, but I think it's better
1788 * to hold on to a smaller malloc block; the arguments
1791 base_arg0 = g_path_get_basename (*cmdline);
1800 * g_option_context_parse:
1801 * @context: a #GOptionContext
1802 * @argc: (inout) (allow-none): a pointer to the number of command line arguments
1803 * @argv: (inout) (array length=argc) (allow-none): a pointer to the array of command line arguments
1804 * @error: a return location for errors
1806 * Parses the command line arguments, recognizing options
1807 * which have been added to @context. A side-effect of
1808 * calling this function is that g_set_prgname() will be
1811 * If the parsing is successful, any parsed arguments are
1812 * removed from the array and @argc and @argv are updated
1813 * accordingly. A '--' option is stripped from @argv
1814 * unless there are unparsed options before and after it,
1815 * or some of the options after it start with '-'. In case
1816 * of an error, @argc and @argv are left unmodified.
1818 * If automatic <option>--help</option> support is enabled
1819 * (see g_option_context_set_help_enabled()), and the
1820 * @argv array contains one of the recognized help options,
1821 * this function will produce help output to stdout and
1822 * call <literal>exit (0)</literal>.
1824 * Note that function depends on the
1825 * <link linkend="setlocale">current locale</link> for
1826 * automatic character set conversion of string and filename
1829 * Return value: %TRUE if the parsing was successful,
1830 * %FALSE if an error occurred
1835 g_option_context_parse (GOptionContext *context,
1843 /* Set program name */
1844 if (!g_get_prgname())
1848 if (argc && argv && *argc)
1849 prgname = g_path_get_basename ((*argv)[0]);
1851 prgname = platform_get_argv0 ();
1854 g_set_prgname (prgname);
1856 g_set_prgname ("<unknown>");
1861 /* Call pre-parse hooks */
1862 list = context->groups;
1865 GOptionGroup *group = list->data;
1867 if (group->pre_parse_func)
1869 if (!(* group->pre_parse_func) (context, group,
1870 group->user_data, error))
1877 if (context->main_group && context->main_group->pre_parse_func)
1879 if (!(* context->main_group->pre_parse_func) (context, context->main_group,
1880 context->main_group->user_data, error))
1886 gboolean stop_parsing = FALSE;
1887 gboolean has_unknown = FALSE;
1888 gint separator_pos = 0;
1890 for (i = 1; i < *argc; i++)
1893 gboolean parsed = FALSE;
1895 if ((*argv)[i][0] == '-' && (*argv)[i][1] != '\0' && !stop_parsing)
1897 if ((*argv)[i][1] == '-')
1901 arg = (*argv)[i] + 2;
1903 /* '--' terminates list of arguments */
1907 stop_parsing = TRUE;
1911 /* Handle help options */
1912 if (context->help_enabled)
1914 if (strcmp (arg, "help") == 0)
1915 print_help (context, TRUE, NULL);
1916 else if (strcmp (arg, "help-all") == 0)
1917 print_help (context, FALSE, NULL);
1918 else if (strncmp (arg, "help-", 5) == 0)
1920 list = context->groups;
1924 GOptionGroup *group = list->data;
1926 if (strcmp (arg + 5, group->name) == 0)
1927 print_help (context, FALSE, group);
1934 if (context->main_group &&
1935 !parse_long_option (context, context->main_group, &i, arg,
1936 FALSE, argc, argv, error, &parsed))
1942 /* Try the groups */
1943 list = context->groups;
1946 GOptionGroup *group = list->data;
1948 if (!parse_long_option (context, group, &i, arg,
1949 FALSE, argc, argv, error, &parsed))
1961 /* Now look for --<group>-<option> */
1962 dash = strchr (arg, '-');
1965 /* Try the groups */
1966 list = context->groups;
1969 GOptionGroup *group = list->data;
1971 if (strncmp (group->name, arg, dash - arg) == 0)
1973 if (!parse_long_option (context, group, &i, dash + 1,
1974 TRUE, argc, argv, error, &parsed))
1985 if (context->ignore_unknown)
1989 { /* short option */
1990 gint new_i = i, arg_length;
1991 gboolean *nulled_out = NULL;
1992 gboolean has_h_entry = context_has_h_entry (context);
1993 arg = (*argv)[i] + 1;
1994 arg_length = strlen (arg);
1995 nulled_out = g_newa (gboolean, arg_length);
1996 memset (nulled_out, 0, arg_length * sizeof (gboolean));
1997 for (j = 0; j < arg_length; j++)
1999 if (context->help_enabled && (arg[j] == '?' ||
2000 (arg[j] == 'h' && !has_h_entry)))
2001 print_help (context, TRUE, NULL);
2003 if (context->main_group &&
2004 !parse_short_option (context, context->main_group,
2006 argc, argv, error, &parsed))
2010 /* Try the groups */
2011 list = context->groups;
2014 GOptionGroup *group = list->data;
2015 if (!parse_short_option (context, group, i, &new_i, arg[j],
2016 argc, argv, error, &parsed))
2024 if (context->ignore_unknown && parsed)
2025 nulled_out[j] = TRUE;
2026 else if (context->ignore_unknown)
2030 /* !context->ignore_unknown && parsed */
2032 if (context->ignore_unknown)
2034 gchar *new_arg = NULL;
2036 for (j = 0; j < arg_length; j++)
2041 new_arg = g_malloc (arg_length + 1);
2042 new_arg[arg_index++] = arg[j];
2046 new_arg[arg_index] = '\0';
2047 add_pending_null (context, &((*argv)[i]), new_arg);
2051 add_pending_null (context, &((*argv)[i]), NULL);
2059 if (!parsed && !context->ignore_unknown)
2062 G_OPTION_ERROR, G_OPTION_ERROR_UNKNOWN_OPTION,
2063 _("Unknown option %s"), (*argv)[i]);
2069 /* Collect remaining args */
2070 if (context->main_group &&
2071 !parse_remaining_arg (context, context->main_group, &i,
2072 argc, argv, error, &parsed))
2075 if (!parsed && (has_unknown || (*argv)[i][0] == '-'))
2080 if (separator_pos > 0)
2081 add_pending_null (context, &((*argv)[separator_pos]), NULL);
2085 /* Call post-parse hooks */
2086 list = context->groups;
2089 GOptionGroup *group = list->data;
2091 if (group->post_parse_func)
2093 if (!(* group->post_parse_func) (context, group,
2094 group->user_data, error))
2101 if (context->main_group && context->main_group->post_parse_func)
2103 if (!(* context->main_group->post_parse_func) (context, context->main_group,
2104 context->main_group->user_data, error))
2110 free_pending_nulls (context, TRUE);
2112 for (i = 1; i < *argc; i++)
2114 for (k = i; k < *argc; k++)
2115 if ((*argv)[k] != NULL)
2121 for (j = i + k; j < *argc; j++)
2123 (*argv)[j-k] = (*argv)[j];
2135 /* Call error hooks */
2136 list = context->groups;
2139 GOptionGroup *group = list->data;
2141 if (group->error_func)
2142 (* group->error_func) (context, group,
2143 group->user_data, error);
2148 if (context->main_group && context->main_group->error_func)
2149 (* context->main_group->error_func) (context, context->main_group,
2150 context->main_group->user_data, error);
2152 free_changes_list (context, TRUE);
2153 free_pending_nulls (context, FALSE);
2159 * g_option_group_new:
2160 * @name: the name for the option group, this is used to provide
2161 * help for the options in this group with <option>--help-</option>@name
2162 * @description: a description for this group to be shown in
2163 * <option>--help</option>. This string is translated using the translation
2164 * domain or translation function of the group
2165 * @help_description: a description for the <option>--help-</option>@name option.
2166 * This string is translated using the translation domain or translation function
2168 * @user_data: (allow-none): user data that will be passed to the pre- and post-parse hooks,
2169 * the error hook and to callbacks of %G_OPTION_ARG_CALLBACK options, or %NULL
2170 * @destroy: (allow-none): a function that will be called to free @user_data, or %NULL
2172 * Creates a new #GOptionGroup.
2174 * Return value: a newly created option group. It should be added
2175 * to a #GOptionContext or freed with g_option_group_free().
2180 g_option_group_new (const gchar *name,
2181 const gchar *description,
2182 const gchar *help_description,
2184 GDestroyNotify destroy)
2187 GOptionGroup *group;
2189 group = g_new0 (GOptionGroup, 1);
2190 group->name = g_strdup (name);
2191 group->description = g_strdup (description);
2192 group->help_description = g_strdup (help_description);
2193 group->user_data = user_data;
2194 group->destroy_notify = destroy;
2201 * g_option_group_free:
2202 * @group: a #GOptionGroup
2204 * Frees a #GOptionGroup. Note that you must <emphasis>not</emphasis>
2205 * free groups which have been added to a #GOptionContext.
2210 g_option_group_free (GOptionGroup *group)
2212 g_return_if_fail (group != NULL);
2214 g_free (group->name);
2215 g_free (group->description);
2216 g_free (group->help_description);
2218 g_free (group->entries);
2220 if (group->destroy_notify)
2221 (* group->destroy_notify) (group->user_data);
2223 if (group->translate_notify)
2224 (* group->translate_notify) (group->translate_data);
2231 * g_option_group_add_entries:
2232 * @group: a #GOptionGroup
2233 * @entries: a %NULL-terminated array of #GOptionEntry<!-- -->s
2235 * Adds the options specified in @entries to @group.
2240 g_option_group_add_entries (GOptionGroup *group,
2241 const GOptionEntry *entries)
2245 g_return_if_fail (entries != NULL);
2247 for (n_entries = 0; entries[n_entries].long_name != NULL; n_entries++) ;
2249 group->entries = g_renew (GOptionEntry, group->entries, group->n_entries + n_entries);
2251 memcpy (group->entries + group->n_entries, entries, sizeof (GOptionEntry) * n_entries);
2253 for (i = group->n_entries; i < group->n_entries + n_entries; i++)
2255 gchar c = group->entries[i].short_name;
2257 if (c == '-' || (c != 0 && !g_ascii_isprint (c)))
2259 g_warning (G_STRLOC ": ignoring invalid short option '%c' (%d) in entry %s:%s",
2260 c, c, group->name, group->entries[i].long_name);
2261 group->entries[i].short_name = '\0';
2264 if (group->entries[i].arg != G_OPTION_ARG_NONE &&
2265 (group->entries[i].flags & G_OPTION_FLAG_REVERSE) != 0)
2267 g_warning (G_STRLOC ": ignoring reverse flag on option of arg-type %d in entry %s:%s",
2268 group->entries[i].arg, group->name, group->entries[i].long_name);
2270 group->entries[i].flags &= ~G_OPTION_FLAG_REVERSE;
2273 if (group->entries[i].arg != G_OPTION_ARG_CALLBACK &&
2274 (group->entries[i].flags & (G_OPTION_FLAG_NO_ARG|G_OPTION_FLAG_OPTIONAL_ARG|G_OPTION_FLAG_FILENAME)) != 0)
2276 g_warning (G_STRLOC ": ignoring no-arg, optional-arg or filename flags (%d) on option of arg-type %d in entry %s:%s",
2277 group->entries[i].flags, group->entries[i].arg, group->name, group->entries[i].long_name);
2279 group->entries[i].flags &= ~(G_OPTION_FLAG_NO_ARG|G_OPTION_FLAG_OPTIONAL_ARG|G_OPTION_FLAG_FILENAME);
2283 group->n_entries += n_entries;
2287 * g_option_group_set_parse_hooks:
2288 * @group: a #GOptionGroup
2289 * @pre_parse_func: (allow-none): a function to call before parsing, or %NULL
2290 * @post_parse_func: (allow-none): a function to call after parsing, or %NULL
2292 * Associates two functions with @group which will be called
2293 * from g_option_context_parse() before the first option is parsed
2294 * and after the last option has been parsed, respectively.
2296 * Note that the user data to be passed to @pre_parse_func and
2297 * @post_parse_func can be specified when constructing the group
2298 * with g_option_group_new().
2303 g_option_group_set_parse_hooks (GOptionGroup *group,
2304 GOptionParseFunc pre_parse_func,
2305 GOptionParseFunc post_parse_func)
2307 g_return_if_fail (group != NULL);
2309 group->pre_parse_func = pre_parse_func;
2310 group->post_parse_func = post_parse_func;
2314 * g_option_group_set_error_hook:
2315 * @group: a #GOptionGroup
2316 * @error_func: a function to call when an error occurs
2318 * Associates a function with @group which will be called
2319 * from g_option_context_parse() when an error occurs.
2321 * Note that the user data to be passed to @error_func can be
2322 * specified when constructing the group with g_option_group_new().
2327 g_option_group_set_error_hook (GOptionGroup *group,
2328 GOptionErrorFunc error_func)
2330 g_return_if_fail (group != NULL);
2332 group->error_func = error_func;
2337 * g_option_group_set_translate_func:
2338 * @group: a #GOptionGroup
2339 * @func: (allow-none): the #GTranslateFunc, or %NULL
2340 * @data: (allow-none): user data to pass to @func, or %NULL
2341 * @destroy_notify: (allow-none): a function which gets called to free @data, or %NULL
2343 * Sets the function which is used to translate user-visible
2344 * strings, for <option>--help</option> output. Different
2345 * groups can use different #GTranslateFunc<!-- -->s. If @func
2346 * is %NULL, strings are not translated.
2348 * If you are using gettext(), you only need to set the translation
2349 * domain, see g_option_group_set_translation_domain().
2354 g_option_group_set_translate_func (GOptionGroup *group,
2355 GTranslateFunc func,
2357 GDestroyNotify destroy_notify)
2359 g_return_if_fail (group != NULL);
2361 if (group->translate_notify)
2362 group->translate_notify (group->translate_data);
2364 group->translate_func = func;
2365 group->translate_data = data;
2366 group->translate_notify = destroy_notify;
2369 static const gchar *
2370 dgettext_swapped (const gchar *msgid,
2371 const gchar *domainname)
2373 return g_dgettext (domainname, msgid);
2377 * g_option_group_set_translation_domain:
2378 * @group: a #GOptionGroup
2379 * @domain: the domain to use
2381 * A convenience function to use gettext() for translating
2382 * user-visible strings.
2387 g_option_group_set_translation_domain (GOptionGroup *group,
2388 const gchar *domain)
2390 g_return_if_fail (group != NULL);
2392 g_option_group_set_translate_func (group,
2393 (GTranslateFunc)dgettext_swapped,
2399 * g_option_context_set_translate_func:
2400 * @context: a #GOptionContext
2401 * @func: (allow-none): the #GTranslateFunc, or %NULL
2402 * @data: (allow-none): user data to pass to @func, or %NULL
2403 * @destroy_notify: (allow-none): a function which gets called to free @data, or %NULL
2405 * Sets the function which is used to translate the contexts
2406 * user-visible strings, for <option>--help</option> output.
2407 * If @func is %NULL, strings are not translated.
2409 * Note that option groups have their own translation functions,
2410 * this function only affects the @parameter_string (see g_option_context_new()),
2411 * the summary (see g_option_context_set_summary()) and the description
2412 * (see g_option_context_set_description()).
2414 * If you are using gettext(), you only need to set the translation
2415 * domain, see g_option_context_set_translation_domain().
2420 g_option_context_set_translate_func (GOptionContext *context,
2421 GTranslateFunc func,
2423 GDestroyNotify destroy_notify)
2425 g_return_if_fail (context != NULL);
2427 if (context->translate_notify)
2428 context->translate_notify (context->translate_data);
2430 context->translate_func = func;
2431 context->translate_data = data;
2432 context->translate_notify = destroy_notify;
2436 * g_option_context_set_translation_domain:
2437 * @context: a #GOptionContext
2438 * @domain: the domain to use
2440 * A convenience function to use gettext() for translating
2441 * user-visible strings.
2446 g_option_context_set_translation_domain (GOptionContext *context,
2447 const gchar *domain)
2449 g_return_if_fail (context != NULL);
2451 g_option_context_set_translate_func (context,
2452 (GTranslateFunc)dgettext_swapped,
2458 * g_option_context_set_summary:
2459 * @context: a #GOptionContext
2460 * @summary: (allow-none): a string to be shown in <option>--help</option> output
2461 * before the list of options, or %NULL
2463 * Adds a string to be displayed in <option>--help</option> output
2464 * before the list of options. This is typically a summary of the
2465 * program functionality.
2467 * Note that the summary is translated (see
2468 * g_option_context_set_translate_func() and
2469 * g_option_context_set_translation_domain()).
2474 g_option_context_set_summary (GOptionContext *context,
2475 const gchar *summary)
2477 g_return_if_fail (context != NULL);
2479 g_free (context->summary);
2480 context->summary = g_strdup (summary);
2485 * g_option_context_get_summary:
2486 * @context: a #GOptionContext
2488 * Returns the summary. See g_option_context_set_summary().
2490 * Returns: the summary
2495 g_option_context_get_summary (GOptionContext *context)
2497 g_return_val_if_fail (context != NULL, NULL);
2499 return context->summary;
2503 * g_option_context_set_description:
2504 * @context: a #GOptionContext
2505 * @description: (allow-none): a string to be shown in <option>--help</option> output
2506 * after the list of options, or %NULL
2508 * Adds a string to be displayed in <option>--help</option> output
2509 * after the list of options. This text often includes a bug reporting
2512 * Note that the summary is translated (see
2513 * g_option_context_set_translate_func()).
2518 g_option_context_set_description (GOptionContext *context,
2519 const gchar *description)
2521 g_return_if_fail (context != NULL);
2523 g_free (context->description);
2524 context->description = g_strdup (description);
2529 * g_option_context_get_description:
2530 * @context: a #GOptionContext
2532 * Returns the description. See g_option_context_set_description().
2534 * Returns: the description
2539 g_option_context_get_description (GOptionContext *context)
2541 g_return_val_if_fail (context != NULL, NULL);
2543 return context->description;
2547 * g_option_context_parse_strv:
2548 * @context: a #GOptionContext
2549 * @arguments: (inout) (array null-terminated=1): a pointer to the
2550 * command line arguments (which must be in UTF-8 on Windows)
2551 * @error: a return location for errors
2553 * Parses the command line arguments.
2555 * This function is similar to g_option_context_parse() except that it
2556 * respects the normal memory rules when dealing with a strv instead of
2557 * assuming that the passed-in array is the argv of the main function.
2559 * In particular, strings that are removed from the arguments list will
2560 * be freed using g_free().
2562 * On Windows, the strings are expected to be in UTF-8. This is in
2563 * contrast to g_option_context_parse() which expects them to be in the
2564 * system codepage, which is how they are passed as @argv to main().
2565 * See g_win32_get_command_line() for a solution.
2567 * This function is useful if you are trying to use #GOptionContext with
2570 * Returns: %TRUE if the parsing was successful,
2571 * %FALSE if an error occurred
2576 g_option_context_parse_strv (GOptionContext *context,
2583 context->strv_mode = TRUE;
2584 argc = g_strv_length (*arguments);
2585 success = g_option_context_parse (context, &argc, arguments, error);
2586 context->strv_mode = FALSE;