contenttype: Improve test coverage
[glib.git] / glib / goption.c
blobf5372ffe2b7206366032bea3a39277d5c7856cca
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.
22 /**
23 * SECTION:option
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
34 * commandline parser
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>
65 * Usage:
66 * testtreemodel [OPTION...] - test tree model performance
68 * Help Options:
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 rand = 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, &rand, "Randomize the data", NULL },
111 * { NULL }
112 * };
114 * int
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);
126 * exit (1);
129 * /&ast; ... &ast;/
132 * </programlisting></informalexample>
135 #include "config.h"
137 #include <string.h>
138 #include <stdlib.h>
139 #include <stdio.h>
140 #include <errno.h>
142 #if defined __OpenBSD__
143 #include <sys/types.h>
144 #include <unistd.h>
145 #include <sys/param.h>
146 #include <sys/sysctl.h>
147 #endif
149 #include "goption.h"
151 #include "gprintf.h"
152 #include "glibintl.h"
154 #define TRANSLATE(group, str) (((group)->translate_func ? (* (group)->translate_func) ((str), (group)->translate_data) : (str)))
156 #define NO_ARG(entry) ((entry)->arg == G_OPTION_ARG_NONE || \
157 ((entry)->arg == G_OPTION_ARG_CALLBACK && \
158 ((entry)->flags & G_OPTION_FLAG_NO_ARG)))
160 #define OPTIONAL_ARG(entry) ((entry)->arg == G_OPTION_ARG_CALLBACK && \
161 (entry)->flags & G_OPTION_FLAG_OPTIONAL_ARG)
163 typedef struct
165 GOptionArg arg_type;
166 gpointer arg_data;
167 union
169 gboolean bool;
170 gint integer;
171 gchar *str;
172 gchar **array;
173 gdouble dbl;
174 gint64 int64;
175 } prev;
176 union
178 gchar *str;
179 struct
181 gint len;
182 gchar **data;
183 } array;
184 } allocated;
185 } Change;
187 typedef struct
189 gchar **ptr;
190 gchar *value;
191 } PendingNull;
193 struct _GOptionContext
195 GList *groups;
197 gchar *parameter_string;
198 gchar *summary;
199 gchar *description;
201 GTranslateFunc translate_func;
202 GDestroyNotify translate_notify;
203 gpointer translate_data;
205 guint help_enabled : 1;
206 guint ignore_unknown : 1;
208 GOptionGroup *main_group;
210 /* We keep a list of change so we can revert them */
211 GList *changes;
213 /* We also keep track of all argv elements
214 * that should be NULLed or modified.
216 GList *pending_nulls;
219 struct _GOptionGroup
221 gchar *name;
222 gchar *description;
223 gchar *help_description;
225 GDestroyNotify destroy_notify;
226 gpointer user_data;
228 GTranslateFunc translate_func;
229 GDestroyNotify translate_notify;
230 gpointer translate_data;
232 GOptionEntry *entries;
233 gint n_entries;
235 GOptionParseFunc pre_parse_func;
236 GOptionParseFunc post_parse_func;
237 GOptionErrorFunc error_func;
240 static void free_changes_list (GOptionContext *context,
241 gboolean revert);
242 static void free_pending_nulls (GOptionContext *context,
243 gboolean perform_nulls);
246 static int
247 _g_unichar_get_width (gunichar c)
249 if (G_UNLIKELY (g_unichar_iszerowidth (c)))
250 return 0;
252 /* we ignore the fact that we should call g_unichar_iswide_cjk() under
253 * some locales (legacy East Asian ones) */
254 if (g_unichar_iswide (c))
255 return 2;
257 return 1;
260 static glong
261 _g_utf8_strwidth (const gchar *p)
263 glong len = 0;
264 const gchar *start = p;
265 g_return_val_if_fail (p != NULL, 0);
267 while (*p)
269 len += _g_unichar_get_width (g_utf8_get_char (p));
270 p = g_utf8_next_char (p);
273 return len;
277 GQuark
278 g_option_error_quark (void)
280 return g_quark_from_static_string ("g-option-context-error-quark");
284 * g_option_context_new:
285 * @parameter_string: a string which is displayed in
286 * the first line of <option>--help</option> output, after the
287 * usage summary
288 * <literal><replaceable>programname</replaceable> [OPTION...]</literal>
290 * Creates a new option context.
292 * The @parameter_string can serve multiple purposes. It can be used
293 * to add descriptions for "rest" arguments, which are not parsed by
294 * the #GOptionContext, typically something like "FILES" or
295 * "FILE1 FILE2...". If you are using #G_OPTION_REMAINING for
296 * collecting "rest" arguments, GLib handles this automatically by
297 * using the @arg_description of the corresponding #GOptionEntry in
298 * the usage summary.
300 * Another usage is to give a short summary of the program
301 * functionality, like " - frob the strings", which will be displayed
302 * in the same line as the usage. For a longer description of the
303 * program functionality that should be displayed as a paragraph
304 * below the usage line, use g_option_context_set_summary().
306 * Note that the @parameter_string is translated using the
307 * function set with g_option_context_set_translate_func(), so
308 * it should normally be passed untranslated.
310 * Returns: a newly created #GOptionContext, which must be
311 * freed with g_option_context_free() after use.
313 * Since: 2.6
315 GOptionContext *
316 g_option_context_new (const gchar *parameter_string)
319 GOptionContext *context;
321 context = g_new0 (GOptionContext, 1);
323 context->parameter_string = g_strdup (parameter_string);
324 context->help_enabled = TRUE;
325 context->ignore_unknown = FALSE;
327 return context;
331 * g_option_context_free:
332 * @context: a #GOptionContext
334 * Frees context and all the groups which have been
335 * added to it.
337 * Please note that parsed arguments need to be freed separately (see
338 * #GOptionEntry).
340 * Since: 2.6
342 void g_option_context_free (GOptionContext *context)
344 g_return_if_fail (context != NULL);
346 g_list_free_full (context->groups, (GDestroyNotify) g_option_group_free);
348 if (context->main_group)
349 g_option_group_free (context->main_group);
351 free_changes_list (context, FALSE);
352 free_pending_nulls (context, FALSE);
354 g_free (context->parameter_string);
355 g_free (context->summary);
356 g_free (context->description);
358 if (context->translate_notify)
359 (* context->translate_notify) (context->translate_data);
361 g_free (context);
366 * g_option_context_set_help_enabled:
367 * @context: a #GOptionContext
368 * @help_enabled: %TRUE to enable <option>--help</option>, %FALSE to disable it
370 * Enables or disables automatic generation of <option>--help</option>
371 * output. By default, g_option_context_parse() recognizes
372 * <option>--help</option>, <option>-h</option>,
373 * <option>-?</option>, <option>--help-all</option>
374 * and <option>--help-</option><replaceable>groupname</replaceable> and creates
375 * suitable output to stdout.
377 * Since: 2.6
379 void g_option_context_set_help_enabled (GOptionContext *context,
380 gboolean help_enabled)
383 g_return_if_fail (context != NULL);
385 context->help_enabled = help_enabled;
389 * g_option_context_get_help_enabled:
390 * @context: a #GOptionContext
392 * Returns whether automatic <option>--help</option> generation
393 * is turned on for @context. See g_option_context_set_help_enabled().
395 * Returns: %TRUE if automatic help generation is turned on.
397 * Since: 2.6
399 gboolean
400 g_option_context_get_help_enabled (GOptionContext *context)
402 g_return_val_if_fail (context != NULL, FALSE);
404 return context->help_enabled;
408 * g_option_context_set_ignore_unknown_options:
409 * @context: a #GOptionContext
410 * @ignore_unknown: %TRUE to ignore unknown options, %FALSE to produce
411 * an error when unknown options are met
413 * Sets whether to ignore unknown options or not. If an argument is
414 * ignored, it is left in the @argv array after parsing. By default,
415 * g_option_context_parse() treats unknown options as error.
417 * This setting does not affect non-option arguments (i.e. arguments
418 * which don't start with a dash). But note that GOption cannot reliably
419 * determine whether a non-option belongs to a preceding unknown option.
421 * Since: 2.6
423 void
424 g_option_context_set_ignore_unknown_options (GOptionContext *context,
425 gboolean ignore_unknown)
427 g_return_if_fail (context != NULL);
429 context->ignore_unknown = ignore_unknown;
433 * g_option_context_get_ignore_unknown_options:
434 * @context: a #GOptionContext
436 * Returns whether unknown options are ignored or not. See
437 * g_option_context_set_ignore_unknown_options().
439 * Returns: %TRUE if unknown options are ignored.
441 * Since: 2.6
443 gboolean
444 g_option_context_get_ignore_unknown_options (GOptionContext *context)
446 g_return_val_if_fail (context != NULL, FALSE);
448 return context->ignore_unknown;
452 * g_option_context_add_group:
453 * @context: a #GOptionContext
454 * @group: the group to add
456 * Adds a #GOptionGroup to the @context, so that parsing with @context
457 * will recognize the options in the group. Note that the group will
458 * be freed together with the context when g_option_context_free() is
459 * called, so you must not free the group yourself after adding it
460 * to a context.
462 * Since: 2.6
464 void
465 g_option_context_add_group (GOptionContext *context,
466 GOptionGroup *group)
468 GList *list;
470 g_return_if_fail (context != NULL);
471 g_return_if_fail (group != NULL);
472 g_return_if_fail (group->name != NULL);
473 g_return_if_fail (group->description != NULL);
474 g_return_if_fail (group->help_description != NULL);
476 for (list = context->groups; list; list = list->next)
478 GOptionGroup *g = (GOptionGroup *)list->data;
480 if ((group->name == NULL && g->name == NULL) ||
481 (group->name && g->name && strcmp (group->name, g->name) == 0))
482 g_warning ("A group named \"%s\" is already part of this GOptionContext",
483 group->name);
486 context->groups = g_list_append (context->groups, group);
490 * g_option_context_set_main_group:
491 * @context: a #GOptionContext
492 * @group: the group to set as main group
494 * Sets a #GOptionGroup as main group of the @context.
495 * This has the same effect as calling g_option_context_add_group(),
496 * the only difference is that the options in the main group are
497 * treated differently when generating <option>--help</option> output.
499 * Since: 2.6
501 void
502 g_option_context_set_main_group (GOptionContext *context,
503 GOptionGroup *group)
505 g_return_if_fail (context != NULL);
506 g_return_if_fail (group != NULL);
508 if (context->main_group)
510 g_warning ("This GOptionContext already has a main group");
512 return;
515 context->main_group = group;
519 * g_option_context_get_main_group:
520 * @context: a #GOptionContext
522 * Returns a pointer to the main group of @context.
524 * Return value: the main group of @context, or %NULL if @context doesn't
525 * have a main group. Note that group belongs to @context and should
526 * not be modified or freed.
528 * Since: 2.6
530 GOptionGroup *
531 g_option_context_get_main_group (GOptionContext *context)
533 g_return_val_if_fail (context != NULL, NULL);
535 return context->main_group;
539 * g_option_context_add_main_entries:
540 * @context: a #GOptionContext
541 * @entries: a %NULL-terminated array of #GOptionEntry<!-- -->s
542 * @translation_domain: (allow-none): a translation domain to use for translating
543 * the <option>--help</option> output for the options in @entries
544 * with gettext(), or %NULL
546 * A convenience function which creates a main group if it doesn't
547 * exist, adds the @entries to it and sets the translation domain.
549 * Since: 2.6
551 void
552 g_option_context_add_main_entries (GOptionContext *context,
553 const GOptionEntry *entries,
554 const gchar *translation_domain)
556 g_return_if_fail (entries != NULL);
558 if (!context->main_group)
559 context->main_group = g_option_group_new (NULL, NULL, NULL, NULL, NULL);
561 g_option_group_add_entries (context->main_group, entries);
562 g_option_group_set_translation_domain (context->main_group, translation_domain);
565 static gint
566 calculate_max_length (GOptionGroup *group)
568 GOptionEntry *entry;
569 gint i, len, max_length;
571 max_length = 0;
573 for (i = 0; i < group->n_entries; i++)
575 entry = &group->entries[i];
577 if (entry->flags & G_OPTION_FLAG_HIDDEN)
578 continue;
580 len = _g_utf8_strwidth (entry->long_name);
582 if (entry->short_name)
583 len += 4;
585 if (!NO_ARG (entry) && entry->arg_description)
586 len += 1 + _g_utf8_strwidth (TRANSLATE (group, entry->arg_description));
588 max_length = MAX (max_length, len);
591 return max_length;
594 static void
595 print_entry (GOptionGroup *group,
596 gint max_length,
597 const GOptionEntry *entry,
598 GString *string)
600 GString *str;
602 if (entry->flags & G_OPTION_FLAG_HIDDEN)
603 return;
605 if (entry->long_name[0] == 0)
606 return;
608 str = g_string_new (NULL);
610 if (entry->short_name)
611 g_string_append_printf (str, " -%c, --%s", entry->short_name, entry->long_name);
612 else
613 g_string_append_printf (str, " --%s", entry->long_name);
615 if (entry->arg_description)
616 g_string_append_printf (str, "=%s", TRANSLATE (group, entry->arg_description));
618 g_string_append_printf (string, "%s%*s %s\n", str->str,
619 (int) (max_length + 4 - _g_utf8_strwidth (str->str)), "",
620 entry->description ? TRANSLATE (group, entry->description) : "");
621 g_string_free (str, TRUE);
624 static gboolean
625 group_has_visible_entries (GOptionContext *context,
626 GOptionGroup *group,
627 gboolean main_entries)
629 GOptionFlags reject_filter = G_OPTION_FLAG_HIDDEN;
630 GOptionEntry *entry;
631 gint i, l;
632 gboolean main_group = group == context->main_group;
634 if (!main_entries)
635 reject_filter |= G_OPTION_FLAG_IN_MAIN;
637 for (i = 0, l = (group ? group->n_entries : 0); i < l; i++)
639 entry = &group->entries[i];
641 if (main_entries && !main_group && !(entry->flags & G_OPTION_FLAG_IN_MAIN))
642 continue;
643 if (!(entry->flags & reject_filter))
644 return TRUE;
647 return FALSE;
650 static gboolean
651 group_list_has_visible_entires (GOptionContext *context,
652 GList *group_list,
653 gboolean main_entries)
655 while (group_list)
657 if (group_has_visible_entries (context, group_list->data, main_entries))
658 return TRUE;
660 group_list = group_list->next;
663 return FALSE;
666 static gboolean
667 context_has_h_entry (GOptionContext *context)
669 gsize i;
670 GList *list;
672 if (context->main_group)
674 for (i = 0; i < context->main_group->n_entries; i++)
676 if (context->main_group->entries[i].short_name == 'h')
677 return TRUE;
681 for (list = context->groups; list != NULL; list = g_list_next (list))
683 GOptionGroup *group;
685 group = (GOptionGroup*)list->data;
686 for (i = 0; i < group->n_entries; i++)
688 if (group->entries[i].short_name == 'h')
689 return TRUE;
692 return FALSE;
696 * g_option_context_get_help:
697 * @context: a #GOptionContext
698 * @main_help: if %TRUE, only include the main group
699 * @group: (allow-none): the #GOptionGroup to create help for, or %NULL
701 * Returns a formatted, translated help text for the given context.
702 * To obtain the text produced by <option>--help</option>, call
703 * <literal>g_option_context_get_help (context, TRUE, NULL)</literal>.
704 * To obtain the text produced by <option>--help-all</option>, call
705 * <literal>g_option_context_get_help (context, FALSE, NULL)</literal>.
706 * To obtain the help text for an option group, call
707 * <literal>g_option_context_get_help (context, FALSE, group)</literal>.
709 * Returns: A newly allocated string containing the help text
711 * Since: 2.14
713 gchar *
714 g_option_context_get_help (GOptionContext *context,
715 gboolean main_help,
716 GOptionGroup *group)
718 GList *list;
719 gint max_length, len;
720 gint i;
721 GOptionEntry *entry;
722 GHashTable *shadow_map;
723 gboolean seen[256];
724 const gchar *rest_description;
725 GString *string;
726 guchar token;
728 string = g_string_sized_new (1024);
730 rest_description = NULL;
731 if (context->main_group)
734 for (i = 0; i < context->main_group->n_entries; i++)
736 entry = &context->main_group->entries[i];
737 if (entry->long_name[0] == 0)
739 rest_description = TRANSLATE (context->main_group, entry->arg_description);
740 break;
745 g_string_append_printf (string, "%s\n %s %s",
746 _("Usage:"), g_get_prgname(), _("[OPTION...]"));
748 if (rest_description)
750 g_string_append (string, " ");
751 g_string_append (string, rest_description);
754 if (context->parameter_string)
756 g_string_append (string, " ");
757 g_string_append (string, TRANSLATE (context, context->parameter_string));
760 g_string_append (string, "\n\n");
762 if (context->summary)
764 g_string_append (string, TRANSLATE (context, context->summary));
765 g_string_append (string, "\n\n");
768 memset (seen, 0, sizeof (gboolean) * 256);
769 shadow_map = g_hash_table_new (g_str_hash, g_str_equal);
771 if (context->main_group)
773 for (i = 0; i < context->main_group->n_entries; i++)
775 entry = &context->main_group->entries[i];
776 g_hash_table_insert (shadow_map,
777 (gpointer)entry->long_name,
778 entry);
780 if (seen[(guchar)entry->short_name])
781 entry->short_name = 0;
782 else
783 seen[(guchar)entry->short_name] = TRUE;
787 list = context->groups;
788 while (list != NULL)
790 GOptionGroup *g = list->data;
791 for (i = 0; i < g->n_entries; i++)
793 entry = &g->entries[i];
794 if (g_hash_table_lookup (shadow_map, entry->long_name) &&
795 !(entry->flags & G_OPTION_FLAG_NOALIAS))
796 entry->long_name = g_strdup_printf ("%s-%s", g->name, entry->long_name);
797 else
798 g_hash_table_insert (shadow_map, (gpointer)entry->long_name, entry);
800 if (seen[(guchar)entry->short_name] &&
801 !(entry->flags & G_OPTION_FLAG_NOALIAS))
802 entry->short_name = 0;
803 else
804 seen[(guchar)entry->short_name] = TRUE;
806 list = list->next;
809 g_hash_table_destroy (shadow_map);
811 list = context->groups;
813 max_length = _g_utf8_strwidth ("-?, --help");
815 if (list)
817 len = _g_utf8_strwidth ("--help-all");
818 max_length = MAX (max_length, len);
821 if (context->main_group)
823 len = calculate_max_length (context->main_group);
824 max_length = MAX (max_length, len);
827 while (list != NULL)
829 GOptionGroup *g = list->data;
831 /* First, we check the --help-<groupname> options */
832 len = _g_utf8_strwidth ("--help-") + _g_utf8_strwidth (g->name);
833 max_length = MAX (max_length, len);
835 /* Then we go through the entries */
836 len = calculate_max_length (g);
837 max_length = MAX (max_length, len);
839 list = list->next;
842 /* Add a bit of padding */
843 max_length += 4;
845 if (!group)
847 list = context->groups;
849 token = context_has_h_entry (context) ? '?' : 'h';
851 g_string_append_printf (string, "%s\n -%c, --%-*s %s\n",
852 _("Help Options:"), token, max_length - 4, "help",
853 _("Show help options"));
855 /* We only want --help-all when there are groups */
856 if (list)
857 g_string_append_printf (string, " --%-*s %s\n",
858 max_length, "help-all",
859 _("Show all help options"));
861 while (list)
863 GOptionGroup *g = list->data;
865 if (group_has_visible_entries (context, g, FALSE))
866 g_string_append_printf (string, " --help-%-*s %s\n",
867 max_length - 5, g->name,
868 TRANSLATE (g, g->help_description));
870 list = list->next;
873 g_string_append (string, "\n");
876 if (group)
878 /* Print a certain group */
880 if (group_has_visible_entries (context, group, FALSE))
882 g_string_append (string, TRANSLATE (group, group->description));
883 g_string_append (string, "\n");
884 for (i = 0; i < group->n_entries; i++)
885 print_entry (group, max_length, &group->entries[i], string);
886 g_string_append (string, "\n");
889 else if (!main_help)
891 /* Print all groups */
893 list = context->groups;
895 while (list)
897 GOptionGroup *g = list->data;
899 if (group_has_visible_entries (context, g, FALSE))
901 g_string_append (string, g->description);
902 g_string_append (string, "\n");
903 for (i = 0; i < g->n_entries; i++)
904 if (!(g->entries[i].flags & G_OPTION_FLAG_IN_MAIN))
905 print_entry (g, max_length, &g->entries[i], string);
907 g_string_append (string, "\n");
910 list = list->next;
914 /* Print application options if --help or --help-all has been specified */
915 if ((main_help || !group) &&
916 (group_has_visible_entries (context, context->main_group, TRUE) ||
917 group_list_has_visible_entires (context, context->groups, TRUE)))
919 list = context->groups;
921 g_string_append (string, _("Application Options:"));
922 g_string_append (string, "\n");
923 if (context->main_group)
924 for (i = 0; i < context->main_group->n_entries; i++)
925 print_entry (context->main_group, max_length,
926 &context->main_group->entries[i], string);
928 while (list != NULL)
930 GOptionGroup *g = list->data;
932 /* Print main entries from other groups */
933 for (i = 0; i < g->n_entries; i++)
934 if (g->entries[i].flags & G_OPTION_FLAG_IN_MAIN)
935 print_entry (g, max_length, &g->entries[i], string);
937 list = list->next;
940 g_string_append (string, "\n");
943 if (context->description)
945 g_string_append (string, TRANSLATE (context, context->description));
946 g_string_append (string, "\n");
949 return g_string_free (string, FALSE);
952 G_GNUC_NORETURN
953 static void
954 print_help (GOptionContext *context,
955 gboolean main_help,
956 GOptionGroup *group)
958 gchar *help;
960 help = g_option_context_get_help (context, main_help, group);
961 g_print ("%s", help);
962 g_free (help);
964 exit (0);
967 static gboolean
968 parse_int (const gchar *arg_name,
969 const gchar *arg,
970 gint *result,
971 GError **error)
973 gchar *end;
974 glong tmp;
976 errno = 0;
977 tmp = strtol (arg, &end, 0);
979 if (*arg == '\0' || *end != '\0')
981 g_set_error (error,
982 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
983 _("Cannot parse integer value '%s' for %s"),
984 arg, arg_name);
985 return FALSE;
988 *result = tmp;
989 if (*result != tmp || errno == ERANGE)
991 g_set_error (error,
992 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
993 _("Integer value '%s' for %s out of range"),
994 arg, arg_name);
995 return FALSE;
998 return TRUE;
1002 static gboolean
1003 parse_double (const gchar *arg_name,
1004 const gchar *arg,
1005 gdouble *result,
1006 GError **error)
1008 gchar *end;
1009 gdouble tmp;
1011 errno = 0;
1012 tmp = g_strtod (arg, &end);
1014 if (*arg == '\0' || *end != '\0')
1016 g_set_error (error,
1017 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1018 _("Cannot parse double value '%s' for %s"),
1019 arg, arg_name);
1020 return FALSE;
1022 if (errno == ERANGE)
1024 g_set_error (error,
1025 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1026 _("Double value '%s' for %s out of range"),
1027 arg, arg_name);
1028 return FALSE;
1031 *result = tmp;
1033 return TRUE;
1037 static gboolean
1038 parse_int64 (const gchar *arg_name,
1039 const gchar *arg,
1040 gint64 *result,
1041 GError **error)
1043 gchar *end;
1044 gint64 tmp;
1046 errno = 0;
1047 tmp = g_ascii_strtoll (arg, &end, 0);
1049 if (*arg == '\0' || *end != '\0')
1051 g_set_error (error,
1052 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1053 _("Cannot parse integer value '%s' for %s"),
1054 arg, arg_name);
1055 return FALSE;
1057 if (errno == ERANGE)
1059 g_set_error (error,
1060 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1061 _("Integer value '%s' for %s out of range"),
1062 arg, arg_name);
1063 return FALSE;
1066 *result = tmp;
1068 return TRUE;
1072 static Change *
1073 get_change (GOptionContext *context,
1074 GOptionArg arg_type,
1075 gpointer arg_data)
1077 GList *list;
1078 Change *change = NULL;
1080 for (list = context->changes; list != NULL; list = list->next)
1082 change = list->data;
1084 if (change->arg_data == arg_data)
1085 goto found;
1088 change = g_new0 (Change, 1);
1089 change->arg_type = arg_type;
1090 change->arg_data = arg_data;
1092 context->changes = g_list_prepend (context->changes, change);
1094 found:
1096 return change;
1099 static void
1100 add_pending_null (GOptionContext *context,
1101 gchar **ptr,
1102 gchar *value)
1104 PendingNull *n;
1106 n = g_new0 (PendingNull, 1);
1107 n->ptr = ptr;
1108 n->value = value;
1110 context->pending_nulls = g_list_prepend (context->pending_nulls, n);
1113 static gboolean
1114 parse_arg (GOptionContext *context,
1115 GOptionGroup *group,
1116 GOptionEntry *entry,
1117 const gchar *value,
1118 const gchar *option_name,
1119 GError **error)
1122 Change *change;
1124 g_assert (value || OPTIONAL_ARG (entry) || NO_ARG (entry));
1126 switch (entry->arg)
1128 case G_OPTION_ARG_NONE:
1130 change = get_change (context, G_OPTION_ARG_NONE,
1131 entry->arg_data);
1133 *(gboolean *)entry->arg_data = !(entry->flags & G_OPTION_FLAG_REVERSE);
1134 break;
1136 case G_OPTION_ARG_STRING:
1138 gchar *data;
1140 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1142 if (!data)
1143 return FALSE;
1145 change = get_change (context, G_OPTION_ARG_STRING,
1146 entry->arg_data);
1147 g_free (change->allocated.str);
1149 change->prev.str = *(gchar **)entry->arg_data;
1150 change->allocated.str = data;
1152 *(gchar **)entry->arg_data = data;
1153 break;
1155 case G_OPTION_ARG_STRING_ARRAY:
1157 gchar *data;
1159 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1161 if (!data)
1162 return FALSE;
1164 change = get_change (context, G_OPTION_ARG_STRING_ARRAY,
1165 entry->arg_data);
1167 if (change->allocated.array.len == 0)
1169 change->prev.array = *(gchar ***)entry->arg_data;
1170 change->allocated.array.data = g_new (gchar *, 2);
1172 else
1173 change->allocated.array.data =
1174 g_renew (gchar *, change->allocated.array.data,
1175 change->allocated.array.len + 2);
1177 change->allocated.array.data[change->allocated.array.len] = data;
1178 change->allocated.array.data[change->allocated.array.len + 1] = NULL;
1180 change->allocated.array.len ++;
1182 *(gchar ***)entry->arg_data = change->allocated.array.data;
1184 break;
1187 case G_OPTION_ARG_FILENAME:
1189 gchar *data;
1191 #ifdef G_OS_WIN32
1192 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1194 if (!data)
1195 return FALSE;
1196 #else
1197 data = g_strdup (value);
1198 #endif
1199 change = get_change (context, G_OPTION_ARG_FILENAME,
1200 entry->arg_data);
1201 g_free (change->allocated.str);
1203 change->prev.str = *(gchar **)entry->arg_data;
1204 change->allocated.str = data;
1206 *(gchar **)entry->arg_data = data;
1207 break;
1210 case G_OPTION_ARG_FILENAME_ARRAY:
1212 gchar *data;
1214 #ifdef G_OS_WIN32
1215 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1217 if (!data)
1218 return FALSE;
1219 #else
1220 data = g_strdup (value);
1221 #endif
1222 change = get_change (context, G_OPTION_ARG_STRING_ARRAY,
1223 entry->arg_data);
1225 if (change->allocated.array.len == 0)
1227 change->prev.array = *(gchar ***)entry->arg_data;
1228 change->allocated.array.data = g_new (gchar *, 2);
1230 else
1231 change->allocated.array.data =
1232 g_renew (gchar *, change->allocated.array.data,
1233 change->allocated.array.len + 2);
1235 change->allocated.array.data[change->allocated.array.len] = data;
1236 change->allocated.array.data[change->allocated.array.len + 1] = NULL;
1238 change->allocated.array.len ++;
1240 *(gchar ***)entry->arg_data = change->allocated.array.data;
1242 break;
1245 case G_OPTION_ARG_INT:
1247 gint data;
1249 if (!parse_int (option_name, value,
1250 &data,
1251 error))
1252 return FALSE;
1254 change = get_change (context, G_OPTION_ARG_INT,
1255 entry->arg_data);
1256 change->prev.integer = *(gint *)entry->arg_data;
1257 *(gint *)entry->arg_data = data;
1258 break;
1260 case G_OPTION_ARG_CALLBACK:
1262 gchar *data;
1263 gboolean retval;
1265 if (!value && entry->flags & G_OPTION_FLAG_OPTIONAL_ARG)
1266 data = NULL;
1267 else if (entry->flags & G_OPTION_FLAG_NO_ARG)
1268 data = NULL;
1269 else if (entry->flags & G_OPTION_FLAG_FILENAME)
1271 #ifdef G_OS_WIN32
1272 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1273 #else
1274 data = g_strdup (value);
1275 #endif
1277 else
1278 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1280 if (!(entry->flags & (G_OPTION_FLAG_NO_ARG|G_OPTION_FLAG_OPTIONAL_ARG)) &&
1281 !data)
1282 return FALSE;
1284 retval = (* (GOptionArgFunc) entry->arg_data) (option_name, data, group->user_data, error);
1286 if (!retval && error != NULL && *error == NULL)
1287 g_set_error (error,
1288 G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
1289 _("Error parsing option %s"), option_name);
1291 g_free (data);
1293 return retval;
1295 break;
1297 case G_OPTION_ARG_DOUBLE:
1299 gdouble data;
1301 if (!parse_double (option_name, value,
1302 &data,
1303 error))
1305 return FALSE;
1308 change = get_change (context, G_OPTION_ARG_DOUBLE,
1309 entry->arg_data);
1310 change->prev.dbl = *(gdouble *)entry->arg_data;
1311 *(gdouble *)entry->arg_data = data;
1312 break;
1314 case G_OPTION_ARG_INT64:
1316 gint64 data;
1318 if (!parse_int64 (option_name, value,
1319 &data,
1320 error))
1322 return FALSE;
1325 change = get_change (context, G_OPTION_ARG_INT64,
1326 entry->arg_data);
1327 change->prev.int64 = *(gint64 *)entry->arg_data;
1328 *(gint64 *)entry->arg_data = data;
1329 break;
1331 default:
1332 g_assert_not_reached ();
1335 return TRUE;
1338 static gboolean
1339 parse_short_option (GOptionContext *context,
1340 GOptionGroup *group,
1341 gint idx,
1342 gint *new_idx,
1343 gchar arg,
1344 gint *argc,
1345 gchar ***argv,
1346 GError **error,
1347 gboolean *parsed)
1349 gint j;
1351 for (j = 0; j < group->n_entries; j++)
1353 if (arg == group->entries[j].short_name)
1355 gchar *option_name;
1356 gchar *value = NULL;
1358 option_name = g_strdup_printf ("-%c", group->entries[j].short_name);
1360 if (NO_ARG (&group->entries[j]))
1361 value = NULL;
1362 else
1364 if (*new_idx > idx)
1366 g_set_error (error,
1367 G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
1368 _("Error parsing option %s"), option_name);
1369 g_free (option_name);
1370 return FALSE;
1373 if (idx < *argc - 1)
1375 if (!OPTIONAL_ARG (&group->entries[j]))
1377 value = (*argv)[idx + 1];
1378 add_pending_null (context, &((*argv)[idx + 1]), NULL);
1379 *new_idx = idx + 1;
1381 else
1383 if ((*argv)[idx + 1][0] == '-')
1384 value = NULL;
1385 else
1387 value = (*argv)[idx + 1];
1388 add_pending_null (context, &((*argv)[idx + 1]), NULL);
1389 *new_idx = idx + 1;
1393 else if (idx >= *argc - 1 && OPTIONAL_ARG (&group->entries[j]))
1394 value = NULL;
1395 else
1397 g_set_error (error,
1398 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1399 _("Missing argument for %s"), option_name);
1400 g_free (option_name);
1401 return FALSE;
1405 if (!parse_arg (context, group, &group->entries[j],
1406 value, option_name, error))
1408 g_free (option_name);
1409 return FALSE;
1412 g_free (option_name);
1413 *parsed = TRUE;
1417 return TRUE;
1420 static gboolean
1421 parse_long_option (GOptionContext *context,
1422 GOptionGroup *group,
1423 gint *idx,
1424 gchar *arg,
1425 gboolean aliased,
1426 gint *argc,
1427 gchar ***argv,
1428 GError **error,
1429 gboolean *parsed)
1431 gint j;
1433 for (j = 0; j < group->n_entries; j++)
1435 if (*idx >= *argc)
1436 return TRUE;
1438 if (aliased && (group->entries[j].flags & G_OPTION_FLAG_NOALIAS))
1439 continue;
1441 if (NO_ARG (&group->entries[j]) &&
1442 strcmp (arg, group->entries[j].long_name) == 0)
1444 gchar *option_name;
1445 gboolean retval;
1447 option_name = g_strconcat ("--", group->entries[j].long_name, NULL);
1448 retval = parse_arg (context, group, &group->entries[j],
1449 NULL, option_name, error);
1450 g_free (option_name);
1452 add_pending_null (context, &((*argv)[*idx]), NULL);
1453 *parsed = TRUE;
1455 return retval;
1457 else
1459 gint len = strlen (group->entries[j].long_name);
1461 if (strncmp (arg, group->entries[j].long_name, len) == 0 &&
1462 (arg[len] == '=' || arg[len] == 0))
1464 gchar *value = NULL;
1465 gchar *option_name;
1467 add_pending_null (context, &((*argv)[*idx]), NULL);
1468 option_name = g_strconcat ("--", group->entries[j].long_name, NULL);
1470 if (arg[len] == '=')
1471 value = arg + len + 1;
1472 else if (*idx < *argc - 1)
1474 if (!OPTIONAL_ARG (&group->entries[j]))
1476 value = (*argv)[*idx + 1];
1477 add_pending_null (context, &((*argv)[*idx + 1]), NULL);
1478 (*idx)++;
1480 else
1482 if ((*argv)[*idx + 1][0] == '-')
1484 gboolean retval;
1485 retval = parse_arg (context, group, &group->entries[j],
1486 NULL, option_name, error);
1487 *parsed = TRUE;
1488 g_free (option_name);
1489 return retval;
1491 else
1493 value = (*argv)[*idx + 1];
1494 add_pending_null (context, &((*argv)[*idx + 1]), NULL);
1495 (*idx)++;
1499 else if (*idx >= *argc - 1 && OPTIONAL_ARG (&group->entries[j]))
1501 gboolean retval;
1502 retval = parse_arg (context, group, &group->entries[j],
1503 NULL, option_name, error);
1504 *parsed = TRUE;
1505 g_free (option_name);
1506 return retval;
1508 else
1510 g_set_error (error,
1511 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1512 _("Missing argument for %s"), option_name);
1513 g_free (option_name);
1514 return FALSE;
1517 if (!parse_arg (context, group, &group->entries[j],
1518 value, option_name, error))
1520 g_free (option_name);
1521 return FALSE;
1524 g_free (option_name);
1525 *parsed = TRUE;
1530 return TRUE;
1533 static gboolean
1534 parse_remaining_arg (GOptionContext *context,
1535 GOptionGroup *group,
1536 gint *idx,
1537 gint *argc,
1538 gchar ***argv,
1539 GError **error,
1540 gboolean *parsed)
1542 gint j;
1544 for (j = 0; j < group->n_entries; j++)
1546 if (*idx >= *argc)
1547 return TRUE;
1549 if (group->entries[j].long_name[0])
1550 continue;
1552 g_return_val_if_fail (group->entries[j].arg == G_OPTION_ARG_CALLBACK ||
1553 group->entries[j].arg == G_OPTION_ARG_STRING_ARRAY ||
1554 group->entries[j].arg == G_OPTION_ARG_FILENAME_ARRAY, FALSE);
1556 add_pending_null (context, &((*argv)[*idx]), NULL);
1558 if (!parse_arg (context, group, &group->entries[j], (*argv)[*idx], "", error))
1559 return FALSE;
1561 *parsed = TRUE;
1562 return TRUE;
1565 return TRUE;
1568 static void
1569 free_changes_list (GOptionContext *context,
1570 gboolean revert)
1572 GList *list;
1574 for (list = context->changes; list != NULL; list = list->next)
1576 Change *change = list->data;
1578 if (revert)
1580 switch (change->arg_type)
1582 case G_OPTION_ARG_NONE:
1583 *(gboolean *)change->arg_data = change->prev.bool;
1584 break;
1585 case G_OPTION_ARG_INT:
1586 *(gint *)change->arg_data = change->prev.integer;
1587 break;
1588 case G_OPTION_ARG_STRING:
1589 case G_OPTION_ARG_FILENAME:
1590 g_free (change->allocated.str);
1591 *(gchar **)change->arg_data = change->prev.str;
1592 break;
1593 case G_OPTION_ARG_STRING_ARRAY:
1594 case G_OPTION_ARG_FILENAME_ARRAY:
1595 g_strfreev (change->allocated.array.data);
1596 *(gchar ***)change->arg_data = change->prev.array;
1597 break;
1598 case G_OPTION_ARG_DOUBLE:
1599 *(gdouble *)change->arg_data = change->prev.dbl;
1600 break;
1601 case G_OPTION_ARG_INT64:
1602 *(gint64 *)change->arg_data = change->prev.int64;
1603 break;
1604 default:
1605 g_assert_not_reached ();
1609 g_free (change);
1612 g_list_free (context->changes);
1613 context->changes = NULL;
1616 static void
1617 free_pending_nulls (GOptionContext *context,
1618 gboolean perform_nulls)
1620 GList *list;
1622 for (list = context->pending_nulls; list != NULL; list = list->next)
1624 PendingNull *n = list->data;
1626 if (perform_nulls)
1628 if (n->value)
1630 /* Copy back the short options */
1631 *(n->ptr)[0] = '-';
1632 strcpy (*n->ptr + 1, n->value);
1634 else
1635 *n->ptr = NULL;
1638 g_free (n->value);
1639 g_free (n);
1642 g_list_free (context->pending_nulls);
1643 context->pending_nulls = NULL;
1646 /* Use a platform-specific mechanism to look up the first argument to
1647 * the current process.
1648 * Note if you implement this for other platforms, also add it to
1649 * tests/option-argv0.c
1651 static char *
1652 platform_get_argv0 (void)
1654 #if defined __linux
1655 char *cmdline;
1656 char *base_arg0;
1657 gsize len;
1659 if (!g_file_get_contents ("/proc/self/cmdline",
1660 &cmdline,
1661 &len,
1662 NULL))
1663 return NULL;
1664 /* Sanity check for a NUL terminator. */
1665 if (!memchr (cmdline, 0, len))
1666 return NULL;
1667 /* We could just return cmdline, but I think it's better
1668 * to hold on to a smaller malloc block; the arguments
1669 * could be large.
1671 base_arg0 = g_path_get_basename (cmdline);
1672 g_free (cmdline);
1673 return base_arg0;
1674 #elif defined __OpenBSD__
1675 char **cmdline = NULL;
1676 char *base_arg0;
1677 gsize len = PATH_MAX;
1679 int mib[] = { CTL_KERN, KERN_PROC_ARGS, getpid(), KERN_PROC_ARGV };
1681 cmdline = (char **) realloc (cmdline, len);
1683 if (sysctl (mib, nitems (mib), cmdline, &len, NULL, 0) == -1)
1685 g_free (cmdline);
1686 return NULL;
1689 /* We could just return cmdline, but I think it's better
1690 * to hold on to a smaller malloc block; the arguments
1691 * could be large.
1693 base_arg0 = g_path_get_basename (*cmdline);
1694 g_free (cmdline);
1695 return base_arg0;
1696 #endif
1698 return NULL;
1702 * g_option_context_parse:
1703 * @context: a #GOptionContext
1704 * @argc: (inout) (allow-none): a pointer to the number of command line arguments
1705 * @argv: (inout) (array length=argc) (allow-none): a pointer to the array of command line arguments
1706 * @error: a return location for errors
1708 * Parses the command line arguments, recognizing options
1709 * which have been added to @context. A side-effect of
1710 * calling this function is that g_set_prgname() will be
1711 * called.
1713 * If the parsing is successful, any parsed arguments are
1714 * removed from the array and @argc and @argv are updated
1715 * accordingly. A '--' option is stripped from @argv
1716 * unless there are unparsed options before and after it,
1717 * or some of the options after it start with '-'. In case
1718 * of an error, @argc and @argv are left unmodified.
1720 * If automatic <option>--help</option> support is enabled
1721 * (see g_option_context_set_help_enabled()), and the
1722 * @argv array contains one of the recognized help options,
1723 * this function will produce help output to stdout and
1724 * call <literal>exit (0)</literal>.
1726 * Note that function depends on the
1727 * <link linkend="setlocale">current locale</link> for
1728 * automatic character set conversion of string and filename
1729 * arguments.
1731 * Return value: %TRUE if the parsing was successful,
1732 * %FALSE if an error occurred
1734 * Since: 2.6
1736 gboolean
1737 g_option_context_parse (GOptionContext *context,
1738 gint *argc,
1739 gchar ***argv,
1740 GError **error)
1742 gint i, j, k;
1743 GList *list;
1745 /* Set program name */
1746 if (!g_get_prgname())
1748 gchar *prgname;
1750 if (argc && argv && *argc)
1751 prgname = g_path_get_basename ((*argv)[0]);
1752 else
1753 prgname = platform_get_argv0 ();
1755 if (prgname)
1756 g_set_prgname (prgname);
1757 else
1758 g_set_prgname ("<unknown>");
1760 g_free (prgname);
1763 /* Call pre-parse hooks */
1764 list = context->groups;
1765 while (list)
1767 GOptionGroup *group = list->data;
1769 if (group->pre_parse_func)
1771 if (!(* group->pre_parse_func) (context, group,
1772 group->user_data, error))
1773 goto fail;
1776 list = list->next;
1779 if (context->main_group && context->main_group->pre_parse_func)
1781 if (!(* context->main_group->pre_parse_func) (context, context->main_group,
1782 context->main_group->user_data, error))
1783 goto fail;
1786 if (argc && argv)
1788 gboolean stop_parsing = FALSE;
1789 gboolean has_unknown = FALSE;
1790 gint separator_pos = 0;
1792 for (i = 1; i < *argc; i++)
1794 gchar *arg, *dash;
1795 gboolean parsed = FALSE;
1797 if ((*argv)[i][0] == '-' && (*argv)[i][1] != '\0' && !stop_parsing)
1799 if ((*argv)[i][1] == '-')
1801 /* -- option */
1803 arg = (*argv)[i] + 2;
1805 /* '--' terminates list of arguments */
1806 if (*arg == 0)
1808 separator_pos = i;
1809 stop_parsing = TRUE;
1810 continue;
1813 /* Handle help options */
1814 if (context->help_enabled)
1816 if (strcmp (arg, "help") == 0)
1817 print_help (context, TRUE, NULL);
1818 else if (strcmp (arg, "help-all") == 0)
1819 print_help (context, FALSE, NULL);
1820 else if (strncmp (arg, "help-", 5) == 0)
1822 list = context->groups;
1824 while (list)
1826 GOptionGroup *group = list->data;
1828 if (strcmp (arg + 5, group->name) == 0)
1829 print_help (context, FALSE, group);
1831 list = list->next;
1836 if (context->main_group &&
1837 !parse_long_option (context, context->main_group, &i, arg,
1838 FALSE, argc, argv, error, &parsed))
1839 goto fail;
1841 if (parsed)
1842 continue;
1844 /* Try the groups */
1845 list = context->groups;
1846 while (list)
1848 GOptionGroup *group = list->data;
1850 if (!parse_long_option (context, group, &i, arg,
1851 FALSE, argc, argv, error, &parsed))
1852 goto fail;
1854 if (parsed)
1855 break;
1857 list = list->next;
1860 if (parsed)
1861 continue;
1863 /* Now look for --<group>-<option> */
1864 dash = strchr (arg, '-');
1865 if (dash)
1867 /* Try the groups */
1868 list = context->groups;
1869 while (list)
1871 GOptionGroup *group = list->data;
1873 if (strncmp (group->name, arg, dash - arg) == 0)
1875 if (!parse_long_option (context, group, &i, dash + 1,
1876 TRUE, argc, argv, error, &parsed))
1877 goto fail;
1879 if (parsed)
1880 break;
1883 list = list->next;
1887 if (context->ignore_unknown)
1888 continue;
1890 else
1891 { /* short option */
1892 gint new_i = i, arg_length;
1893 gboolean *nulled_out = NULL;
1894 gboolean has_h_entry = context_has_h_entry (context);
1895 arg = (*argv)[i] + 1;
1896 arg_length = strlen (arg);
1897 nulled_out = g_newa (gboolean, arg_length);
1898 memset (nulled_out, 0, arg_length * sizeof (gboolean));
1899 for (j = 0; j < arg_length; j++)
1901 if (context->help_enabled && (arg[j] == '?' ||
1902 (arg[j] == 'h' && !has_h_entry)))
1903 print_help (context, TRUE, NULL);
1904 parsed = FALSE;
1905 if (context->main_group &&
1906 !parse_short_option (context, context->main_group,
1907 i, &new_i, arg[j],
1908 argc, argv, error, &parsed))
1909 goto fail;
1910 if (!parsed)
1912 /* Try the groups */
1913 list = context->groups;
1914 while (list)
1916 GOptionGroup *group = list->data;
1917 if (!parse_short_option (context, group, i, &new_i, arg[j],
1918 argc, argv, error, &parsed))
1919 goto fail;
1920 if (parsed)
1921 break;
1922 list = list->next;
1926 if (context->ignore_unknown && parsed)
1927 nulled_out[j] = TRUE;
1928 else if (context->ignore_unknown)
1929 continue;
1930 else if (!parsed)
1931 break;
1932 /* !context->ignore_unknown && parsed */
1934 if (context->ignore_unknown)
1936 gchar *new_arg = NULL;
1937 gint arg_index = 0;
1938 for (j = 0; j < arg_length; j++)
1940 if (!nulled_out[j])
1942 if (!new_arg)
1943 new_arg = g_malloc (arg_length + 1);
1944 new_arg[arg_index++] = arg[j];
1947 if (new_arg)
1948 new_arg[arg_index] = '\0';
1949 add_pending_null (context, &((*argv)[i]), new_arg);
1951 else if (parsed)
1953 add_pending_null (context, &((*argv)[i]), NULL);
1954 i = new_i;
1958 if (!parsed)
1959 has_unknown = TRUE;
1961 if (!parsed && !context->ignore_unknown)
1963 g_set_error (error,
1964 G_OPTION_ERROR, G_OPTION_ERROR_UNKNOWN_OPTION,
1965 _("Unknown option %s"), (*argv)[i]);
1966 goto fail;
1969 else
1971 /* Collect remaining args */
1972 if (context->main_group &&
1973 !parse_remaining_arg (context, context->main_group, &i,
1974 argc, argv, error, &parsed))
1975 goto fail;
1977 if (!parsed && (has_unknown || (*argv)[i][0] == '-'))
1978 separator_pos = 0;
1982 if (separator_pos > 0)
1983 add_pending_null (context, &((*argv)[separator_pos]), NULL);
1987 /* Call post-parse hooks */
1988 list = context->groups;
1989 while (list)
1991 GOptionGroup *group = list->data;
1993 if (group->post_parse_func)
1995 if (!(* group->post_parse_func) (context, group,
1996 group->user_data, error))
1997 goto fail;
2000 list = list->next;
2003 if (context->main_group && context->main_group->post_parse_func)
2005 if (!(* context->main_group->post_parse_func) (context, context->main_group,
2006 context->main_group->user_data, error))
2007 goto fail;
2010 if (argc && argv)
2012 free_pending_nulls (context, TRUE);
2014 for (i = 1; i < *argc; i++)
2016 for (k = i; k < *argc; k++)
2017 if ((*argv)[k] != NULL)
2018 break;
2020 if (k > i)
2022 k -= i;
2023 for (j = i + k; j < *argc; j++)
2025 (*argv)[j-k] = (*argv)[j];
2026 (*argv)[j] = NULL;
2028 *argc -= k;
2033 return TRUE;
2035 fail:
2037 /* Call error hooks */
2038 list = context->groups;
2039 while (list)
2041 GOptionGroup *group = list->data;
2043 if (group->error_func)
2044 (* group->error_func) (context, group,
2045 group->user_data, error);
2047 list = list->next;
2050 if (context->main_group && context->main_group->error_func)
2051 (* context->main_group->error_func) (context, context->main_group,
2052 context->main_group->user_data, error);
2054 free_changes_list (context, TRUE);
2055 free_pending_nulls (context, FALSE);
2057 return FALSE;
2061 * g_option_group_new:
2062 * @name: the name for the option group, this is used to provide
2063 * help for the options in this group with <option>--help-</option>@name
2064 * @description: a description for this group to be shown in
2065 * <option>--help</option>. This string is translated using the translation
2066 * domain or translation function of the group
2067 * @help_description: a description for the <option>--help-</option>@name option.
2068 * This string is translated using the translation domain or translation function
2069 * of the group
2070 * @user_data: (allow-none): user data that will be passed to the pre- and post-parse hooks,
2071 * the error hook and to callbacks of %G_OPTION_ARG_CALLBACK options, or %NULL
2072 * @destroy: (allow-none): a function that will be called to free @user_data, or %NULL
2074 * Creates a new #GOptionGroup.
2076 * Return value: a newly created option group. It should be added
2077 * to a #GOptionContext or freed with g_option_group_free().
2079 * Since: 2.6
2081 GOptionGroup *
2082 g_option_group_new (const gchar *name,
2083 const gchar *description,
2084 const gchar *help_description,
2085 gpointer user_data,
2086 GDestroyNotify destroy)
2089 GOptionGroup *group;
2091 group = g_new0 (GOptionGroup, 1);
2092 group->name = g_strdup (name);
2093 group->description = g_strdup (description);
2094 group->help_description = g_strdup (help_description);
2095 group->user_data = user_data;
2096 group->destroy_notify = destroy;
2098 return group;
2103 * g_option_group_free:
2104 * @group: a #GOptionGroup
2106 * Frees a #GOptionGroup. Note that you must <emphasis>not</emphasis>
2107 * free groups which have been added to a #GOptionContext.
2109 * Since: 2.6
2111 void
2112 g_option_group_free (GOptionGroup *group)
2114 g_return_if_fail (group != NULL);
2116 g_free (group->name);
2117 g_free (group->description);
2118 g_free (group->help_description);
2120 g_free (group->entries);
2122 if (group->destroy_notify)
2123 (* group->destroy_notify) (group->user_data);
2125 if (group->translate_notify)
2126 (* group->translate_notify) (group->translate_data);
2128 g_free (group);
2133 * g_option_group_add_entries:
2134 * @group: a #GOptionGroup
2135 * @entries: a %NULL-terminated array of #GOptionEntry<!-- -->s
2137 * Adds the options specified in @entries to @group.
2139 * Since: 2.6
2141 void
2142 g_option_group_add_entries (GOptionGroup *group,
2143 const GOptionEntry *entries)
2145 gint i, n_entries;
2147 g_return_if_fail (entries != NULL);
2149 for (n_entries = 0; entries[n_entries].long_name != NULL; n_entries++) ;
2151 group->entries = g_renew (GOptionEntry, group->entries, group->n_entries + n_entries);
2153 memcpy (group->entries + group->n_entries, entries, sizeof (GOptionEntry) * n_entries);
2155 for (i = group->n_entries; i < group->n_entries + n_entries; i++)
2157 gchar c = group->entries[i].short_name;
2159 if (c == '-' || (c != 0 && !g_ascii_isprint (c)))
2161 g_warning (G_STRLOC ": ignoring invalid short option '%c' (%d) in entry %s:%s",
2162 c, c, group->name, group->entries[i].long_name);
2163 group->entries[i].short_name = '\0';
2166 if (group->entries[i].arg != G_OPTION_ARG_NONE &&
2167 (group->entries[i].flags & G_OPTION_FLAG_REVERSE) != 0)
2169 g_warning (G_STRLOC ": ignoring reverse flag on option of arg-type %d in entry %s:%s",
2170 group->entries[i].arg, group->name, group->entries[i].long_name);
2172 group->entries[i].flags &= ~G_OPTION_FLAG_REVERSE;
2175 if (group->entries[i].arg != G_OPTION_ARG_CALLBACK &&
2176 (group->entries[i].flags & (G_OPTION_FLAG_NO_ARG|G_OPTION_FLAG_OPTIONAL_ARG|G_OPTION_FLAG_FILENAME)) != 0)
2178 g_warning (G_STRLOC ": ignoring no-arg, optional-arg or filename flags (%d) on option of arg-type %d in entry %s:%s",
2179 group->entries[i].flags, group->entries[i].arg, group->name, group->entries[i].long_name);
2181 group->entries[i].flags &= ~(G_OPTION_FLAG_NO_ARG|G_OPTION_FLAG_OPTIONAL_ARG|G_OPTION_FLAG_FILENAME);
2185 group->n_entries += n_entries;
2189 * g_option_group_set_parse_hooks:
2190 * @group: a #GOptionGroup
2191 * @pre_parse_func: (allow-none): a function to call before parsing, or %NULL
2192 * @post_parse_func: (allow-none): a function to call after parsing, or %NULL
2194 * Associates two functions with @group which will be called
2195 * from g_option_context_parse() before the first option is parsed
2196 * and after the last option has been parsed, respectively.
2198 * Note that the user data to be passed to @pre_parse_func and
2199 * @post_parse_func can be specified when constructing the group
2200 * with g_option_group_new().
2202 * Since: 2.6
2204 void
2205 g_option_group_set_parse_hooks (GOptionGroup *group,
2206 GOptionParseFunc pre_parse_func,
2207 GOptionParseFunc post_parse_func)
2209 g_return_if_fail (group != NULL);
2211 group->pre_parse_func = pre_parse_func;
2212 group->post_parse_func = post_parse_func;
2216 * g_option_group_set_error_hook:
2217 * @group: a #GOptionGroup
2218 * @error_func: a function to call when an error occurs
2220 * Associates a function with @group which will be called
2221 * from g_option_context_parse() when an error occurs.
2223 * Note that the user data to be passed to @error_func can be
2224 * specified when constructing the group with g_option_group_new().
2226 * Since: 2.6
2228 void
2229 g_option_group_set_error_hook (GOptionGroup *group,
2230 GOptionErrorFunc error_func)
2232 g_return_if_fail (group != NULL);
2234 group->error_func = error_func;
2239 * g_option_group_set_translate_func:
2240 * @group: a #GOptionGroup
2241 * @func: (allow-none): the #GTranslateFunc, or %NULL
2242 * @data: (allow-none): user data to pass to @func, or %NULL
2243 * @destroy_notify: (allow-none): a function which gets called to free @data, or %NULL
2245 * Sets the function which is used to translate user-visible
2246 * strings, for <option>--help</option> output. Different
2247 * groups can use different #GTranslateFunc<!-- -->s. If @func
2248 * is %NULL, strings are not translated.
2250 * If you are using gettext(), you only need to set the translation
2251 * domain, see g_option_group_set_translation_domain().
2253 * Since: 2.6
2255 void
2256 g_option_group_set_translate_func (GOptionGroup *group,
2257 GTranslateFunc func,
2258 gpointer data,
2259 GDestroyNotify destroy_notify)
2261 g_return_if_fail (group != NULL);
2263 if (group->translate_notify)
2264 group->translate_notify (group->translate_data);
2266 group->translate_func = func;
2267 group->translate_data = data;
2268 group->translate_notify = destroy_notify;
2271 static const gchar *
2272 dgettext_swapped (const gchar *msgid,
2273 const gchar *domainname)
2275 return g_dgettext (domainname, msgid);
2279 * g_option_group_set_translation_domain:
2280 * @group: a #GOptionGroup
2281 * @domain: the domain to use
2283 * A convenience function to use gettext() for translating
2284 * user-visible strings.
2286 * Since: 2.6
2288 void
2289 g_option_group_set_translation_domain (GOptionGroup *group,
2290 const gchar *domain)
2292 g_return_if_fail (group != NULL);
2294 g_option_group_set_translate_func (group,
2295 (GTranslateFunc)dgettext_swapped,
2296 g_strdup (domain),
2297 g_free);
2301 * g_option_context_set_translate_func:
2302 * @context: a #GOptionContext
2303 * @func: (allow-none): the #GTranslateFunc, or %NULL
2304 * @data: (allow-none): user data to pass to @func, or %NULL
2305 * @destroy_notify: (allow-none): a function which gets called to free @data, or %NULL
2307 * Sets the function which is used to translate the contexts
2308 * user-visible strings, for <option>--help</option> output.
2309 * If @func is %NULL, strings are not translated.
2311 * Note that option groups have their own translation functions,
2312 * this function only affects the @parameter_string (see g_option_context_new()),
2313 * the summary (see g_option_context_set_summary()) and the description
2314 * (see g_option_context_set_description()).
2316 * If you are using gettext(), you only need to set the translation
2317 * domain, see g_option_context_set_translation_domain().
2319 * Since: 2.12
2321 void
2322 g_option_context_set_translate_func (GOptionContext *context,
2323 GTranslateFunc func,
2324 gpointer data,
2325 GDestroyNotify destroy_notify)
2327 g_return_if_fail (context != NULL);
2329 if (context->translate_notify)
2330 context->translate_notify (context->translate_data);
2332 context->translate_func = func;
2333 context->translate_data = data;
2334 context->translate_notify = destroy_notify;
2338 * g_option_context_set_translation_domain:
2339 * @context: a #GOptionContext
2340 * @domain: the domain to use
2342 * A convenience function to use gettext() for translating
2343 * user-visible strings.
2345 * Since: 2.12
2347 void
2348 g_option_context_set_translation_domain (GOptionContext *context,
2349 const gchar *domain)
2351 g_return_if_fail (context != NULL);
2353 g_option_context_set_translate_func (context,
2354 (GTranslateFunc)dgettext_swapped,
2355 g_strdup (domain),
2356 g_free);
2360 * g_option_context_set_summary:
2361 * @context: a #GOptionContext
2362 * @summary: (allow-none): a string to be shown in <option>--help</option> output
2363 * before the list of options, or %NULL
2365 * Adds a string to be displayed in <option>--help</option> output
2366 * before the list of options. This is typically a summary of the
2367 * program functionality.
2369 * Note that the summary is translated (see
2370 * g_option_context_set_translate_func() and
2371 * g_option_context_set_translation_domain()).
2373 * Since: 2.12
2375 void
2376 g_option_context_set_summary (GOptionContext *context,
2377 const gchar *summary)
2379 g_return_if_fail (context != NULL);
2381 g_free (context->summary);
2382 context->summary = g_strdup (summary);
2387 * g_option_context_get_summary:
2388 * @context: a #GOptionContext
2390 * Returns the summary. See g_option_context_set_summary().
2392 * Returns: the summary
2394 * Since: 2.12
2396 const gchar *
2397 g_option_context_get_summary (GOptionContext *context)
2399 g_return_val_if_fail (context != NULL, NULL);
2401 return context->summary;
2405 * g_option_context_set_description:
2406 * @context: a #GOptionContext
2407 * @description: (allow-none): a string to be shown in <option>--help</option> output
2408 * after the list of options, or %NULL
2410 * Adds a string to be displayed in <option>--help</option> output
2411 * after the list of options. This text often includes a bug reporting
2412 * address.
2414 * Note that the summary is translated (see
2415 * g_option_context_set_translate_func()).
2417 * Since: 2.12
2419 void
2420 g_option_context_set_description (GOptionContext *context,
2421 const gchar *description)
2423 g_return_if_fail (context != NULL);
2425 g_free (context->description);
2426 context->description = g_strdup (description);
2431 * g_option_context_get_description:
2432 * @context: a #GOptionContext
2434 * Returns the description. See g_option_context_set_description().
2436 * Returns: the description
2438 * Since: 2.12
2440 const gchar *
2441 g_option_context_get_description (GOptionContext *context)
2443 g_return_val_if_fail (context != NULL, NULL);
2445 return context->description;