goption: [linux] Look in /proc/self/cmdline for argv0 if not specified
[glib.git] / glib / goption.c
blob0e0437c3c2dd4dbe803ae10a4c473b02db6cd311
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 #include "goption.h"
144 #include "gprintf.h"
145 #include "glibintl.h"
147 #define TRANSLATE(group, str) (((group)->translate_func ? (* (group)->translate_func) ((str), (group)->translate_data) : (str)))
149 #define NO_ARG(entry) ((entry)->arg == G_OPTION_ARG_NONE || \
150 ((entry)->arg == G_OPTION_ARG_CALLBACK && \
151 ((entry)->flags & G_OPTION_FLAG_NO_ARG)))
153 #define OPTIONAL_ARG(entry) ((entry)->arg == G_OPTION_ARG_CALLBACK && \
154 (entry)->flags & G_OPTION_FLAG_OPTIONAL_ARG)
156 typedef struct
158 GOptionArg arg_type;
159 gpointer arg_data;
160 union
162 gboolean bool;
163 gint integer;
164 gchar *str;
165 gchar **array;
166 gdouble dbl;
167 gint64 int64;
168 } prev;
169 union
171 gchar *str;
172 struct
174 gint len;
175 gchar **data;
176 } array;
177 } allocated;
178 } Change;
180 typedef struct
182 gchar **ptr;
183 gchar *value;
184 } PendingNull;
186 struct _GOptionContext
188 GList *groups;
190 gchar *parameter_string;
191 gchar *summary;
192 gchar *description;
194 GTranslateFunc translate_func;
195 GDestroyNotify translate_notify;
196 gpointer translate_data;
198 guint help_enabled : 1;
199 guint ignore_unknown : 1;
201 GOptionGroup *main_group;
203 /* We keep a list of change so we can revert them */
204 GList *changes;
206 /* We also keep track of all argv elements
207 * that should be NULLed or modified.
209 GList *pending_nulls;
212 struct _GOptionGroup
214 gchar *name;
215 gchar *description;
216 gchar *help_description;
218 GDestroyNotify destroy_notify;
219 gpointer user_data;
221 GTranslateFunc translate_func;
222 GDestroyNotify translate_notify;
223 gpointer translate_data;
225 GOptionEntry *entries;
226 gint n_entries;
228 GOptionParseFunc pre_parse_func;
229 GOptionParseFunc post_parse_func;
230 GOptionErrorFunc error_func;
233 static void free_changes_list (GOptionContext *context,
234 gboolean revert);
235 static void free_pending_nulls (GOptionContext *context,
236 gboolean perform_nulls);
239 static int
240 _g_unichar_get_width (gunichar c)
242 if (G_UNLIKELY (g_unichar_iszerowidth (c)))
243 return 0;
245 /* we ignore the fact that we should call g_unichar_iswide_cjk() under
246 * some locales (legacy East Asian ones) */
247 if (g_unichar_iswide (c))
248 return 2;
250 return 1;
253 static glong
254 _g_utf8_strwidth (const gchar *p,
255 gssize max)
257 glong len = 0;
258 const gchar *start = p;
259 g_return_val_if_fail (p != NULL || max == 0, 0);
261 if (max < 0)
263 while (*p)
265 len += _g_unichar_get_width (g_utf8_get_char (p));
266 p = g_utf8_next_char (p);
269 else
271 if (max == 0 || !*p)
272 return 0;
274 /* this case may not be quite correct */
276 len += _g_unichar_get_width (g_utf8_get_char (p));
277 p = g_utf8_next_char (p);
279 while (p - start < max && *p)
281 len += _g_unichar_get_width (g_utf8_get_char (p));
282 p = g_utf8_next_char (p);
286 return len;
290 GQuark
291 g_option_error_quark (void)
293 return g_quark_from_static_string ("g-option-context-error-quark");
297 * g_option_context_new:
298 * @parameter_string: a string which is displayed in
299 * the first line of <option>--help</option> output, after the
300 * usage summary
301 * <literal><replaceable>programname</replaceable> [OPTION...]</literal>
303 * Creates a new option context.
305 * The @parameter_string can serve multiple purposes. It can be used
306 * to add descriptions for "rest" arguments, which are not parsed by
307 * the #GOptionContext, typically something like "FILES" or
308 * "FILE1 FILE2...". If you are using #G_OPTION_REMAINING for
309 * collecting "rest" arguments, GLib handles this automatically by
310 * using the @arg_description of the corresponding #GOptionEntry in
311 * the usage summary.
313 * Another usage is to give a short summary of the program
314 * functionality, like " - frob the strings", which will be displayed
315 * in the same line as the usage. For a longer description of the
316 * program functionality that should be displayed as a paragraph
317 * below the usage line, use g_option_context_set_summary().
319 * Note that the @parameter_string is translated using the
320 * function set with g_option_context_set_translate_func(), so
321 * it should normally be passed untranslated.
323 * Returns: a newly created #GOptionContext, which must be
324 * freed with g_option_context_free() after use.
326 * Since: 2.6
328 GOptionContext *
329 g_option_context_new (const gchar *parameter_string)
332 GOptionContext *context;
334 context = g_new0 (GOptionContext, 1);
336 context->parameter_string = g_strdup (parameter_string);
337 context->help_enabled = TRUE;
338 context->ignore_unknown = FALSE;
340 return context;
344 * g_option_context_free:
345 * @context: a #GOptionContext
347 * Frees context and all the groups which have been
348 * added to it.
350 * Please note that parsed arguments need to be freed separately (see
351 * #GOptionEntry).
353 * Since: 2.6
355 void g_option_context_free (GOptionContext *context)
357 g_return_if_fail (context != NULL);
359 g_list_foreach (context->groups, (GFunc)g_option_group_free, NULL);
360 g_list_free (context->groups);
362 if (context->main_group)
363 g_option_group_free (context->main_group);
365 free_changes_list (context, FALSE);
366 free_pending_nulls (context, FALSE);
368 g_free (context->parameter_string);
369 g_free (context->summary);
370 g_free (context->description);
372 if (context->translate_notify)
373 (* context->translate_notify) (context->translate_data);
375 g_free (context);
380 * g_option_context_set_help_enabled:
381 * @context: a #GOptionContext
382 * @help_enabled: %TRUE to enable <option>--help</option>, %FALSE to disable it
384 * Enables or disables automatic generation of <option>--help</option>
385 * output. By default, g_option_context_parse() recognizes
386 * <option>--help</option>, <option>-h</option>,
387 * <option>-?</option>, <option>--help-all</option>
388 * and <option>--help-</option><replaceable>groupname</replaceable> and creates
389 * suitable output to stdout.
391 * Since: 2.6
393 void g_option_context_set_help_enabled (GOptionContext *context,
394 gboolean help_enabled)
397 g_return_if_fail (context != NULL);
399 context->help_enabled = help_enabled;
403 * g_option_context_get_help_enabled:
404 * @context: a #GOptionContext
406 * Returns whether automatic <option>--help</option> generation
407 * is turned on for @context. See g_option_context_set_help_enabled().
409 * Returns: %TRUE if automatic help generation is turned on.
411 * Since: 2.6
413 gboolean
414 g_option_context_get_help_enabled (GOptionContext *context)
416 g_return_val_if_fail (context != NULL, FALSE);
418 return context->help_enabled;
422 * g_option_context_set_ignore_unknown_options:
423 * @context: a #GOptionContext
424 * @ignore_unknown: %TRUE to ignore unknown options, %FALSE to produce
425 * an error when unknown options are met
427 * Sets whether to ignore unknown options or not. If an argument is
428 * ignored, it is left in the @argv array after parsing. By default,
429 * g_option_context_parse() treats unknown options as error.
431 * This setting does not affect non-option arguments (i.e. arguments
432 * which don't start with a dash). But note that GOption cannot reliably
433 * determine whether a non-option belongs to a preceding unknown option.
435 * Since: 2.6
437 void
438 g_option_context_set_ignore_unknown_options (GOptionContext *context,
439 gboolean ignore_unknown)
441 g_return_if_fail (context != NULL);
443 context->ignore_unknown = ignore_unknown;
447 * g_option_context_get_ignore_unknown_options:
448 * @context: a #GOptionContext
450 * Returns whether unknown options are ignored or not. See
451 * g_option_context_set_ignore_unknown_options().
453 * Returns: %TRUE if unknown options are ignored.
455 * Since: 2.6
457 gboolean
458 g_option_context_get_ignore_unknown_options (GOptionContext *context)
460 g_return_val_if_fail (context != NULL, FALSE);
462 return context->ignore_unknown;
466 * g_option_context_add_group:
467 * @context: a #GOptionContext
468 * @group: the group to add
470 * Adds a #GOptionGroup to the @context, so that parsing with @context
471 * will recognize the options in the group. Note that the group will
472 * be freed together with the context when g_option_context_free() is
473 * called, so you must not free the group yourself after adding it
474 * to a context.
476 * Since: 2.6
478 void
479 g_option_context_add_group (GOptionContext *context,
480 GOptionGroup *group)
482 GList *list;
484 g_return_if_fail (context != NULL);
485 g_return_if_fail (group != NULL);
486 g_return_if_fail (group->name != NULL);
487 g_return_if_fail (group->description != NULL);
488 g_return_if_fail (group->help_description != NULL);
490 for (list = context->groups; list; list = list->next)
492 GOptionGroup *g = (GOptionGroup *)list->data;
494 if ((group->name == NULL && g->name == NULL) ||
495 (group->name && g->name && strcmp (group->name, g->name) == 0))
496 g_warning ("A group named \"%s\" is already part of this GOptionContext",
497 group->name);
500 context->groups = g_list_append (context->groups, group);
504 * g_option_context_set_main_group:
505 * @context: a #GOptionContext
506 * @group: the group to set as main group
508 * Sets a #GOptionGroup as main group of the @context.
509 * This has the same effect as calling g_option_context_add_group(),
510 * the only difference is that the options in the main group are
511 * treated differently when generating <option>--help</option> output.
513 * Since: 2.6
515 void
516 g_option_context_set_main_group (GOptionContext *context,
517 GOptionGroup *group)
519 g_return_if_fail (context != NULL);
520 g_return_if_fail (group != NULL);
522 if (context->main_group)
524 g_warning ("This GOptionContext already has a main group");
526 return;
529 context->main_group = group;
533 * g_option_context_get_main_group:
534 * @context: a #GOptionContext
536 * Returns a pointer to the main group of @context.
538 * Return value: the main group of @context, or %NULL if @context doesn't
539 * have a main group. Note that group belongs to @context and should
540 * not be modified or freed.
542 * Since: 2.6
544 GOptionGroup *
545 g_option_context_get_main_group (GOptionContext *context)
547 g_return_val_if_fail (context != NULL, NULL);
549 return context->main_group;
553 * g_option_context_add_main_entries:
554 * @context: a #GOptionContext
555 * @entries: a %NULL-terminated array of #GOptionEntry<!-- -->s
556 * @translation_domain: a translation domain to use for translating
557 * the <option>--help</option> output for the options in @entries
558 * with gettext(), or %NULL
560 * A convenience function which creates a main group if it doesn't
561 * exist, adds the @entries to it and sets the translation domain.
563 * Since: 2.6
565 void
566 g_option_context_add_main_entries (GOptionContext *context,
567 const GOptionEntry *entries,
568 const gchar *translation_domain)
570 g_return_if_fail (entries != NULL);
572 if (!context->main_group)
573 context->main_group = g_option_group_new (NULL, NULL, NULL, NULL, NULL);
575 g_option_group_add_entries (context->main_group, entries);
576 g_option_group_set_translation_domain (context->main_group, translation_domain);
579 static gint
580 calculate_max_length (GOptionGroup *group)
582 GOptionEntry *entry;
583 gint i, len, max_length;
585 max_length = 0;
587 for (i = 0; i < group->n_entries; i++)
589 entry = &group->entries[i];
591 if (entry->flags & G_OPTION_FLAG_HIDDEN)
592 continue;
594 len = _g_utf8_strwidth (entry->long_name, -1);
596 if (entry->short_name)
597 len += 4;
599 if (!NO_ARG (entry) && entry->arg_description)
600 len += 1 + _g_utf8_strwidth (TRANSLATE (group, entry->arg_description), -1);
602 max_length = MAX (max_length, len);
605 return max_length;
608 static void
609 print_entry (GOptionGroup *group,
610 gint max_length,
611 const GOptionEntry *entry,
612 GString *string)
614 GString *str;
616 if (entry->flags & G_OPTION_FLAG_HIDDEN)
617 return;
619 if (entry->long_name[0] == 0)
620 return;
622 str = g_string_new (NULL);
624 if (entry->short_name)
625 g_string_append_printf (str, " -%c, --%s", entry->short_name, entry->long_name);
626 else
627 g_string_append_printf (str, " --%s", entry->long_name);
629 if (entry->arg_description)
630 g_string_append_printf (str, "=%s", TRANSLATE (group, entry->arg_description));
632 g_string_append_printf (string, "%s%*s %s\n", str->str,
633 (int) (max_length + 4 - _g_utf8_strwidth (str->str, -1)), "",
634 entry->description ? TRANSLATE (group, entry->description) : "");
635 g_string_free (str, TRUE);
638 static gboolean
639 group_has_visible_entries (GOptionContext *context,
640 GOptionGroup *group,
641 gboolean main_entries)
643 GOptionFlags reject_filter = G_OPTION_FLAG_HIDDEN;
644 GOptionEntry *entry;
645 gint i, l;
646 gboolean main_group = group == context->main_group;
648 if (!main_entries)
649 reject_filter |= G_OPTION_FLAG_IN_MAIN;
651 for (i = 0, l = (group ? group->n_entries : 0); i < l; i++)
653 entry = &group->entries[i];
655 if (main_entries && !main_group && !(entry->flags & G_OPTION_FLAG_IN_MAIN))
656 continue;
657 if (!(entry->flags & reject_filter))
658 return TRUE;
661 return FALSE;
664 static gboolean
665 group_list_has_visible_entires (GOptionContext *context,
666 GList *group_list,
667 gboolean main_entries)
669 while (group_list)
671 if (group_has_visible_entries (context, group_list->data, main_entries))
672 return TRUE;
674 group_list = group_list->next;
677 return FALSE;
680 static gboolean
681 context_has_h_entry (GOptionContext *context)
683 gsize i;
684 GList *list;
686 if (context->main_group)
688 for (i = 0; i < context->main_group->n_entries; i++)
690 if (context->main_group->entries[i].short_name == 'h')
691 return TRUE;
695 for (list = context->groups; list != NULL; list = g_list_next (list))
697 GOptionGroup *group;
699 group = (GOptionGroup*)list->data;
700 for (i = 0; i < group->n_entries; i++)
702 if (group->entries[i].short_name == 'h')
703 return TRUE;
706 return FALSE;
710 * g_option_context_get_help:
711 * @context: a #GOptionContext
712 * @main_help: if %TRUE, only include the main group
713 * @group: the #GOptionGroup to create help for, or %NULL
715 * Returns a formatted, translated help text for the given context.
716 * To obtain the text produced by <option>--help</option>, call
717 * <literal>g_option_context_get_help (context, TRUE, NULL)</literal>.
718 * To obtain the text produced by <option>--help-all</option>, call
719 * <literal>g_option_context_get_help (context, FALSE, NULL)</literal>.
720 * To obtain the help text for an option group, call
721 * <literal>g_option_context_get_help (context, FALSE, group)</literal>.
723 * Returns: A newly allocated string containing the help text
725 * Since: 2.14
727 gchar *
728 g_option_context_get_help (GOptionContext *context,
729 gboolean main_help,
730 GOptionGroup *group)
732 GList *list;
733 gint max_length, len;
734 gint i;
735 GOptionEntry *entry;
736 GHashTable *shadow_map;
737 gboolean seen[256];
738 const gchar *rest_description;
739 GString *string;
740 guchar token;
742 string = g_string_sized_new (1024);
744 rest_description = NULL;
745 if (context->main_group)
748 for (i = 0; i < context->main_group->n_entries; i++)
750 entry = &context->main_group->entries[i];
751 if (entry->long_name[0] == 0)
753 rest_description = TRANSLATE (context->main_group, entry->arg_description);
754 break;
759 g_string_append_printf (string, "%s\n %s %s",
760 _("Usage:"), g_get_prgname(), _("[OPTION...]"));
762 if (rest_description)
764 g_string_append (string, " ");
765 g_string_append (string, rest_description);
768 if (context->parameter_string)
770 g_string_append (string, " ");
771 g_string_append (string, TRANSLATE (context, context->parameter_string));
774 g_string_append (string, "\n\n");
776 if (context->summary)
778 g_string_append (string, TRANSLATE (context, context->summary));
779 g_string_append (string, "\n\n");
782 memset (seen, 0, sizeof (gboolean) * 256);
783 shadow_map = g_hash_table_new (g_str_hash, g_str_equal);
785 if (context->main_group)
787 for (i = 0; i < context->main_group->n_entries; i++)
789 entry = &context->main_group->entries[i];
790 g_hash_table_insert (shadow_map,
791 (gpointer)entry->long_name,
792 entry);
794 if (seen[(guchar)entry->short_name])
795 entry->short_name = 0;
796 else
797 seen[(guchar)entry->short_name] = TRUE;
801 list = context->groups;
802 while (list != NULL)
804 GOptionGroup *g = list->data;
805 for (i = 0; i < g->n_entries; i++)
807 entry = &g->entries[i];
808 if (g_hash_table_lookup (shadow_map, entry->long_name) &&
809 !(entry->flags & G_OPTION_FLAG_NOALIAS))
810 entry->long_name = g_strdup_printf ("%s-%s", g->name, entry->long_name);
811 else
812 g_hash_table_insert (shadow_map, (gpointer)entry->long_name, entry);
814 if (seen[(guchar)entry->short_name] &&
815 !(entry->flags & G_OPTION_FLAG_NOALIAS))
816 entry->short_name = 0;
817 else
818 seen[(guchar)entry->short_name] = TRUE;
820 list = list->next;
823 g_hash_table_destroy (shadow_map);
825 list = context->groups;
827 max_length = _g_utf8_strwidth ("-?, --help", -1);
829 if (list)
831 len = _g_utf8_strwidth ("--help-all", -1);
832 max_length = MAX (max_length, len);
835 if (context->main_group)
837 len = calculate_max_length (context->main_group);
838 max_length = MAX (max_length, len);
841 while (list != NULL)
843 GOptionGroup *g = list->data;
845 /* First, we check the --help-<groupname> options */
846 len = _g_utf8_strwidth ("--help-", -1) + _g_utf8_strwidth (g->name, -1);
847 max_length = MAX (max_length, len);
849 /* Then we go through the entries */
850 len = calculate_max_length (g);
851 max_length = MAX (max_length, len);
853 list = list->next;
856 /* Add a bit of padding */
857 max_length += 4;
859 if (!group)
861 list = context->groups;
863 token = context_has_h_entry (context) ? '?' : 'h';
865 g_string_append_printf (string, "%s\n -%c, --%-*s %s\n",
866 _("Help Options:"), token, max_length - 4, "help",
867 _("Show help options"));
869 /* We only want --help-all when there are groups */
870 if (list)
871 g_string_append_printf (string, " --%-*s %s\n",
872 max_length, "help-all",
873 _("Show all help options"));
875 while (list)
877 GOptionGroup *g = list->data;
879 if (group_has_visible_entries (context, g, FALSE))
880 g_string_append_printf (string, " --help-%-*s %s\n",
881 max_length - 5, g->name,
882 TRANSLATE (g, g->help_description));
884 list = list->next;
887 g_string_append (string, "\n");
890 if (group)
892 /* Print a certain group */
894 if (group_has_visible_entries (context, group, FALSE))
896 g_string_append (string, TRANSLATE (group, group->description));
897 g_string_append (string, "\n");
898 for (i = 0; i < group->n_entries; i++)
899 print_entry (group, max_length, &group->entries[i], string);
900 g_string_append (string, "\n");
903 else if (!main_help)
905 /* Print all groups */
907 list = context->groups;
909 while (list)
911 GOptionGroup *g = list->data;
913 if (group_has_visible_entries (context, g, FALSE))
915 g_string_append (string, g->description);
916 g_string_append (string, "\n");
917 for (i = 0; i < g->n_entries; i++)
918 if (!(g->entries[i].flags & G_OPTION_FLAG_IN_MAIN))
919 print_entry (g, max_length, &g->entries[i], string);
921 g_string_append (string, "\n");
924 list = list->next;
928 /* Print application options if --help or --help-all has been specified */
929 if ((main_help || !group) &&
930 (group_has_visible_entries (context, context->main_group, TRUE) ||
931 group_list_has_visible_entires (context, context->groups, TRUE)))
933 list = context->groups;
935 g_string_append (string, _("Application Options:"));
936 g_string_append (string, "\n");
937 if (context->main_group)
938 for (i = 0; i < context->main_group->n_entries; i++)
939 print_entry (context->main_group, max_length,
940 &context->main_group->entries[i], string);
942 while (list != NULL)
944 GOptionGroup *g = list->data;
946 /* Print main entries from other groups */
947 for (i = 0; i < g->n_entries; i++)
948 if (g->entries[i].flags & G_OPTION_FLAG_IN_MAIN)
949 print_entry (g, max_length, &g->entries[i], string);
951 list = list->next;
954 g_string_append (string, "\n");
957 if (context->description)
959 g_string_append (string, TRANSLATE (context, context->description));
960 g_string_append (string, "\n");
963 return g_string_free (string, FALSE);
966 G_GNUC_NORETURN
967 static void
968 print_help (GOptionContext *context,
969 gboolean main_help,
970 GOptionGroup *group)
972 gchar *help;
974 help = g_option_context_get_help (context, main_help, group);
975 g_print ("%s", help);
976 g_free (help);
978 exit (0);
981 static gboolean
982 parse_int (const gchar *arg_name,
983 const gchar *arg,
984 gint *result,
985 GError **error)
987 gchar *end;
988 glong tmp;
990 errno = 0;
991 tmp = strtol (arg, &end, 0);
993 if (*arg == '\0' || *end != '\0')
995 g_set_error (error,
996 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
997 _("Cannot parse integer value '%s' for %s"),
998 arg, arg_name);
999 return FALSE;
1002 *result = tmp;
1003 if (*result != tmp || errno == ERANGE)
1005 g_set_error (error,
1006 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1007 _("Integer value '%s' for %s out of range"),
1008 arg, arg_name);
1009 return FALSE;
1012 return TRUE;
1016 static gboolean
1017 parse_double (const gchar *arg_name,
1018 const gchar *arg,
1019 gdouble *result,
1020 GError **error)
1022 gchar *end;
1023 gdouble tmp;
1025 errno = 0;
1026 tmp = g_strtod (arg, &end);
1028 if (*arg == '\0' || *end != '\0')
1030 g_set_error (error,
1031 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1032 _("Cannot parse double value '%s' for %s"),
1033 arg, arg_name);
1034 return FALSE;
1036 if (errno == ERANGE)
1038 g_set_error (error,
1039 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1040 _("Double value '%s' for %s out of range"),
1041 arg, arg_name);
1042 return FALSE;
1045 *result = tmp;
1047 return TRUE;
1051 static gboolean
1052 parse_int64 (const gchar *arg_name,
1053 const gchar *arg,
1054 gint64 *result,
1055 GError **error)
1057 gchar *end;
1058 gint64 tmp;
1060 errno = 0;
1061 tmp = g_ascii_strtoll (arg, &end, 0);
1063 if (*arg == '\0' || *end != '\0')
1065 g_set_error (error,
1066 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1067 _("Cannot parse integer value '%s' for %s"),
1068 arg, arg_name);
1069 return FALSE;
1071 if (errno == ERANGE)
1073 g_set_error (error,
1074 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1075 _("Integer value '%s' for %s out of range"),
1076 arg, arg_name);
1077 return FALSE;
1080 *result = tmp;
1082 return TRUE;
1086 static Change *
1087 get_change (GOptionContext *context,
1088 GOptionArg arg_type,
1089 gpointer arg_data)
1091 GList *list;
1092 Change *change = NULL;
1094 for (list = context->changes; list != NULL; list = list->next)
1096 change = list->data;
1098 if (change->arg_data == arg_data)
1099 goto found;
1102 change = g_new0 (Change, 1);
1103 change->arg_type = arg_type;
1104 change->arg_data = arg_data;
1106 context->changes = g_list_prepend (context->changes, change);
1108 found:
1110 return change;
1113 static void
1114 add_pending_null (GOptionContext *context,
1115 gchar **ptr,
1116 gchar *value)
1118 PendingNull *n;
1120 n = g_new0 (PendingNull, 1);
1121 n->ptr = ptr;
1122 n->value = value;
1124 context->pending_nulls = g_list_prepend (context->pending_nulls, n);
1127 static gboolean
1128 parse_arg (GOptionContext *context,
1129 GOptionGroup *group,
1130 GOptionEntry *entry,
1131 const gchar *value,
1132 const gchar *option_name,
1133 GError **error)
1136 Change *change;
1138 g_assert (value || OPTIONAL_ARG (entry) || NO_ARG (entry));
1140 switch (entry->arg)
1142 case G_OPTION_ARG_NONE:
1144 change = get_change (context, G_OPTION_ARG_NONE,
1145 entry->arg_data);
1147 *(gboolean *)entry->arg_data = !(entry->flags & G_OPTION_FLAG_REVERSE);
1148 break;
1150 case G_OPTION_ARG_STRING:
1152 gchar *data;
1154 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1156 if (!data)
1157 return FALSE;
1159 change = get_change (context, G_OPTION_ARG_STRING,
1160 entry->arg_data);
1161 g_free (change->allocated.str);
1163 change->prev.str = *(gchar **)entry->arg_data;
1164 change->allocated.str = data;
1166 *(gchar **)entry->arg_data = data;
1167 break;
1169 case G_OPTION_ARG_STRING_ARRAY:
1171 gchar *data;
1173 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1175 if (!data)
1176 return FALSE;
1178 change = get_change (context, G_OPTION_ARG_STRING_ARRAY,
1179 entry->arg_data);
1181 if (change->allocated.array.len == 0)
1183 change->prev.array = *(gchar ***)entry->arg_data;
1184 change->allocated.array.data = g_new (gchar *, 2);
1186 else
1187 change->allocated.array.data =
1188 g_renew (gchar *, change->allocated.array.data,
1189 change->allocated.array.len + 2);
1191 change->allocated.array.data[change->allocated.array.len] = data;
1192 change->allocated.array.data[change->allocated.array.len + 1] = NULL;
1194 change->allocated.array.len ++;
1196 *(gchar ***)entry->arg_data = change->allocated.array.data;
1198 break;
1201 case G_OPTION_ARG_FILENAME:
1203 gchar *data;
1205 #ifdef G_OS_WIN32
1206 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1208 if (!data)
1209 return FALSE;
1210 #else
1211 data = g_strdup (value);
1212 #endif
1213 change = get_change (context, G_OPTION_ARG_FILENAME,
1214 entry->arg_data);
1215 g_free (change->allocated.str);
1217 change->prev.str = *(gchar **)entry->arg_data;
1218 change->allocated.str = data;
1220 *(gchar **)entry->arg_data = data;
1221 break;
1224 case G_OPTION_ARG_FILENAME_ARRAY:
1226 gchar *data;
1228 #ifdef G_OS_WIN32
1229 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1231 if (!data)
1232 return FALSE;
1233 #else
1234 data = g_strdup (value);
1235 #endif
1236 change = get_change (context, G_OPTION_ARG_STRING_ARRAY,
1237 entry->arg_data);
1239 if (change->allocated.array.len == 0)
1241 change->prev.array = *(gchar ***)entry->arg_data;
1242 change->allocated.array.data = g_new (gchar *, 2);
1244 else
1245 change->allocated.array.data =
1246 g_renew (gchar *, change->allocated.array.data,
1247 change->allocated.array.len + 2);
1249 change->allocated.array.data[change->allocated.array.len] = data;
1250 change->allocated.array.data[change->allocated.array.len + 1] = NULL;
1252 change->allocated.array.len ++;
1254 *(gchar ***)entry->arg_data = change->allocated.array.data;
1256 break;
1259 case G_OPTION_ARG_INT:
1261 gint data;
1263 if (!parse_int (option_name, value,
1264 &data,
1265 error))
1266 return FALSE;
1268 change = get_change (context, G_OPTION_ARG_INT,
1269 entry->arg_data);
1270 change->prev.integer = *(gint *)entry->arg_data;
1271 *(gint *)entry->arg_data = data;
1272 break;
1274 case G_OPTION_ARG_CALLBACK:
1276 gchar *data;
1277 gboolean retval;
1279 if (!value && entry->flags & G_OPTION_FLAG_OPTIONAL_ARG)
1280 data = NULL;
1281 else if (entry->flags & G_OPTION_FLAG_NO_ARG)
1282 data = NULL;
1283 else if (entry->flags & G_OPTION_FLAG_FILENAME)
1285 #ifdef G_OS_WIN32
1286 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1287 #else
1288 data = g_strdup (value);
1289 #endif
1291 else
1292 data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1294 if (!(entry->flags & (G_OPTION_FLAG_NO_ARG|G_OPTION_FLAG_OPTIONAL_ARG)) &&
1295 !data)
1296 return FALSE;
1298 retval = (* (GOptionArgFunc) entry->arg_data) (option_name, data, group->user_data, error);
1300 if (!retval && error != NULL && *error == NULL)
1301 g_set_error (error,
1302 G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
1303 _("Error parsing option %s"), option_name);
1305 g_free (data);
1307 return retval;
1309 break;
1311 case G_OPTION_ARG_DOUBLE:
1313 gdouble data;
1315 if (!parse_double (option_name, value,
1316 &data,
1317 error))
1319 return FALSE;
1322 change = get_change (context, G_OPTION_ARG_DOUBLE,
1323 entry->arg_data);
1324 change->prev.dbl = *(gdouble *)entry->arg_data;
1325 *(gdouble *)entry->arg_data = data;
1326 break;
1328 case G_OPTION_ARG_INT64:
1330 gint64 data;
1332 if (!parse_int64 (option_name, value,
1333 &data,
1334 error))
1336 return FALSE;
1339 change = get_change (context, G_OPTION_ARG_INT64,
1340 entry->arg_data);
1341 change->prev.int64 = *(gint64 *)entry->arg_data;
1342 *(gint64 *)entry->arg_data = data;
1343 break;
1345 default:
1346 g_assert_not_reached ();
1349 return TRUE;
1352 static gboolean
1353 parse_short_option (GOptionContext *context,
1354 GOptionGroup *group,
1355 gint idx,
1356 gint *new_idx,
1357 gchar arg,
1358 gint *argc,
1359 gchar ***argv,
1360 GError **error,
1361 gboolean *parsed)
1363 gint j;
1365 for (j = 0; j < group->n_entries; j++)
1367 if (arg == group->entries[j].short_name)
1369 gchar *option_name;
1370 gchar *value = NULL;
1372 option_name = g_strdup_printf ("-%c", group->entries[j].short_name);
1374 if (NO_ARG (&group->entries[j]))
1375 value = NULL;
1376 else
1378 if (*new_idx > idx)
1380 g_set_error (error,
1381 G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
1382 _("Error parsing option %s"), option_name);
1383 g_free (option_name);
1384 return FALSE;
1387 if (idx < *argc - 1)
1389 if (!OPTIONAL_ARG (&group->entries[j]))
1391 value = (*argv)[idx + 1];
1392 add_pending_null (context, &((*argv)[idx + 1]), NULL);
1393 *new_idx = idx + 1;
1395 else
1397 if ((*argv)[idx + 1][0] == '-')
1398 value = NULL;
1399 else
1401 value = (*argv)[idx + 1];
1402 add_pending_null (context, &((*argv)[idx + 1]), NULL);
1403 *new_idx = idx + 1;
1407 else if (idx >= *argc - 1 && OPTIONAL_ARG (&group->entries[j]))
1408 value = NULL;
1409 else
1411 g_set_error (error,
1412 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1413 _("Missing argument for %s"), option_name);
1414 g_free (option_name);
1415 return FALSE;
1419 if (!parse_arg (context, group, &group->entries[j],
1420 value, option_name, error))
1422 g_free (option_name);
1423 return FALSE;
1426 g_free (option_name);
1427 *parsed = TRUE;
1431 return TRUE;
1434 static gboolean
1435 parse_long_option (GOptionContext *context,
1436 GOptionGroup *group,
1437 gint *idx,
1438 gchar *arg,
1439 gboolean aliased,
1440 gint *argc,
1441 gchar ***argv,
1442 GError **error,
1443 gboolean *parsed)
1445 gint j;
1447 for (j = 0; j < group->n_entries; j++)
1449 if (*idx >= *argc)
1450 return TRUE;
1452 if (aliased && (group->entries[j].flags & G_OPTION_FLAG_NOALIAS))
1453 continue;
1455 if (NO_ARG (&group->entries[j]) &&
1456 strcmp (arg, group->entries[j].long_name) == 0)
1458 gchar *option_name;
1459 gboolean retval;
1461 option_name = g_strconcat ("--", group->entries[j].long_name, NULL);
1462 retval = parse_arg (context, group, &group->entries[j],
1463 NULL, option_name, error);
1464 g_free (option_name);
1466 add_pending_null (context, &((*argv)[*idx]), NULL);
1467 *parsed = TRUE;
1469 return retval;
1471 else
1473 gint len = strlen (group->entries[j].long_name);
1475 if (strncmp (arg, group->entries[j].long_name, len) == 0 &&
1476 (arg[len] == '=' || arg[len] == 0))
1478 gchar *value = NULL;
1479 gchar *option_name;
1481 add_pending_null (context, &((*argv)[*idx]), NULL);
1482 option_name = g_strconcat ("--", group->entries[j].long_name, NULL);
1484 if (arg[len] == '=')
1485 value = arg + len + 1;
1486 else if (*idx < *argc - 1)
1488 if (!OPTIONAL_ARG (&group->entries[j]))
1490 value = (*argv)[*idx + 1];
1491 add_pending_null (context, &((*argv)[*idx + 1]), NULL);
1492 (*idx)++;
1494 else
1496 if ((*argv)[*idx + 1][0] == '-')
1498 gboolean retval;
1499 retval = parse_arg (context, group, &group->entries[j],
1500 NULL, option_name, error);
1501 *parsed = TRUE;
1502 g_free (option_name);
1503 return retval;
1505 else
1507 value = (*argv)[*idx + 1];
1508 add_pending_null (context, &((*argv)[*idx + 1]), NULL);
1509 (*idx)++;
1513 else if (*idx >= *argc - 1 && OPTIONAL_ARG (&group->entries[j]))
1515 gboolean retval;
1516 retval = parse_arg (context, group, &group->entries[j],
1517 NULL, option_name, error);
1518 *parsed = TRUE;
1519 g_free (option_name);
1520 return retval;
1522 else
1524 g_set_error (error,
1525 G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1526 _("Missing argument for %s"), option_name);
1527 g_free (option_name);
1528 return FALSE;
1531 if (!parse_arg (context, group, &group->entries[j],
1532 value, option_name, error))
1534 g_free (option_name);
1535 return FALSE;
1538 g_free (option_name);
1539 *parsed = TRUE;
1544 return TRUE;
1547 static gboolean
1548 parse_remaining_arg (GOptionContext *context,
1549 GOptionGroup *group,
1550 gint *idx,
1551 gint *argc,
1552 gchar ***argv,
1553 GError **error,
1554 gboolean *parsed)
1556 gint j;
1558 for (j = 0; j < group->n_entries; j++)
1560 if (*idx >= *argc)
1561 return TRUE;
1563 if (group->entries[j].long_name[0])
1564 continue;
1566 g_return_val_if_fail (group->entries[j].arg == G_OPTION_ARG_CALLBACK ||
1567 group->entries[j].arg == G_OPTION_ARG_STRING_ARRAY ||
1568 group->entries[j].arg == G_OPTION_ARG_FILENAME_ARRAY, FALSE);
1570 add_pending_null (context, &((*argv)[*idx]), NULL);
1572 if (!parse_arg (context, group, &group->entries[j], (*argv)[*idx], "", error))
1573 return FALSE;
1575 *parsed = TRUE;
1576 return TRUE;
1579 return TRUE;
1582 static void
1583 free_changes_list (GOptionContext *context,
1584 gboolean revert)
1586 GList *list;
1588 for (list = context->changes; list != NULL; list = list->next)
1590 Change *change = list->data;
1592 if (revert)
1594 switch (change->arg_type)
1596 case G_OPTION_ARG_NONE:
1597 *(gboolean *)change->arg_data = change->prev.bool;
1598 break;
1599 case G_OPTION_ARG_INT:
1600 *(gint *)change->arg_data = change->prev.integer;
1601 break;
1602 case G_OPTION_ARG_STRING:
1603 case G_OPTION_ARG_FILENAME:
1604 g_free (change->allocated.str);
1605 *(gchar **)change->arg_data = change->prev.str;
1606 break;
1607 case G_OPTION_ARG_STRING_ARRAY:
1608 case G_OPTION_ARG_FILENAME_ARRAY:
1609 g_strfreev (change->allocated.array.data);
1610 *(gchar ***)change->arg_data = change->prev.array;
1611 break;
1612 case G_OPTION_ARG_DOUBLE:
1613 *(gdouble *)change->arg_data = change->prev.dbl;
1614 break;
1615 case G_OPTION_ARG_INT64:
1616 *(gint64 *)change->arg_data = change->prev.int64;
1617 break;
1618 default:
1619 g_assert_not_reached ();
1623 g_free (change);
1626 g_list_free (context->changes);
1627 context->changes = NULL;
1630 static void
1631 free_pending_nulls (GOptionContext *context,
1632 gboolean perform_nulls)
1634 GList *list;
1636 for (list = context->pending_nulls; list != NULL; list = list->next)
1638 PendingNull *n = list->data;
1640 if (perform_nulls)
1642 if (n->value)
1644 /* Copy back the short options */
1645 *(n->ptr)[0] = '-';
1646 strcpy (*n->ptr + 1, n->value);
1648 else
1649 *n->ptr = NULL;
1652 g_free (n->value);
1653 g_free (n);
1656 g_list_free (context->pending_nulls);
1657 context->pending_nulls = NULL;
1660 /* Use a platform-specific mechanism to look up the first argument to
1661 * the current process.
1662 * Note if you implement this for other platforms, also add it to
1663 * tests/option-argv0.c
1665 static char *
1666 platform_get_argv0 (void)
1668 #ifdef __linux
1669 char *cmdline;
1670 char *base_arg0;
1671 gsize len;
1673 if (!g_file_get_contents ("/proc/self/cmdline",
1674 &cmdline,
1675 &len,
1676 NULL))
1677 return NULL;
1678 /* Sanity check for a NUL terminator. */
1679 if (!memchr (cmdline, 0, len))
1680 return NULL;
1681 /* We could just return cmdline, but I think it's better
1682 * to hold on to a smaller malloc block; the arguments
1683 * could be large.
1685 base_arg0 = g_path_get_basename (cmdline);
1686 g_free (cmdline);
1687 return base_arg0;
1688 #endif
1690 return NULL;
1694 * g_option_context_parse:
1695 * @context: a #GOptionContext
1696 * @argc: a pointer to the number of command line arguments
1697 * @argv: a pointer to the array of command line arguments
1698 * @error: a return location for errors
1700 * Parses the command line arguments, recognizing options
1701 * which have been added to @context. A side-effect of
1702 * calling this function is that g_set_prgname() will be
1703 * called.
1705 * If the parsing is successful, any parsed arguments are
1706 * removed from the array and @argc and @argv are updated
1707 * accordingly. A '--' option is stripped from @argv
1708 * unless there are unparsed options before and after it,
1709 * or some of the options after it start with '-'. In case
1710 * of an error, @argc and @argv are left unmodified.
1712 * If automatic <option>--help</option> support is enabled
1713 * (see g_option_context_set_help_enabled()), and the
1714 * @argv array contains one of the recognized help options,
1715 * this function will produce help output to stdout and
1716 * call <literal>exit (0)</literal>.
1718 * Note that function depends on the
1719 * <link linkend="setlocale">current locale</link> for
1720 * automatic character set conversion of string and filename
1721 * arguments.
1723 * Return value: %TRUE if the parsing was successful,
1724 * %FALSE if an error occurred
1726 * Since: 2.6
1728 gboolean
1729 g_option_context_parse (GOptionContext *context,
1730 gint *argc,
1731 gchar ***argv,
1732 GError **error)
1734 gint i, j, k;
1735 GList *list;
1737 /* Set program name */
1738 if (!g_get_prgname())
1740 gchar *prgname;
1742 if (argc && argv && *argc)
1743 prgname = g_path_get_basename ((*argv)[0]);
1744 else
1745 prgname = platform_get_argv0 ();
1747 if (prgname)
1748 g_set_prgname (prgname);
1749 else
1750 g_set_prgname ("<unknown>");
1752 g_free (prgname);
1755 /* Call pre-parse hooks */
1756 list = context->groups;
1757 while (list)
1759 GOptionGroup *group = list->data;
1761 if (group->pre_parse_func)
1763 if (!(* group->pre_parse_func) (context, group,
1764 group->user_data, error))
1765 goto fail;
1768 list = list->next;
1771 if (context->main_group && context->main_group->pre_parse_func)
1773 if (!(* context->main_group->pre_parse_func) (context, context->main_group,
1774 context->main_group->user_data, error))
1775 goto fail;
1778 if (argc && argv)
1780 gboolean stop_parsing = FALSE;
1781 gboolean has_unknown = FALSE;
1782 gint separator_pos = 0;
1784 for (i = 1; i < *argc; i++)
1786 gchar *arg, *dash;
1787 gboolean parsed = FALSE;
1789 if ((*argv)[i][0] == '-' && (*argv)[i][1] != '\0' && !stop_parsing)
1791 if ((*argv)[i][1] == '-')
1793 /* -- option */
1795 arg = (*argv)[i] + 2;
1797 /* '--' terminates list of arguments */
1798 if (*arg == 0)
1800 separator_pos = i;
1801 stop_parsing = TRUE;
1802 continue;
1805 /* Handle help options */
1806 if (context->help_enabled)
1808 if (strcmp (arg, "help") == 0)
1809 print_help (context, TRUE, NULL);
1810 else if (strcmp (arg, "help-all") == 0)
1811 print_help (context, FALSE, NULL);
1812 else if (strncmp (arg, "help-", 5) == 0)
1814 list = context->groups;
1816 while (list)
1818 GOptionGroup *group = list->data;
1820 if (strcmp (arg + 5, group->name) == 0)
1821 print_help (context, FALSE, group);
1823 list = list->next;
1828 if (context->main_group &&
1829 !parse_long_option (context, context->main_group, &i, arg,
1830 FALSE, argc, argv, error, &parsed))
1831 goto fail;
1833 if (parsed)
1834 continue;
1836 /* Try the groups */
1837 list = context->groups;
1838 while (list)
1840 GOptionGroup *group = list->data;
1842 if (!parse_long_option (context, group, &i, arg,
1843 FALSE, argc, argv, error, &parsed))
1844 goto fail;
1846 if (parsed)
1847 break;
1849 list = list->next;
1852 if (parsed)
1853 continue;
1855 /* Now look for --<group>-<option> */
1856 dash = strchr (arg, '-');
1857 if (dash)
1859 /* Try the groups */
1860 list = context->groups;
1861 while (list)
1863 GOptionGroup *group = list->data;
1865 if (strncmp (group->name, arg, dash - arg) == 0)
1867 if (!parse_long_option (context, group, &i, dash + 1,
1868 TRUE, argc, argv, error, &parsed))
1869 goto fail;
1871 if (parsed)
1872 break;
1875 list = list->next;
1879 if (context->ignore_unknown)
1880 continue;
1882 else
1883 { /* short option */
1884 gint new_i = i, arg_length;
1885 gboolean *nulled_out = NULL;
1886 gboolean has_h_entry = context_has_h_entry (context);
1887 arg = (*argv)[i] + 1;
1888 arg_length = strlen (arg);
1889 nulled_out = g_newa (gboolean, arg_length);
1890 memset (nulled_out, 0, arg_length * sizeof (gboolean));
1891 for (j = 0; j < arg_length; j++)
1893 if (context->help_enabled && (arg[j] == '?' ||
1894 (arg[j] == 'h' && !has_h_entry)))
1895 print_help (context, TRUE, NULL);
1896 parsed = FALSE;
1897 if (context->main_group &&
1898 !parse_short_option (context, context->main_group,
1899 i, &new_i, arg[j],
1900 argc, argv, error, &parsed))
1901 goto fail;
1902 if (!parsed)
1904 /* Try the groups */
1905 list = context->groups;
1906 while (list)
1908 GOptionGroup *group = list->data;
1909 if (!parse_short_option (context, group, i, &new_i, arg[j],
1910 argc, argv, error, &parsed))
1911 goto fail;
1912 if (parsed)
1913 break;
1914 list = list->next;
1918 if (context->ignore_unknown && parsed)
1919 nulled_out[j] = TRUE;
1920 else if (context->ignore_unknown)
1921 continue;
1922 else if (!parsed)
1923 break;
1924 /* !context->ignore_unknown && parsed */
1926 if (context->ignore_unknown)
1928 gchar *new_arg = NULL;
1929 gint arg_index = 0;
1930 for (j = 0; j < arg_length; j++)
1932 if (!nulled_out[j])
1934 if (!new_arg)
1935 new_arg = g_malloc (arg_length + 1);
1936 new_arg[arg_index++] = arg[j];
1939 if (new_arg)
1940 new_arg[arg_index] = '\0';
1941 add_pending_null (context, &((*argv)[i]), new_arg);
1943 else if (parsed)
1945 add_pending_null (context, &((*argv)[i]), NULL);
1946 i = new_i;
1950 if (!parsed)
1951 has_unknown = TRUE;
1953 if (!parsed && !context->ignore_unknown)
1955 g_set_error (error,
1956 G_OPTION_ERROR, G_OPTION_ERROR_UNKNOWN_OPTION,
1957 _("Unknown option %s"), (*argv)[i]);
1958 goto fail;
1961 else
1963 /* Collect remaining args */
1964 if (context->main_group &&
1965 !parse_remaining_arg (context, context->main_group, &i,
1966 argc, argv, error, &parsed))
1967 goto fail;
1969 if (!parsed && (has_unknown || (*argv)[i][0] == '-'))
1970 separator_pos = 0;
1974 if (separator_pos > 0)
1975 add_pending_null (context, &((*argv)[separator_pos]), NULL);
1979 /* Call post-parse hooks */
1980 list = context->groups;
1981 while (list)
1983 GOptionGroup *group = list->data;
1985 if (group->post_parse_func)
1987 if (!(* group->post_parse_func) (context, group,
1988 group->user_data, error))
1989 goto fail;
1992 list = list->next;
1995 if (context->main_group && context->main_group->post_parse_func)
1997 if (!(* context->main_group->post_parse_func) (context, context->main_group,
1998 context->main_group->user_data, error))
1999 goto fail;
2002 if (argc && argv)
2004 free_pending_nulls (context, TRUE);
2006 for (i = 1; i < *argc; i++)
2008 for (k = i; k < *argc; k++)
2009 if ((*argv)[k] != NULL)
2010 break;
2012 if (k > i)
2014 k -= i;
2015 for (j = i + k; j < *argc; j++)
2017 (*argv)[j-k] = (*argv)[j];
2018 (*argv)[j] = NULL;
2020 *argc -= k;
2025 return TRUE;
2027 fail:
2029 /* Call error hooks */
2030 list = context->groups;
2031 while (list)
2033 GOptionGroup *group = list->data;
2035 if (group->error_func)
2036 (* group->error_func) (context, group,
2037 group->user_data, error);
2039 list = list->next;
2042 if (context->main_group && context->main_group->error_func)
2043 (* context->main_group->error_func) (context, context->main_group,
2044 context->main_group->user_data, error);
2046 free_changes_list (context, TRUE);
2047 free_pending_nulls (context, FALSE);
2049 return FALSE;
2053 * g_option_group_new:
2054 * @name: the name for the option group, this is used to provide
2055 * help for the options in this group with <option>--help-</option>@name
2056 * @description: a description for this group to be shown in
2057 * <option>--help</option>. This string is translated using the translation
2058 * domain or translation function of the group
2059 * @help_description: a description for the <option>--help-</option>@name option.
2060 * This string is translated using the translation domain or translation function
2061 * of the group
2062 * @user_data: user data that will be passed to the pre- and post-parse hooks,
2063 * the error hook and to callbacks of %G_OPTION_ARG_CALLBACK options, or %NULL
2064 * @destroy: a function that will be called to free @user_data, or %NULL
2066 * Creates a new #GOptionGroup.
2068 * Return value: a newly created option group. It should be added
2069 * to a #GOptionContext or freed with g_option_group_free().
2071 * Since: 2.6
2073 GOptionGroup *
2074 g_option_group_new (const gchar *name,
2075 const gchar *description,
2076 const gchar *help_description,
2077 gpointer user_data,
2078 GDestroyNotify destroy)
2081 GOptionGroup *group;
2083 group = g_new0 (GOptionGroup, 1);
2084 group->name = g_strdup (name);
2085 group->description = g_strdup (description);
2086 group->help_description = g_strdup (help_description);
2087 group->user_data = user_data;
2088 group->destroy_notify = destroy;
2090 return group;
2095 * g_option_group_free:
2096 * @group: a #GOptionGroup
2098 * Frees a #GOptionGroup. Note that you must <emphasis>not</emphasis>
2099 * free groups which have been added to a #GOptionContext.
2101 * Since: 2.6
2103 void
2104 g_option_group_free (GOptionGroup *group)
2106 g_return_if_fail (group != NULL);
2108 g_free (group->name);
2109 g_free (group->description);
2110 g_free (group->help_description);
2112 g_free (group->entries);
2114 if (group->destroy_notify)
2115 (* group->destroy_notify) (group->user_data);
2117 if (group->translate_notify)
2118 (* group->translate_notify) (group->translate_data);
2120 g_free (group);
2125 * g_option_group_add_entries:
2126 * @group: a #GOptionGroup
2127 * @entries: a %NULL-terminated array of #GOptionEntry<!-- -->s
2129 * Adds the options specified in @entries to @group.
2131 * Since: 2.6
2133 void
2134 g_option_group_add_entries (GOptionGroup *group,
2135 const GOptionEntry *entries)
2137 gint i, n_entries;
2139 g_return_if_fail (entries != NULL);
2141 for (n_entries = 0; entries[n_entries].long_name != NULL; n_entries++) ;
2143 group->entries = g_renew (GOptionEntry, group->entries, group->n_entries + n_entries);
2145 memcpy (group->entries + group->n_entries, entries, sizeof (GOptionEntry) * n_entries);
2147 for (i = group->n_entries; i < group->n_entries + n_entries; i++)
2149 gchar c = group->entries[i].short_name;
2151 if (c == '-' || (c != 0 && !g_ascii_isprint (c)))
2153 g_warning (G_STRLOC ": ignoring invalid short option '%c' (%d)", c, c);
2154 group->entries[i].short_name = 0;
2157 if (group->entries[i].arg != G_OPTION_ARG_NONE &&
2158 (group->entries[i].flags & G_OPTION_FLAG_REVERSE) != 0)
2160 g_warning (G_STRLOC ": ignoring reverse flag on option of type %d", group->entries[i].arg);
2162 group->entries[i].flags &= ~G_OPTION_FLAG_REVERSE;
2165 if (group->entries[i].arg != G_OPTION_ARG_CALLBACK &&
2166 (group->entries[i].flags & (G_OPTION_FLAG_NO_ARG|G_OPTION_FLAG_OPTIONAL_ARG|G_OPTION_FLAG_FILENAME)) != 0)
2168 g_warning (G_STRLOC ": ignoring no-arg, optional-arg or filename flags (%d) on option of type %d", group->entries[i].flags, group->entries[i].arg);
2170 group->entries[i].flags &= ~(G_OPTION_FLAG_NO_ARG|G_OPTION_FLAG_OPTIONAL_ARG|G_OPTION_FLAG_FILENAME);
2174 group->n_entries += n_entries;
2178 * g_option_group_set_parse_hooks:
2179 * @group: a #GOptionGroup
2180 * @pre_parse_func: a function to call before parsing, or %NULL
2181 * @post_parse_func: a function to call after parsing, or %NULL
2183 * Associates two functions with @group which will be called
2184 * from g_option_context_parse() before the first option is parsed
2185 * and after the last option has been parsed, respectively.
2187 * Note that the user data to be passed to @pre_parse_func and
2188 * @post_parse_func can be specified when constructing the group
2189 * with g_option_group_new().
2191 * Since: 2.6
2193 void
2194 g_option_group_set_parse_hooks (GOptionGroup *group,
2195 GOptionParseFunc pre_parse_func,
2196 GOptionParseFunc post_parse_func)
2198 g_return_if_fail (group != NULL);
2200 group->pre_parse_func = pre_parse_func;
2201 group->post_parse_func = post_parse_func;
2205 * g_option_group_set_error_hook:
2206 * @group: a #GOptionGroup
2207 * @error_func: a function to call when an error occurs
2209 * Associates a function with @group which will be called
2210 * from g_option_context_parse() when an error occurs.
2212 * Note that the user data to be passed to @error_func can be
2213 * specified when constructing the group with g_option_group_new().
2215 * Since: 2.6
2217 void
2218 g_option_group_set_error_hook (GOptionGroup *group,
2219 GOptionErrorFunc error_func)
2221 g_return_if_fail (group != NULL);
2223 group->error_func = error_func;
2228 * g_option_group_set_translate_func:
2229 * @group: a #GOptionGroup
2230 * @func: the #GTranslateFunc, or %NULL
2231 * @data: user data to pass to @func, or %NULL
2232 * @destroy_notify: a function which gets called to free @data, or %NULL
2234 * Sets the function which is used to translate user-visible
2235 * strings, for <option>--help</option> output. Different
2236 * groups can use different #GTranslateFunc<!-- -->s. If @func
2237 * is %NULL, strings are not translated.
2239 * If you are using gettext(), you only need to set the translation
2240 * domain, see g_option_group_set_translation_domain().
2242 * Since: 2.6
2244 void
2245 g_option_group_set_translate_func (GOptionGroup *group,
2246 GTranslateFunc func,
2247 gpointer data,
2248 GDestroyNotify destroy_notify)
2250 g_return_if_fail (group != NULL);
2252 if (group->translate_notify)
2253 group->translate_notify (group->translate_data);
2255 group->translate_func = func;
2256 group->translate_data = data;
2257 group->translate_notify = destroy_notify;
2260 static const gchar *
2261 dgettext_swapped (const gchar *msgid,
2262 const gchar *domainname)
2264 return g_dgettext (domainname, msgid);
2268 * g_option_group_set_translation_domain:
2269 * @group: a #GOptionGroup
2270 * @domain: the domain to use
2272 * A convenience function to use gettext() for translating
2273 * user-visible strings.
2275 * Since: 2.6
2277 void
2278 g_option_group_set_translation_domain (GOptionGroup *group,
2279 const gchar *domain)
2281 g_return_if_fail (group != NULL);
2283 g_option_group_set_translate_func (group,
2284 (GTranslateFunc)dgettext_swapped,
2285 g_strdup (domain),
2286 g_free);
2290 * g_option_context_set_translate_func:
2291 * @context: a #GOptionContext
2292 * @func: the #GTranslateFunc, or %NULL
2293 * @data: user data to pass to @func, or %NULL
2294 * @destroy_notify: a function which gets called to free @data, or %NULL
2296 * Sets the function which is used to translate the contexts
2297 * user-visible strings, for <option>--help</option> output.
2298 * If @func is %NULL, strings are not translated.
2300 * Note that option groups have their own translation functions,
2301 * this function only affects the @parameter_string (see g_option_context_new()),
2302 * the summary (see g_option_context_set_summary()) and the description
2303 * (see g_option_context_set_description()).
2305 * If you are using gettext(), you only need to set the translation
2306 * domain, see g_option_context_set_translation_domain().
2308 * Since: 2.12
2310 void
2311 g_option_context_set_translate_func (GOptionContext *context,
2312 GTranslateFunc func,
2313 gpointer data,
2314 GDestroyNotify destroy_notify)
2316 g_return_if_fail (context != NULL);
2318 if (context->translate_notify)
2319 context->translate_notify (context->translate_data);
2321 context->translate_func = func;
2322 context->translate_data = data;
2323 context->translate_notify = destroy_notify;
2327 * g_option_context_set_translation_domain:
2328 * @context: a #GOptionContext
2329 * @domain: the domain to use
2331 * A convenience function to use gettext() for translating
2332 * user-visible strings.
2334 * Since: 2.12
2336 void
2337 g_option_context_set_translation_domain (GOptionContext *context,
2338 const gchar *domain)
2340 g_return_if_fail (context != NULL);
2342 g_option_context_set_translate_func (context,
2343 (GTranslateFunc)dgettext_swapped,
2344 g_strdup (domain),
2345 g_free);
2349 * g_option_context_set_summary:
2350 * @context: a #GOptionContext
2351 * @summary: a string to be shown in <option>--help</option> output
2352 * before the list of options, or %NULL
2354 * Adds a string to be displayed in <option>--help</option> output
2355 * before the list of options. This is typically a summary of the
2356 * program functionality.
2358 * Note that the summary is translated (see
2359 * g_option_context_set_translate_func() and
2360 * g_option_context_set_translation_domain()).
2362 * Since: 2.12
2364 void
2365 g_option_context_set_summary (GOptionContext *context,
2366 const gchar *summary)
2368 g_return_if_fail (context != NULL);
2370 g_free (context->summary);
2371 context->summary = g_strdup (summary);
2376 * g_option_context_get_summary:
2377 * @context: a #GOptionContext
2379 * Returns the summary. See g_option_context_set_summary().
2381 * Returns: the summary
2383 * Since: 2.12
2385 G_CONST_RETURN gchar *
2386 g_option_context_get_summary (GOptionContext *context)
2388 g_return_val_if_fail (context != NULL, NULL);
2390 return context->summary;
2394 * g_option_context_set_description:
2395 * @context: a #GOptionContext
2396 * @description: a string to be shown in <option>--help</option> output
2397 * after the list of options, or %NULL
2399 * Adds a string to be displayed in <option>--help</option> output
2400 * after the list of options. This text often includes a bug reporting
2401 * address.
2403 * Note that the summary is translated (see
2404 * g_option_context_set_translate_func()).
2406 * Since: 2.12
2408 void
2409 g_option_context_set_description (GOptionContext *context,
2410 const gchar *description)
2412 g_return_if_fail (context != NULL);
2414 g_free (context->description);
2415 context->description = g_strdup (description);
2420 * g_option_context_get_description:
2421 * @context: a #GOptionContext
2423 * Returns the description. See g_option_context_set_description().
2425 * Returns: the description
2427 * Since: 2.12
2429 G_CONST_RETURN gchar *
2430 g_option_context_get_description (GOptionContext *context)
2432 g_return_val_if_fail (context != NULL, NULL);
2434 return context->description;