GOptionContext: Don't crash without main group
[platform/upstream/glib.git] / glib / goption.c
1 /* goption.c - Option parser
2  *
3  *  Copyright (C) 1999, 2003 Red Hat Software
4  *  Copyright (C) 2004       Anders Carlsson <andersca@gnome.org>
5  *
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.
10  *
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.
15  *
16  * You should have received a copy of the GNU Library General Public
17  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
18  */
19
20 /**
21  * SECTION:option
22  * @Short_description: parses commandline options
23  * @Title: Commandline option parser
24  *
25  * The GOption commandline parser is intended to be a simpler replacement
26  * for the popt library. It supports short and long commandline options,
27  * as shown in the following example:
28  *
29  * `testtreemodel -r 1 --max-size 20 --rand --display=:1.0 -vb -- file1 file2`
30  *
31  * The example demonstrates a number of features of the GOption
32  * commandline parser:
33  *
34  * - Options can be single letters, prefixed by a single dash.
35  *
36  * - Multiple short options can be grouped behind a single dash.
37  *
38  * - Long options are prefixed by two consecutive dashes.
39  *
40  * - Options can have an extra argument, which can be a number, a string or
41  *   a filename. For long options, the extra argument can be appended with
42  *   an equals sign after the option name, which is useful if the extra
43  *   argument starts with a dash, which would otherwise cause it to be
44  *   interpreted as another option.
45  *
46  * - Non-option arguments are returned to the application as rest arguments.
47  *
48  * - An argument consisting solely of two dashes turns off further parsing,
49  *   any remaining arguments (even those starting with a dash) are returned
50  *   to the application as rest arguments.
51  *
52  * Another important feature of GOption is that it can automatically
53  * generate nicely formatted help output. Unless it is explicitly turned
54  * off with g_option_context_set_help_enabled(), GOption will recognize
55  * the `--help`, `-?`, `--help-all` and `--help-groupname` options
56  * (where `groupname` is the name of a #GOptionGroup) and write a text
57  * similar to the one shown in the following example to stdout.
58  *
59  * |[
60  * Usage:
61  *   testtreemodel [OPTION...] - test tree model performance
62  *  
63  * Help Options:
64  *   -h, --help               Show help options
65  *   --help-all               Show all help options
66  *   --help-gtk               Show GTK+ Options
67  *  
68  * Application Options:
69  *   -r, --repeats=N          Average over N repetitions
70  *   -m, --max-size=M         Test up to 2^M items
71  *   --display=DISPLAY        X display to use
72  *   -v, --verbose            Be verbose
73  *   -b, --beep               Beep when done
74  *   --rand                   Randomize the data
75  * ]|
76  *
77  * GOption groups options in #GOptionGroups, which makes it easy to
78  * incorporate options from multiple sources. The intended use for this is
79  * to let applications collect option groups from the libraries it uses,
80  * add them to their #GOptionContext, and parse all options by a single call
81  * to g_option_context_parse(). See gtk_get_option_group() for an example.
82  *
83  * If an option is declared to be of type string or filename, GOption takes
84  * care of converting it to the right encoding; strings are returned in
85  * UTF-8, filenames are returned in the GLib filename encoding. Note that
86  * this only works if setlocale() has been called before
87  * g_option_context_parse().
88  *
89  * Here is a complete example of setting up GOption to parse the example
90  * commandline above and produce the example help output.
91  * |[<!-- language="C" --> 
92  * static gint repeats = 2;
93  * static gint max_size = 8;
94  * static gboolean verbose = FALSE;
95  * static gboolean beep = FALSE;
96  * static gboolean randomize = FALSE;
97  *
98  * static GOptionEntry entries[] =
99  * {
100  *   { "repeats", 'r', 0, G_OPTION_ARG_INT, &repeats, "Average over N repetitions", "N" },
101  *   { "max-size", 'm', 0, G_OPTION_ARG_INT, &max_size, "Test up to 2^M items", "M" },
102  *   { "verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose, "Be verbose", NULL },
103  *   { "beep", 'b', 0, G_OPTION_ARG_NONE, &beep, "Beep when done", NULL },
104  *   { "rand", 0, 0, G_OPTION_ARG_NONE, &randomize, "Randomize the data", NULL },
105  *   { NULL }
106  * };
107  *
108  * int
109  * main (int argc, char *argv[])
110  * {
111  *   GError *error = NULL;
112  *   GOptionContext *context;
113  *
114  *   context = g_option_context_new ("- test tree model performance");
115  *   g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
116  *   g_option_context_add_group (context, gtk_get_option_group (TRUE));
117  *   if (!g_option_context_parse (context, &argc, &argv, &error))
118  *     {
119  *       g_print ("option parsing failed: %s\n", error->message);
120  *       exit (1);
121  *     }
122  *
123  *   ...
124  *
125  * }
126  * ]|
127  *
128  * On UNIX systems, the argv that is passed to main() has no particular
129  * encoding, even to the extent that different parts of it may have
130  * different encodings.  In general, normal arguments and flags will be
131  * in the current locale and filenames should be considered to be opaque
132  * byte strings.  Proper use of %G_OPTION_ARG_FILENAME vs
133  * %G_OPTION_ARG_STRING is therefore important.
134  *
135  * Note that on Windows, filenames do have an encoding, but using
136  * #GOptionContext with the argv as passed to main() will result in a
137  * program that can only accept commandline arguments with characters
138  * from the system codepage.  This can cause problems when attempting to
139  * deal with filenames containing Unicode characters that fall outside
140  * of the codepage.
141  *
142  * A solution to this is to use g_win32_get_command_line() and
143  * g_option_context_parse_strv() which will properly handle full Unicode
144  * filenames.  If you are using #GApplication, this is done
145  * automatically for you.
146  *
147  * The following example shows how you can use #GOptionContext directly
148  * in order to correctly deal with Unicode filenames on Windows:
149  *
150  * |[<!-- language="C" --> 
151  * int
152  * main (int argc, char **argv)
153  * {
154  *   GError *error = NULL;
155  *   GOptionContext *context;
156  *   gchar **args;
157  *
158  * #ifdef G_OS_WIN32
159  *   args = g_win32_get_command_line ();
160  * #else
161  *   args = g_strdupv (argv);
162  * #endif
163  *
164  *   // set up context
165  *
166  *   if (!g_option_context_parse_strv (context, &args, &error))
167  *     {
168  *       // error happened
169  *     }
170  *
171  *   ...
172  *
173  *   g_strfreev (args);
174  *
175  *   ...
176  * }
177  * ]|
178  */
179
180 #include "config.h"
181
182 #include <string.h>
183 #include <stdlib.h>
184 #include <stdio.h>
185 #include <errno.h>
186
187 #if defined __OpenBSD__
188 #include <unistd.h>
189 #include <sys/sysctl.h>
190 #endif
191
192 #include "goption.h"
193
194 #include "gprintf.h"
195 #include "glibintl.h"
196
197 #define TRANSLATE(group, str) (((group)->translate_func ? (* (group)->translate_func) ((str), (group)->translate_data) : (str)))
198
199 #define NO_ARG(entry) ((entry)->arg == G_OPTION_ARG_NONE ||       \
200                        ((entry)->arg == G_OPTION_ARG_CALLBACK &&  \
201                         ((entry)->flags & G_OPTION_FLAG_NO_ARG)))
202
203 #define OPTIONAL_ARG(entry) ((entry)->arg == G_OPTION_ARG_CALLBACK &&  \
204                        (entry)->flags & G_OPTION_FLAG_OPTIONAL_ARG)
205
206 typedef struct
207 {
208   GOptionArg arg_type;
209   gpointer arg_data;
210   union
211   {
212     gboolean bool;
213     gint integer;
214     gchar *str;
215     gchar **array;
216     gdouble dbl;
217     gint64 int64;
218   } prev;
219   union
220   {
221     gchar *str;
222     struct
223     {
224       gint len;
225       gchar **data;
226     } array;
227   } allocated;
228 } Change;
229
230 typedef struct
231 {
232   gchar **ptr;
233   gchar *value;
234 } PendingNull;
235
236 struct _GOptionContext
237 {
238   GList           *groups;
239
240   gchar           *parameter_string;
241   gchar           *summary;
242   gchar           *description;
243
244   GTranslateFunc   translate_func;
245   GDestroyNotify   translate_notify;
246   gpointer         translate_data;
247
248   guint            help_enabled   : 1;
249   guint            ignore_unknown : 1;
250   guint            strv_mode      : 1;
251   guint            strict_posix   : 1;
252
253   GOptionGroup    *main_group;
254
255   /* We keep a list of change so we can revert them */
256   GList           *changes;
257
258   /* We also keep track of all argv elements
259    * that should be NULLed or modified.
260    */
261   GList           *pending_nulls;
262 };
263
264 struct _GOptionGroup
265 {
266   gchar           *name;
267   gchar           *description;
268   gchar           *help_description;
269
270   gint             ref_count;
271
272   GDestroyNotify   destroy_notify;
273   gpointer         user_data;
274
275   GTranslateFunc   translate_func;
276   GDestroyNotify   translate_notify;
277   gpointer         translate_data;
278
279   GOptionEntry    *entries;
280   gint             n_entries;
281
282   GOptionParseFunc pre_parse_func;
283   GOptionParseFunc post_parse_func;
284   GOptionErrorFunc error_func;
285 };
286
287 static void free_changes_list (GOptionContext *context,
288                                gboolean        revert);
289 static void free_pending_nulls (GOptionContext *context,
290                                 gboolean        perform_nulls);
291
292
293 static int
294 _g_unichar_get_width (gunichar c)
295 {
296   if (G_UNLIKELY (g_unichar_iszerowidth (c)))
297     return 0;
298
299   /* we ignore the fact that we should call g_unichar_iswide_cjk() under
300    * some locales (legacy East Asian ones) */
301   if (g_unichar_iswide (c))
302     return 2;
303
304   return 1;
305 }
306
307 static glong
308 _g_utf8_strwidth (const gchar *p)
309 {
310   glong len = 0;
311   g_return_val_if_fail (p != NULL, 0);
312
313   while (*p)
314     {
315       len += _g_unichar_get_width (g_utf8_get_char (p));
316       p = g_utf8_next_char (p);
317     }
318
319   return len;
320 }
321
322 G_DEFINE_QUARK (g-option-context-error-quark, g_option_error)
323
324 /**
325  * g_option_context_new:
326  * @parameter_string: (allow-none): a string which is displayed in
327  *    the first line of `--help` output, after the usage summary
328  *    `programname [OPTION...]`
329  *
330  * Creates a new option context.
331  *
332  * The @parameter_string can serve multiple purposes. It can be used
333  * to add descriptions for "rest" arguments, which are not parsed by
334  * the #GOptionContext, typically something like "FILES" or
335  * "FILE1 FILE2...". If you are using #G_OPTION_REMAINING for
336  * collecting "rest" arguments, GLib handles this automatically by
337  * using the @arg_description of the corresponding #GOptionEntry in
338  * the usage summary.
339  *
340  * Another usage is to give a short summary of the program
341  * functionality, like " - frob the strings", which will be displayed
342  * in the same line as the usage. For a longer description of the
343  * program functionality that should be displayed as a paragraph
344  * below the usage line, use g_option_context_set_summary().
345  *
346  * Note that the @parameter_string is translated using the
347  * function set with g_option_context_set_translate_func(), so
348  * it should normally be passed untranslated.
349  *
350  * Returns: a newly created #GOptionContext, which must be
351  *    freed with g_option_context_free() after use.
352  *
353  * Since: 2.6
354  */
355 GOptionContext *
356 g_option_context_new (const gchar *parameter_string)
357
358 {
359   GOptionContext *context;
360
361   context = g_new0 (GOptionContext, 1);
362
363   context->parameter_string = g_strdup (parameter_string);
364   context->strict_posix = FALSE;
365   context->help_enabled = TRUE;
366   context->ignore_unknown = FALSE;
367
368   return context;
369 }
370
371 /**
372  * g_option_context_free:
373  * @context: a #GOptionContext
374  *
375  * Frees context and all the groups which have been
376  * added to it.
377  *
378  * Please note that parsed arguments need to be freed separately (see
379  * #GOptionEntry).
380  *
381  * Since: 2.6
382  */
383 void g_option_context_free (GOptionContext *context)
384 {
385   g_return_if_fail (context != NULL);
386
387   g_list_free_full (context->groups, (GDestroyNotify) g_option_group_unref);
388
389   if (context->main_group)
390     g_option_group_unref (context->main_group);
391
392   free_changes_list (context, FALSE);
393   free_pending_nulls (context, FALSE);
394
395   g_free (context->parameter_string);
396   g_free (context->summary);
397   g_free (context->description);
398
399   if (context->translate_notify)
400     (* context->translate_notify) (context->translate_data);
401
402   g_free (context);
403 }
404
405
406 /**
407  * g_option_context_set_help_enabled:
408  * @context: a #GOptionContext
409  * @help_enabled: %TRUE to enable `--help`, %FALSE to disable it
410  *
411  * Enables or disables automatic generation of `--help` output.
412  * By default, g_option_context_parse() recognizes `--help`, `-h`,
413  * `-?`, `--help-all` and `--help-groupname` and creates suitable
414  * output to stdout.
415  *
416  * Since: 2.6
417  */
418 void g_option_context_set_help_enabled (GOptionContext *context,
419                                         gboolean        help_enabled)
420
421 {
422   g_return_if_fail (context != NULL);
423
424   context->help_enabled = help_enabled;
425 }
426
427 /**
428  * g_option_context_get_help_enabled:
429  * @context: a #GOptionContext
430  *
431  * Returns whether automatic `--help` generation
432  * is turned on for @context. See g_option_context_set_help_enabled().
433  *
434  * Returns: %TRUE if automatic help generation is turned on.
435  *
436  * Since: 2.6
437  */
438 gboolean
439 g_option_context_get_help_enabled (GOptionContext *context)
440 {
441   g_return_val_if_fail (context != NULL, FALSE);
442
443   return context->help_enabled;
444 }
445
446 /**
447  * g_option_context_set_ignore_unknown_options:
448  * @context: a #GOptionContext
449  * @ignore_unknown: %TRUE to ignore unknown options, %FALSE to produce
450  *    an error when unknown options are met
451  *
452  * Sets whether to ignore unknown options or not. If an argument is
453  * ignored, it is left in the @argv array after parsing. By default,
454  * g_option_context_parse() treats unknown options as error.
455  *
456  * This setting does not affect non-option arguments (i.e. arguments
457  * which don't start with a dash). But note that GOption cannot reliably
458  * determine whether a non-option belongs to a preceding unknown option.
459  *
460  * Since: 2.6
461  **/
462 void
463 g_option_context_set_ignore_unknown_options (GOptionContext *context,
464                                              gboolean        ignore_unknown)
465 {
466   g_return_if_fail (context != NULL);
467
468   context->ignore_unknown = ignore_unknown;
469 }
470
471 /**
472  * g_option_context_get_ignore_unknown_options:
473  * @context: a #GOptionContext
474  *
475  * Returns whether unknown options are ignored or not. See
476  * g_option_context_set_ignore_unknown_options().
477  *
478  * Returns: %TRUE if unknown options are ignored.
479  *
480  * Since: 2.6
481  **/
482 gboolean
483 g_option_context_get_ignore_unknown_options (GOptionContext *context)
484 {
485   g_return_val_if_fail (context != NULL, FALSE);
486
487   return context->ignore_unknown;
488 }
489
490 /**
491  * g_option_context_set_strict_posix:
492  * @context: a #GoptionContext
493  * @strict_posix: the new value
494  *
495  * Sets strict POSIX mode.
496  *
497  * By default, this mode is disabled.
498  *
499  * In strict POSIX mode, the first non-argument parameter encountered
500  * (eg: filename) terminates argument processing.  Remaining arguments
501  * are treated as non-options and are not attempted to be parsed.
502  *
503  * If strict POSIX mode is disabled then parsing is done in the GNU way
504  * where option arguments can be freely mixed with non-options.
505  *
506  * As an example, consider "ls foo -l".  With GNU style parsing, this
507  * will list "foo" in long mode.  In strict POSIX style, this will list
508  * the files named "foo" and "-l".
509  *
510  * It may be useful to force strict POSIX mode when creating "verb
511  * style" command line tools.  For example, the "gsettings" command line
512  * tool supports the global option "--schemadir" as well as many
513  * subcommands ("get", "set", etc.) which each have their own set of
514  * arguments.  Using strict POSIX mode will allow parsing the global
515  * options up to the verb name while leaving the remaining options to be
516  * parsed by the relevant subcommand (which can be determined by
517  * examining the verb name, which should be present in argv[1] after
518  * parsing).
519  *
520  * Since: 2.44
521  **/
522 void
523 g_option_context_set_strict_posix (GOptionContext *context,
524                                    gboolean        strict_posix)
525 {
526   g_return_if_fail (context != NULL);
527
528   context->strict_posix = strict_posix;
529 }
530
531 /**
532  * g_option_context_get_strict_posix:
533  * @context: a #GoptionContext
534  *
535  * Returns whether strict POSIX code is enabled.
536  *
537  * See g_option_context_set_strict_posix() for more information.
538  *
539  * Returns: %TRUE if strict POSIX is enabled, %FALSE otherwise.
540  *
541  * Since: 2.44
542  **/
543 gboolean
544 g_option_context_get_strict_posix (GOptionContext *context)
545 {
546   g_return_val_if_fail (context != NULL, FALSE);
547
548   return context->strict_posix;
549 }
550
551 /**
552  * g_option_context_add_group:
553  * @context: a #GOptionContext
554  * @group: (transfer full): the group to add
555  *
556  * Adds a #GOptionGroup to the @context, so that parsing with @context
557  * will recognize the options in the group. Note that this will take
558  * ownership of the @group and thus the @group should not be freed.
559  *
560  * Since: 2.6
561  **/
562 void
563 g_option_context_add_group (GOptionContext *context,
564                             GOptionGroup   *group)
565 {
566   GList *list;
567
568   g_return_if_fail (context != NULL);
569   g_return_if_fail (group != NULL);
570   g_return_if_fail (group->name != NULL);
571   g_return_if_fail (group->description != NULL);
572   g_return_if_fail (group->help_description != NULL);
573
574   for (list = context->groups; list; list = list->next)
575     {
576       GOptionGroup *g = (GOptionGroup *)list->data;
577
578       if ((group->name == NULL && g->name == NULL) ||
579           (group->name && g->name && strcmp (group->name, g->name) == 0))
580         g_warning ("A group named \"%s\" is already part of this GOptionContext",
581                    group->name);
582     }
583
584   context->groups = g_list_append (context->groups, group);
585 }
586
587 /**
588  * g_option_context_set_main_group:
589  * @context: a #GOptionContext
590  * @group: (transfer full): the group to set as main group
591  *
592  * Sets a #GOptionGroup as main group of the @context.
593  * This has the same effect as calling g_option_context_add_group(),
594  * the only difference is that the options in the main group are
595  * treated differently when generating `--help` output.
596  *
597  * Since: 2.6
598  **/
599 void
600 g_option_context_set_main_group (GOptionContext *context,
601                                  GOptionGroup   *group)
602 {
603   g_return_if_fail (context != NULL);
604   g_return_if_fail (group != NULL);
605
606   if (context->main_group)
607     {
608       g_warning ("This GOptionContext already has a main group");
609
610       return;
611     }
612
613   context->main_group = group;
614 }
615
616 /**
617  * g_option_context_get_main_group:
618  * @context: a #GOptionContext
619  *
620  * Returns a pointer to the main group of @context.
621  *
622  * Returns: (transfer none): the main group of @context, or %NULL if
623  *  @context doesn't have a main group. Note that group belongs to
624  *  @context and should not be modified or freed.
625  *
626  * Since: 2.6
627  **/
628 GOptionGroup *
629 g_option_context_get_main_group (GOptionContext *context)
630 {
631   g_return_val_if_fail (context != NULL, NULL);
632
633   return context->main_group;
634 }
635
636 /**
637  * g_option_context_add_main_entries:
638  * @context: a #GOptionContext
639  * @entries: a %NULL-terminated array of #GOptionEntrys
640  * @translation_domain: (allow-none): a translation domain to use for translating
641  *    the `--help` output for the options in @entries
642  *    with gettext(), or %NULL
643  *
644  * A convenience function which creates a main group if it doesn't
645  * exist, adds the @entries to it and sets the translation domain.
646  *
647  * Since: 2.6
648  **/
649 void
650 g_option_context_add_main_entries (GOptionContext      *context,
651                                    const GOptionEntry  *entries,
652                                    const gchar         *translation_domain)
653 {
654   g_return_if_fail (entries != NULL);
655
656   if (!context->main_group)
657     context->main_group = g_option_group_new (NULL, NULL, NULL, NULL, NULL);
658
659   g_option_group_add_entries (context->main_group, entries);
660   g_option_group_set_translation_domain (context->main_group, translation_domain);
661 }
662
663 static gint
664 calculate_max_length (GOptionGroup *group,
665                       GHashTable   *aliases)
666 {
667   GOptionEntry *entry;
668   gint i, len, max_length;
669   const gchar *long_name;
670
671   max_length = 0;
672
673   for (i = 0; i < group->n_entries; i++)
674     {
675       entry = &group->entries[i];
676
677       if (entry->flags & G_OPTION_FLAG_HIDDEN)
678         continue;
679
680       long_name = g_hash_table_lookup (aliases, &entry->long_name);
681       if (!long_name)
682         long_name = entry->long_name;
683       len = _g_utf8_strwidth (long_name);
684
685       if (entry->short_name)
686         len += 4;
687
688       if (!NO_ARG (entry) && entry->arg_description)
689         len += 1 + _g_utf8_strwidth (TRANSLATE (group, entry->arg_description));
690
691       max_length = MAX (max_length, len);
692     }
693
694   return max_length;
695 }
696
697 static void
698 print_entry (GOptionGroup       *group,
699              gint                max_length,
700              const GOptionEntry *entry,
701              GString            *string,
702              GHashTable         *aliases)
703 {
704   GString *str;
705   const gchar *long_name;
706
707   if (entry->flags & G_OPTION_FLAG_HIDDEN)
708     return;
709
710   if (entry->long_name[0] == 0)
711     return;
712
713   long_name = g_hash_table_lookup (aliases, &entry->long_name);
714   if (!long_name)
715     long_name = entry->long_name;
716
717   str = g_string_new (NULL);
718
719   if (entry->short_name)
720     g_string_append_printf (str, "  -%c, --%s", entry->short_name, long_name);
721   else
722     g_string_append_printf (str, "  --%s", long_name);
723
724   if (entry->arg_description)
725     g_string_append_printf (str, "=%s", TRANSLATE (group, entry->arg_description));
726
727   g_string_append_printf (string, "%s%*s %s\n", str->str,
728                           (int) (max_length + 4 - _g_utf8_strwidth (str->str)), "",
729                           entry->description ? TRANSLATE (group, entry->description) : "");
730   g_string_free (str, TRUE);
731 }
732
733 static gboolean
734 group_has_visible_entries (GOptionContext *context,
735                            GOptionGroup *group,
736                            gboolean      main_entries)
737 {
738   GOptionFlags reject_filter = G_OPTION_FLAG_HIDDEN;
739   GOptionEntry *entry;
740   gint i, l;
741   gboolean main_group = group == context->main_group;
742
743   if (!main_entries)
744     reject_filter |= G_OPTION_FLAG_IN_MAIN;
745
746   for (i = 0, l = (group ? group->n_entries : 0); i < l; i++)
747     {
748       entry = &group->entries[i];
749
750       if (main_entries && !main_group && !(entry->flags & G_OPTION_FLAG_IN_MAIN))
751         continue;
752       if (entry->long_name[0] == 0) /* ignore rest entry */
753         continue;
754       if (!(entry->flags & reject_filter))
755         return TRUE;
756     }
757
758   return FALSE;
759 }
760
761 static gboolean
762 group_list_has_visible_entries (GOptionContext *context,
763                                 GList          *group_list,
764                                 gboolean       main_entries)
765 {
766   while (group_list)
767     {
768       if (group_has_visible_entries (context, group_list->data, main_entries))
769         return TRUE;
770
771       group_list = group_list->next;
772     }
773
774   return FALSE;
775 }
776
777 static gboolean
778 context_has_h_entry (GOptionContext *context)
779 {
780   gsize i;
781   GList *list;
782
783   if (context->main_group)
784     {
785       for (i = 0; i < context->main_group->n_entries; i++)
786         {
787           if (context->main_group->entries[i].short_name == 'h')
788             return TRUE;
789         }
790     }
791
792   for (list = context->groups; list != NULL; list = g_list_next (list))
793     {
794      GOptionGroup *group;
795
796       group = (GOptionGroup*)list->data;
797       for (i = 0; i < group->n_entries; i++)
798         {
799           if (group->entries[i].short_name == 'h')
800             return TRUE;
801         }
802     }
803   return FALSE;
804 }
805
806 /**
807  * g_option_context_get_help:
808  * @context: a #GOptionContext
809  * @main_help: if %TRUE, only include the main group
810  * @group: (allow-none): the #GOptionGroup to create help for, or %NULL
811  *
812  * Returns a formatted, translated help text for the given context.
813  * To obtain the text produced by `--help`, call
814  * `g_option_context_get_help (context, TRUE, NULL)`.
815  * To obtain the text produced by `--help-all`, call
816  * `g_option_context_get_help (context, FALSE, NULL)`.
817  * To obtain the help text for an option group, call
818  * `g_option_context_get_help (context, FALSE, group)`.
819  *
820  * Returns: A newly allocated string containing the help text
821  *
822  * Since: 2.14
823  */
824 gchar *
825 g_option_context_get_help (GOptionContext *context,
826                            gboolean        main_help,
827                            GOptionGroup   *group)
828 {
829   GList *list;
830   gint max_length = 0, len;
831   gint i;
832   GOptionEntry *entry;
833   GHashTable *shadow_map;
834   GHashTable *aliases;
835   gboolean seen[256];
836   const gchar *rest_description;
837   GString *string;
838   guchar token;
839
840   string = g_string_sized_new (1024);
841
842   rest_description = NULL;
843   if (context->main_group)
844     {
845
846       for (i = 0; i < context->main_group->n_entries; i++)
847         {
848           entry = &context->main_group->entries[i];
849           if (entry->long_name[0] == 0)
850             {
851               rest_description = TRANSLATE (context->main_group, entry->arg_description);
852               break;
853             }
854         }
855     }
856
857   g_string_append_printf (string, "%s\n  %s", _("Usage:"), g_get_prgname ());
858   if (context->help_enabled ||
859       (context->main_group && context->main_group->n_entries > 0) ||
860       context->groups != NULL)
861     g_string_append_printf (string, " %s", _("[OPTION...]"));
862
863   if (rest_description)
864     {
865       g_string_append (string, " ");
866       g_string_append (string, rest_description);
867     }
868
869   if (context->parameter_string)
870     {
871       g_string_append (string, " ");
872       g_string_append (string, TRANSLATE (context, context->parameter_string));
873     }
874
875   g_string_append (string, "\n\n");
876
877   if (context->summary)
878     {
879       g_string_append (string, TRANSLATE (context, context->summary));
880       g_string_append (string, "\n\n");
881     }
882
883   memset (seen, 0, sizeof (gboolean) * 256);
884   shadow_map = g_hash_table_new (g_str_hash, g_str_equal);
885   aliases = g_hash_table_new_full (NULL, NULL, NULL, g_free);
886
887   if (context->main_group)
888     {
889       for (i = 0; i < context->main_group->n_entries; i++)
890         {
891           entry = &context->main_group->entries[i];
892           g_hash_table_insert (shadow_map,
893                                (gpointer)entry->long_name,
894                                entry);
895
896           if (seen[(guchar)entry->short_name])
897             entry->short_name = 0;
898           else
899             seen[(guchar)entry->short_name] = TRUE;
900         }
901     }
902
903   list = context->groups;
904   while (list != NULL)
905     {
906       GOptionGroup *g = list->data;
907       for (i = 0; i < g->n_entries; i++)
908         {
909           entry = &g->entries[i];
910           if (g_hash_table_lookup (shadow_map, entry->long_name) &&
911               !(entry->flags & G_OPTION_FLAG_NOALIAS))
912             {
913               g_hash_table_insert (aliases, &entry->long_name,
914                                    g_strdup_printf ("%s-%s", g->name, entry->long_name));
915             }
916           else
917             g_hash_table_insert (shadow_map, (gpointer)entry->long_name, entry);
918
919           if (seen[(guchar)entry->short_name] &&
920               !(entry->flags & G_OPTION_FLAG_NOALIAS))
921             entry->short_name = 0;
922           else
923             seen[(guchar)entry->short_name] = TRUE;
924         }
925       list = list->next;
926     }
927
928   g_hash_table_destroy (shadow_map);
929
930   list = context->groups;
931
932   if (context->help_enabled)
933     {
934       max_length = _g_utf8_strwidth ("-?, --help");
935
936       if (list)
937         {
938           len = _g_utf8_strwidth ("--help-all");
939           max_length = MAX (max_length, len);
940         }
941     }
942
943   if (context->main_group)
944     {
945       len = calculate_max_length (context->main_group, aliases);
946       max_length = MAX (max_length, len);
947     }
948
949   while (list != NULL)
950     {
951       GOptionGroup *g = list->data;
952
953       if (context->help_enabled)
954         {
955           /* First, we check the --help-<groupname> options */
956           len = _g_utf8_strwidth ("--help-") + _g_utf8_strwidth (g->name);
957           max_length = MAX (max_length, len);
958         }
959
960       /* Then we go through the entries */
961       len = calculate_max_length (g, aliases);
962       max_length = MAX (max_length, len);
963
964       list = list->next;
965     }
966
967   /* Add a bit of padding */
968   max_length += 4;
969
970   if (!group && context->help_enabled)
971     {
972       list = context->groups;
973
974       token = context_has_h_entry (context) ? '?' : 'h';
975
976       g_string_append_printf (string, "%s\n  -%c, --%-*s %s\n",
977                               _("Help Options:"), token, max_length - 4, "help",
978                               _("Show help options"));
979
980       /* We only want --help-all when there are groups */
981       if (list)
982         g_string_append_printf (string, "  --%-*s %s\n",
983                                 max_length, "help-all",
984                                 _("Show all help options"));
985
986       while (list)
987         {
988           GOptionGroup *g = list->data;
989
990           if (group_has_visible_entries (context, g, FALSE))
991             g_string_append_printf (string, "  --help-%-*s %s\n",
992                                     max_length - 5, g->name,
993                                     TRANSLATE (g, g->help_description));
994
995           list = list->next;
996         }
997
998       g_string_append (string, "\n");
999     }
1000
1001   if (group)
1002     {
1003       /* Print a certain group */
1004
1005       if (group_has_visible_entries (context, group, FALSE))
1006         {
1007           g_string_append (string, TRANSLATE (group, group->description));
1008           g_string_append (string, "\n");
1009           for (i = 0; i < group->n_entries; i++)
1010             print_entry (group, max_length, &group->entries[i], string, aliases);
1011           g_string_append (string, "\n");
1012         }
1013     }
1014   else if (!main_help)
1015     {
1016       /* Print all groups */
1017
1018       list = context->groups;
1019
1020       while (list)
1021         {
1022           GOptionGroup *g = list->data;
1023
1024           if (group_has_visible_entries (context, g, FALSE))
1025             {
1026               g_string_append (string, g->description);
1027               g_string_append (string, "\n");
1028               for (i = 0; i < g->n_entries; i++)
1029                 if (!(g->entries[i].flags & G_OPTION_FLAG_IN_MAIN))
1030                   print_entry (g, max_length, &g->entries[i], string, aliases);
1031
1032               g_string_append (string, "\n");
1033             }
1034
1035           list = list->next;
1036         }
1037     }
1038
1039   /* Print application options if --help or --help-all has been specified */
1040   if ((main_help || !group) &&
1041       (group_has_visible_entries (context, context->main_group, TRUE) ||
1042        group_list_has_visible_entries (context, context->groups, TRUE)))
1043     {
1044       list = context->groups;
1045
1046       if (context->help_enabled || list)
1047         g_string_append (string,  _("Application Options:"));
1048       else
1049         g_string_append (string, _("Options:"));
1050       g_string_append (string, "\n");
1051       if (context->main_group)
1052         for (i = 0; i < context->main_group->n_entries; i++)
1053           print_entry (context->main_group, max_length,
1054                        &context->main_group->entries[i], string, aliases);
1055
1056       while (list != NULL)
1057         {
1058           GOptionGroup *g = list->data;
1059
1060           /* Print main entries from other groups */
1061           for (i = 0; i < g->n_entries; i++)
1062             if (g->entries[i].flags & G_OPTION_FLAG_IN_MAIN)
1063               print_entry (g, max_length, &g->entries[i], string, aliases);
1064
1065           list = list->next;
1066         }
1067
1068       g_string_append (string, "\n");
1069     }
1070
1071   if (context->description)
1072     {
1073       g_string_append (string, TRANSLATE (context, context->description));
1074       g_string_append (string, "\n");
1075     }
1076
1077   g_hash_table_destroy (aliases);
1078
1079   return g_string_free (string, FALSE);
1080 }
1081
1082 G_GNUC_NORETURN
1083 static void
1084 print_help (GOptionContext *context,
1085             gboolean        main_help,
1086             GOptionGroup   *group)
1087 {
1088   gchar *help;
1089
1090   help = g_option_context_get_help (context, main_help, group);
1091   g_print ("%s", help);
1092   g_free (help);
1093
1094   exit (0);
1095 }
1096
1097 static gboolean
1098 parse_int (const gchar *arg_name,
1099            const gchar *arg,
1100            gint        *result,
1101            GError     **error)
1102 {
1103   gchar *end;
1104   glong tmp;
1105
1106   errno = 0;
1107   tmp = strtol (arg, &end, 0);
1108
1109   if (*arg == '\0' || *end != '\0')
1110     {
1111       g_set_error (error,
1112                    G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1113                    _("Cannot parse integer value '%s' for %s"),
1114                    arg, arg_name);
1115       return FALSE;
1116     }
1117
1118   *result = tmp;
1119   if (*result != tmp || errno == ERANGE)
1120     {
1121       g_set_error (error,
1122                    G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1123                    _("Integer value '%s' for %s out of range"),
1124                    arg, arg_name);
1125       return FALSE;
1126     }
1127
1128   return TRUE;
1129 }
1130
1131
1132 static gboolean
1133 parse_double (const gchar *arg_name,
1134            const gchar *arg,
1135            gdouble        *result,
1136            GError     **error)
1137 {
1138   gchar *end;
1139   gdouble tmp;
1140
1141   errno = 0;
1142   tmp = g_strtod (arg, &end);
1143
1144   if (*arg == '\0' || *end != '\0')
1145     {
1146       g_set_error (error,
1147                    G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1148                    _("Cannot parse double value '%s' for %s"),
1149                    arg, arg_name);
1150       return FALSE;
1151     }
1152   if (errno == ERANGE)
1153     {
1154       g_set_error (error,
1155                    G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1156                    _("Double value '%s' for %s out of range"),
1157                    arg, arg_name);
1158       return FALSE;
1159     }
1160
1161   *result = tmp;
1162
1163   return TRUE;
1164 }
1165
1166
1167 static gboolean
1168 parse_int64 (const gchar *arg_name,
1169              const gchar *arg,
1170              gint64      *result,
1171              GError     **error)
1172 {
1173   gchar *end;
1174   gint64 tmp;
1175
1176   errno = 0;
1177   tmp = g_ascii_strtoll (arg, &end, 0);
1178
1179   if (*arg == '\0' || *end != '\0')
1180     {
1181       g_set_error (error,
1182                    G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1183                    _("Cannot parse integer value '%s' for %s"),
1184                    arg, arg_name);
1185       return FALSE;
1186     }
1187   if (errno == ERANGE)
1188     {
1189       g_set_error (error,
1190                    G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1191                    _("Integer value '%s' for %s out of range"),
1192                    arg, arg_name);
1193       return FALSE;
1194     }
1195
1196   *result = tmp;
1197
1198   return TRUE;
1199 }
1200
1201
1202 static Change *
1203 get_change (GOptionContext *context,
1204             GOptionArg      arg_type,
1205             gpointer        arg_data)
1206 {
1207   GList *list;
1208   Change *change = NULL;
1209
1210   for (list = context->changes; list != NULL; list = list->next)
1211     {
1212       change = list->data;
1213
1214       if (change->arg_data == arg_data)
1215         goto found;
1216     }
1217
1218   change = g_new0 (Change, 1);
1219   change->arg_type = arg_type;
1220   change->arg_data = arg_data;
1221
1222   context->changes = g_list_prepend (context->changes, change);
1223
1224  found:
1225
1226   return change;
1227 }
1228
1229 static void
1230 add_pending_null (GOptionContext *context,
1231                   gchar         **ptr,
1232                   gchar          *value)
1233 {
1234   PendingNull *n;
1235
1236   n = g_new0 (PendingNull, 1);
1237   n->ptr = ptr;
1238   n->value = value;
1239
1240   context->pending_nulls = g_list_prepend (context->pending_nulls, n);
1241 }
1242
1243 static gboolean
1244 parse_arg (GOptionContext *context,
1245            GOptionGroup   *group,
1246            GOptionEntry   *entry,
1247            const gchar    *value,
1248            const gchar    *option_name,
1249            GError        **error)
1250
1251 {
1252   Change *change;
1253
1254   g_assert (value || OPTIONAL_ARG (entry) || NO_ARG (entry));
1255
1256   switch (entry->arg)
1257     {
1258     case G_OPTION_ARG_NONE:
1259       {
1260         (void) get_change (context, G_OPTION_ARG_NONE,
1261                            entry->arg_data);
1262
1263         *(gboolean *)entry->arg_data = !(entry->flags & G_OPTION_FLAG_REVERSE);
1264         break;
1265       }
1266     case G_OPTION_ARG_STRING:
1267       {
1268         gchar *data;
1269
1270 #ifdef G_OS_WIN32
1271         if (!context->strv_mode)
1272           data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1273         else
1274           data = g_strdup (value);
1275 #else
1276         data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1277 #endif
1278
1279         if (!data)
1280           return FALSE;
1281
1282         change = get_change (context, G_OPTION_ARG_STRING,
1283                              entry->arg_data);
1284         g_free (change->allocated.str);
1285
1286         change->prev.str = *(gchar **)entry->arg_data;
1287         change->allocated.str = data;
1288
1289         *(gchar **)entry->arg_data = data;
1290         break;
1291       }
1292     case G_OPTION_ARG_STRING_ARRAY:
1293       {
1294         gchar *data;
1295
1296 #ifdef G_OS_WIN32
1297         if (!context->strv_mode)
1298           data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1299         else
1300           data = g_strdup (value);
1301 #else
1302         data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1303 #endif
1304
1305         if (!data)
1306           return FALSE;
1307
1308         change = get_change (context, G_OPTION_ARG_STRING_ARRAY,
1309                              entry->arg_data);
1310
1311         if (change->allocated.array.len == 0)
1312           {
1313             change->prev.array = *(gchar ***)entry->arg_data;
1314             change->allocated.array.data = g_new (gchar *, 2);
1315           }
1316         else
1317           change->allocated.array.data =
1318             g_renew (gchar *, change->allocated.array.data,
1319                      change->allocated.array.len + 2);
1320
1321         change->allocated.array.data[change->allocated.array.len] = data;
1322         change->allocated.array.data[change->allocated.array.len + 1] = NULL;
1323
1324         change->allocated.array.len ++;
1325
1326         *(gchar ***)entry->arg_data = change->allocated.array.data;
1327
1328         break;
1329       }
1330
1331     case G_OPTION_ARG_FILENAME:
1332       {
1333         gchar *data;
1334
1335 #ifdef G_OS_WIN32
1336         if (!context->strv_mode)
1337           data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1338         else
1339           data = g_strdup (value);
1340
1341         if (!data)
1342           return FALSE;
1343 #else
1344         data = g_strdup (value);
1345 #endif
1346         change = get_change (context, G_OPTION_ARG_FILENAME,
1347                              entry->arg_data);
1348         g_free (change->allocated.str);
1349
1350         change->prev.str = *(gchar **)entry->arg_data;
1351         change->allocated.str = data;
1352
1353         *(gchar **)entry->arg_data = data;
1354         break;
1355       }
1356
1357     case G_OPTION_ARG_FILENAME_ARRAY:
1358       {
1359         gchar *data;
1360
1361 #ifdef G_OS_WIN32
1362         if (!context->strv_mode)
1363           data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1364         else
1365           data = g_strdup (value);
1366
1367         if (!data)
1368           return FALSE;
1369 #else
1370         data = g_strdup (value);
1371 #endif
1372         change = get_change (context, G_OPTION_ARG_STRING_ARRAY,
1373                              entry->arg_data);
1374
1375         if (change->allocated.array.len == 0)
1376           {
1377             change->prev.array = *(gchar ***)entry->arg_data;
1378             change->allocated.array.data = g_new (gchar *, 2);
1379           }
1380         else
1381           change->allocated.array.data =
1382             g_renew (gchar *, change->allocated.array.data,
1383                      change->allocated.array.len + 2);
1384
1385         change->allocated.array.data[change->allocated.array.len] = data;
1386         change->allocated.array.data[change->allocated.array.len + 1] = NULL;
1387
1388         change->allocated.array.len ++;
1389
1390         *(gchar ***)entry->arg_data = change->allocated.array.data;
1391
1392         break;
1393       }
1394
1395     case G_OPTION_ARG_INT:
1396       {
1397         gint data;
1398
1399         if (!parse_int (option_name, value,
1400                         &data,
1401                         error))
1402           return FALSE;
1403
1404         change = get_change (context, G_OPTION_ARG_INT,
1405                              entry->arg_data);
1406         change->prev.integer = *(gint *)entry->arg_data;
1407         *(gint *)entry->arg_data = data;
1408         break;
1409       }
1410     case G_OPTION_ARG_CALLBACK:
1411       {
1412         gchar *data;
1413         gboolean retval;
1414
1415         if (!value && entry->flags & G_OPTION_FLAG_OPTIONAL_ARG)
1416           data = NULL;
1417         else if (entry->flags & G_OPTION_FLAG_NO_ARG)
1418           data = NULL;
1419         else if (entry->flags & G_OPTION_FLAG_FILENAME)
1420           {
1421 #ifdef G_OS_WIN32
1422             if (!context->strv_mode)
1423               data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1424             else
1425               data = g_strdup (value);
1426 #else
1427             data = g_strdup (value);
1428 #endif
1429           }
1430         else
1431           data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1432
1433         if (!(entry->flags & (G_OPTION_FLAG_NO_ARG|G_OPTION_FLAG_OPTIONAL_ARG)) &&
1434             !data)
1435           return FALSE;
1436
1437         retval = (* (GOptionArgFunc) entry->arg_data) (option_name, data, group->user_data, error);
1438
1439         if (!retval && error != NULL && *error == NULL)
1440           g_set_error (error,
1441                        G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
1442                        _("Error parsing option %s"), option_name);
1443
1444         g_free (data);
1445
1446         return retval;
1447
1448         break;
1449       }
1450     case G_OPTION_ARG_DOUBLE:
1451       {
1452         gdouble data;
1453
1454         if (!parse_double (option_name, value,
1455                         &data,
1456                         error))
1457           {
1458             return FALSE;
1459           }
1460
1461         change = get_change (context, G_OPTION_ARG_DOUBLE,
1462                              entry->arg_data);
1463         change->prev.dbl = *(gdouble *)entry->arg_data;
1464         *(gdouble *)entry->arg_data = data;
1465         break;
1466       }
1467     case G_OPTION_ARG_INT64:
1468       {
1469         gint64 data;
1470
1471         if (!parse_int64 (option_name, value,
1472                          &data,
1473                          error))
1474           {
1475             return FALSE;
1476           }
1477
1478         change = get_change (context, G_OPTION_ARG_INT64,
1479                              entry->arg_data);
1480         change->prev.int64 = *(gint64 *)entry->arg_data;
1481         *(gint64 *)entry->arg_data = data;
1482         break;
1483       }
1484     default:
1485       g_assert_not_reached ();
1486     }
1487
1488   return TRUE;
1489 }
1490
1491 static gboolean
1492 parse_short_option (GOptionContext *context,
1493                     GOptionGroup   *group,
1494                     gint            idx,
1495                     gint           *new_idx,
1496                     gchar           arg,
1497                     gint           *argc,
1498                     gchar        ***argv,
1499                     GError        **error,
1500                     gboolean       *parsed)
1501 {
1502   gint j;
1503
1504   for (j = 0; j < group->n_entries; j++)
1505     {
1506       if (arg == group->entries[j].short_name)
1507         {
1508           gchar *option_name;
1509           gchar *value = NULL;
1510
1511           option_name = g_strdup_printf ("-%c", group->entries[j].short_name);
1512
1513           if (NO_ARG (&group->entries[j]))
1514             value = NULL;
1515           else
1516             {
1517               if (*new_idx > idx)
1518                 {
1519                   g_set_error (error,
1520                                G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
1521                                _("Error parsing option %s"), option_name);
1522                   g_free (option_name);
1523                   return FALSE;
1524                 }
1525
1526               if (idx < *argc - 1)
1527                 {
1528                   if (!OPTIONAL_ARG (&group->entries[j]))
1529                     {
1530                       value = (*argv)[idx + 1];
1531                       add_pending_null (context, &((*argv)[idx + 1]), NULL);
1532                       *new_idx = idx + 1;
1533                     }
1534                   else
1535                     {
1536                       if ((*argv)[idx + 1][0] == '-')
1537                         value = NULL;
1538                       else
1539                         {
1540                           value = (*argv)[idx + 1];
1541                           add_pending_null (context, &((*argv)[idx + 1]), NULL);
1542                           *new_idx = idx + 1;
1543                         }
1544                     }
1545                 }
1546               else if (idx >= *argc - 1 && OPTIONAL_ARG (&group->entries[j]))
1547                 value = NULL;
1548               else
1549                 {
1550                   g_set_error (error,
1551                                G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1552                                _("Missing argument for %s"), option_name);
1553                   g_free (option_name);
1554                   return FALSE;
1555                 }
1556             }
1557
1558           if (!parse_arg (context, group, &group->entries[j],
1559                           value, option_name, error))
1560             {
1561               g_free (option_name);
1562               return FALSE;
1563             }
1564
1565           g_free (option_name);
1566           *parsed = TRUE;
1567         }
1568     }
1569
1570   return TRUE;
1571 }
1572
1573 static gboolean
1574 parse_long_option (GOptionContext *context,
1575                    GOptionGroup   *group,
1576                    gint           *idx,
1577                    gchar          *arg,
1578                    gboolean        aliased,
1579                    gint           *argc,
1580                    gchar        ***argv,
1581                    GError        **error,
1582                    gboolean       *parsed)
1583 {
1584   gint j;
1585
1586   for (j = 0; j < group->n_entries; j++)
1587     {
1588       if (*idx >= *argc)
1589         return TRUE;
1590
1591       if (aliased && (group->entries[j].flags & G_OPTION_FLAG_NOALIAS))
1592         continue;
1593
1594       if (NO_ARG (&group->entries[j]) &&
1595           strcmp (arg, group->entries[j].long_name) == 0)
1596         {
1597           gchar *option_name;
1598           gboolean retval;
1599
1600           option_name = g_strconcat ("--", group->entries[j].long_name, NULL);
1601           retval = parse_arg (context, group, &group->entries[j],
1602                               NULL, option_name, error);
1603           g_free (option_name);
1604
1605           add_pending_null (context, &((*argv)[*idx]), NULL);
1606           *parsed = TRUE;
1607
1608           return retval;
1609         }
1610       else
1611         {
1612           gint len = strlen (group->entries[j].long_name);
1613
1614           if (strncmp (arg, group->entries[j].long_name, len) == 0 &&
1615               (arg[len] == '=' || arg[len] == 0))
1616             {
1617               gchar *value = NULL;
1618               gchar *option_name;
1619
1620               add_pending_null (context, &((*argv)[*idx]), NULL);
1621               option_name = g_strconcat ("--", group->entries[j].long_name, NULL);
1622
1623               if (arg[len] == '=')
1624                 value = arg + len + 1;
1625               else if (*idx < *argc - 1)
1626                 {
1627                   if (!OPTIONAL_ARG (&group->entries[j]))
1628                     {
1629                       value = (*argv)[*idx + 1];
1630                       add_pending_null (context, &((*argv)[*idx + 1]), NULL);
1631                       (*idx)++;
1632                     }
1633                   else
1634                     {
1635                       if ((*argv)[*idx + 1][0] == '-')
1636                         {
1637                           gboolean retval;
1638                           retval = parse_arg (context, group, &group->entries[j],
1639                                               NULL, option_name, error);
1640                           *parsed = TRUE;
1641                           g_free (option_name);
1642                           return retval;
1643                         }
1644                       else
1645                         {
1646                           value = (*argv)[*idx + 1];
1647                           add_pending_null (context, &((*argv)[*idx + 1]), NULL);
1648                           (*idx)++;
1649                         }
1650                     }
1651                 }
1652               else if (*idx >= *argc - 1 && OPTIONAL_ARG (&group->entries[j]))
1653                 {
1654                     gboolean retval;
1655                     retval = parse_arg (context, group, &group->entries[j],
1656                                         NULL, option_name, error);
1657                     *parsed = TRUE;
1658                     g_free (option_name);
1659                     return retval;
1660                 }
1661               else
1662                 {
1663                   g_set_error (error,
1664                                G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1665                                _("Missing argument for %s"), option_name);
1666                   g_free (option_name);
1667                   return FALSE;
1668                 }
1669
1670               if (!parse_arg (context, group, &group->entries[j],
1671                               value, option_name, error))
1672                 {
1673                   g_free (option_name);
1674                   return FALSE;
1675                 }
1676
1677               g_free (option_name);
1678               *parsed = TRUE;
1679             }
1680         }
1681     }
1682
1683   return TRUE;
1684 }
1685
1686 static gboolean
1687 parse_remaining_arg (GOptionContext *context,
1688                      GOptionGroup   *group,
1689                      gint           *idx,
1690                      gint           *argc,
1691                      gchar        ***argv,
1692                      GError        **error,
1693                      gboolean       *parsed)
1694 {
1695   gint j;
1696
1697   for (j = 0; j < group->n_entries; j++)
1698     {
1699       if (*idx >= *argc)
1700         return TRUE;
1701
1702       if (group->entries[j].long_name[0])
1703         continue;
1704
1705       g_return_val_if_fail (group->entries[j].arg == G_OPTION_ARG_CALLBACK ||
1706                             group->entries[j].arg == G_OPTION_ARG_STRING_ARRAY ||
1707                             group->entries[j].arg == G_OPTION_ARG_FILENAME_ARRAY, FALSE);
1708
1709       add_pending_null (context, &((*argv)[*idx]), NULL);
1710
1711       if (!parse_arg (context, group, &group->entries[j], (*argv)[*idx], "", error))
1712         return FALSE;
1713
1714       *parsed = TRUE;
1715       return TRUE;
1716     }
1717
1718   return TRUE;
1719 }
1720
1721 static void
1722 free_changes_list (GOptionContext *context,
1723                    gboolean        revert)
1724 {
1725   GList *list;
1726
1727   for (list = context->changes; list != NULL; list = list->next)
1728     {
1729       Change *change = list->data;
1730
1731       if (revert)
1732         {
1733           switch (change->arg_type)
1734             {
1735             case G_OPTION_ARG_NONE:
1736               *(gboolean *)change->arg_data = change->prev.bool;
1737               break;
1738             case G_OPTION_ARG_INT:
1739               *(gint *)change->arg_data = change->prev.integer;
1740               break;
1741             case G_OPTION_ARG_STRING:
1742             case G_OPTION_ARG_FILENAME:
1743               g_free (change->allocated.str);
1744               *(gchar **)change->arg_data = change->prev.str;
1745               break;
1746             case G_OPTION_ARG_STRING_ARRAY:
1747             case G_OPTION_ARG_FILENAME_ARRAY:
1748               g_strfreev (change->allocated.array.data);
1749               *(gchar ***)change->arg_data = change->prev.array;
1750               break;
1751             case G_OPTION_ARG_DOUBLE:
1752               *(gdouble *)change->arg_data = change->prev.dbl;
1753               break;
1754             case G_OPTION_ARG_INT64:
1755               *(gint64 *)change->arg_data = change->prev.int64;
1756               break;
1757             default:
1758               g_assert_not_reached ();
1759             }
1760         }
1761
1762       g_free (change);
1763     }
1764
1765   g_list_free (context->changes);
1766   context->changes = NULL;
1767 }
1768
1769 static void
1770 free_pending_nulls (GOptionContext *context,
1771                     gboolean        perform_nulls)
1772 {
1773   GList *list;
1774
1775   for (list = context->pending_nulls; list != NULL; list = list->next)
1776     {
1777       PendingNull *n = list->data;
1778
1779       if (perform_nulls)
1780         {
1781           if (n->value)
1782             {
1783               /* Copy back the short options */
1784               *(n->ptr)[0] = '-';
1785               strcpy (*n->ptr + 1, n->value);
1786             }
1787           else
1788             {
1789               if (context->strv_mode)
1790                 g_free (*n->ptr);
1791
1792               *n->ptr = NULL;
1793             }
1794         }
1795
1796       g_free (n->value);
1797       g_free (n);
1798     }
1799
1800   g_list_free (context->pending_nulls);
1801   context->pending_nulls = NULL;
1802 }
1803
1804 /* Use a platform-specific mechanism to look up the first argument to
1805  * the current process. 
1806  * Note if you implement this for other platforms, also add it to
1807  * tests/option-argv0.c
1808  */
1809 static char *
1810 platform_get_argv0 (void)
1811 {
1812 #if defined __linux
1813   char *cmdline;
1814   char *base_arg0;
1815   gsize len;
1816
1817   if (!g_file_get_contents ("/proc/self/cmdline",
1818                             &cmdline,
1819                             &len,
1820                             NULL))
1821     return NULL;
1822   /* Sanity check for a NUL terminator. */
1823   if (!memchr (cmdline, 0, len))
1824     return NULL;
1825   /* We could just return cmdline, but I think it's better
1826    * to hold on to a smaller malloc block; the arguments
1827    * could be large.
1828    */
1829   base_arg0 = g_path_get_basename (cmdline);
1830   g_free (cmdline);
1831   return base_arg0;
1832 #elif defined __OpenBSD__
1833   char **cmdline;
1834   char *base_arg0;
1835   gsize len;
1836
1837   int mib[] = { CTL_KERN, KERN_PROC_ARGS, getpid(), KERN_PROC_ARGV };
1838
1839   if (sysctl (mib, G_N_ELEMENTS (mib), NULL, &len, NULL, 0) == -1)
1840       return NULL;
1841
1842   cmdline = g_malloc0 (len);
1843
1844   if (sysctl (mib, G_N_ELEMENTS (mib), cmdline, &len, NULL, 0) == -1)
1845     {
1846       g_free (cmdline);
1847       return NULL;
1848     }
1849
1850   /* We could just return cmdline, but I think it's better
1851    * to hold on to a smaller malloc block; the arguments
1852    * could be large.
1853    */
1854   base_arg0 = g_path_get_basename (*cmdline);
1855   g_free (cmdline);
1856   return base_arg0;
1857 #endif
1858
1859   return NULL;
1860 }
1861
1862 /**
1863  * g_option_context_parse:
1864  * @context: a #GOptionContext
1865  * @argc: (inout) (allow-none): a pointer to the number of command line arguments
1866  * @argv: (inout) (array length=argc) (allow-none): a pointer to the array of command line arguments
1867  * @error: a return location for errors
1868  *
1869  * Parses the command line arguments, recognizing options
1870  * which have been added to @context. A side-effect of
1871  * calling this function is that g_set_prgname() will be
1872  * called.
1873  *
1874  * If the parsing is successful, any parsed arguments are
1875  * removed from the array and @argc and @argv are updated
1876  * accordingly. A '--' option is stripped from @argv
1877  * unless there are unparsed options before and after it,
1878  * or some of the options after it start with '-'. In case
1879  * of an error, @argc and @argv are left unmodified.
1880  *
1881  * If automatic `--help` support is enabled
1882  * (see g_option_context_set_help_enabled()), and the
1883  * @argv array contains one of the recognized help options,
1884  * this function will produce help output to stdout and
1885  * call `exit (0)`.
1886  *
1887  * Note that function depends on the [current locale][setlocale] for
1888  * automatic character set conversion of string and filename
1889  * arguments.
1890  *
1891  * Returns: %TRUE if the parsing was successful,
1892  *               %FALSE if an error occurred
1893  *
1894  * Since: 2.6
1895  **/
1896 gboolean
1897 g_option_context_parse (GOptionContext   *context,
1898                         gint             *argc,
1899                         gchar          ***argv,
1900                         GError          **error)
1901 {
1902   gint i, j, k;
1903   GList *list;
1904
1905   /* Set program name */
1906   if (!g_get_prgname())
1907     {
1908       gchar *prgname;
1909
1910       if (argc && argv && *argc)
1911         prgname = g_path_get_basename ((*argv)[0]);
1912       else
1913         prgname = platform_get_argv0 ();
1914
1915       if (prgname)
1916         g_set_prgname (prgname);
1917       else
1918         g_set_prgname ("<unknown>");
1919
1920       g_free (prgname);
1921     }
1922
1923   /* Call pre-parse hooks */
1924   list = context->groups;
1925   while (list)
1926     {
1927       GOptionGroup *group = list->data;
1928
1929       if (group->pre_parse_func)
1930         {
1931           if (!(* group->pre_parse_func) (context, group,
1932                                           group->user_data, error))
1933             goto fail;
1934         }
1935
1936       list = list->next;
1937     }
1938
1939   if (context->main_group && context->main_group->pre_parse_func)
1940     {
1941       if (!(* context->main_group->pre_parse_func) (context, context->main_group,
1942                                                     context->main_group->user_data, error))
1943         goto fail;
1944     }
1945
1946   if (argc && argv)
1947     {
1948       gboolean stop_parsing = FALSE;
1949       gboolean has_unknown = FALSE;
1950       gint separator_pos = 0;
1951
1952       for (i = 1; i < *argc; i++)
1953         {
1954           gchar *arg, *dash;
1955           gboolean parsed = FALSE;
1956
1957           if ((*argv)[i][0] == '-' && (*argv)[i][1] != '\0' && !stop_parsing)
1958             {
1959               if ((*argv)[i][1] == '-')
1960                 {
1961                   /* -- option */
1962
1963                   arg = (*argv)[i] + 2;
1964
1965                   /* '--' terminates list of arguments */
1966                   if (*arg == 0)
1967                     {
1968                       separator_pos = i;
1969                       stop_parsing = TRUE;
1970                       continue;
1971                     }
1972
1973                   /* Handle help options */
1974                   if (context->help_enabled)
1975                     {
1976                       if (strcmp (arg, "help") == 0)
1977                         print_help (context, TRUE, NULL);
1978                       else if (strcmp (arg, "help-all") == 0)
1979                         print_help (context, FALSE, NULL);
1980                       else if (strncmp (arg, "help-", 5) == 0)
1981                         {
1982                           list = context->groups;
1983
1984                           while (list)
1985                             {
1986                               GOptionGroup *group = list->data;
1987
1988                               if (strcmp (arg + 5, group->name) == 0)
1989                                 print_help (context, FALSE, group);
1990
1991                               list = list->next;
1992                             }
1993                         }
1994                     }
1995
1996                   if (context->main_group &&
1997                       !parse_long_option (context, context->main_group, &i, arg,
1998                                           FALSE, argc, argv, error, &parsed))
1999                     goto fail;
2000
2001                   if (parsed)
2002                     continue;
2003
2004                   /* Try the groups */
2005                   list = context->groups;
2006                   while (list)
2007                     {
2008                       GOptionGroup *group = list->data;
2009
2010                       if (!parse_long_option (context, group, &i, arg,
2011                                               FALSE, argc, argv, error, &parsed))
2012                         goto fail;
2013
2014                       if (parsed)
2015                         break;
2016
2017                       list = list->next;
2018                     }
2019
2020                   if (parsed)
2021                     continue;
2022
2023                   /* Now look for --<group>-<option> */
2024                   dash = strchr (arg, '-');
2025                   if (dash)
2026                     {
2027                       /* Try the groups */
2028                       list = context->groups;
2029                       while (list)
2030                         {
2031                           GOptionGroup *group = list->data;
2032
2033                           if (strncmp (group->name, arg, dash - arg) == 0)
2034                             {
2035                               if (!parse_long_option (context, group, &i, dash + 1,
2036                                                       TRUE, argc, argv, error, &parsed))
2037                                 goto fail;
2038
2039                               if (parsed)
2040                                 break;
2041                             }
2042
2043                           list = list->next;
2044                         }
2045                     }
2046
2047                   if (context->ignore_unknown)
2048                     continue;
2049                 }
2050               else
2051                 { /* short option */
2052                   gint new_i = i, arg_length;
2053                   gboolean *nulled_out = NULL;
2054                   gboolean has_h_entry = context_has_h_entry (context);
2055                   arg = (*argv)[i] + 1;
2056                   arg_length = strlen (arg);
2057                   nulled_out = g_newa (gboolean, arg_length);
2058                   memset (nulled_out, 0, arg_length * sizeof (gboolean));
2059                   for (j = 0; j < arg_length; j++)
2060                     {
2061                       if (context->help_enabled && (arg[j] == '?' ||
2062                         (arg[j] == 'h' && !has_h_entry)))
2063                         print_help (context, TRUE, NULL);
2064                       parsed = FALSE;
2065                       if (context->main_group &&
2066                           !parse_short_option (context, context->main_group,
2067                                                i, &new_i, arg[j],
2068                                                argc, argv, error, &parsed))
2069                         goto fail;
2070                       if (!parsed)
2071                         {
2072                           /* Try the groups */
2073                           list = context->groups;
2074                           while (list)
2075                             {
2076                               GOptionGroup *group = list->data;
2077                               if (!parse_short_option (context, group, i, &new_i, arg[j],
2078                                                        argc, argv, error, &parsed))
2079                                 goto fail;
2080                               if (parsed)
2081                                 break;
2082                               list = list->next;
2083                             }
2084                         }
2085
2086                       if (context->ignore_unknown && parsed)
2087                         nulled_out[j] = TRUE;
2088                       else if (context->ignore_unknown)
2089                         continue;
2090                       else if (!parsed)
2091                         break;
2092                       /* !context->ignore_unknown && parsed */
2093                     }
2094                   if (context->ignore_unknown)
2095                     {
2096                       gchar *new_arg = NULL;
2097                       gint arg_index = 0;
2098                       for (j = 0; j < arg_length; j++)
2099                         {
2100                           if (!nulled_out[j])
2101                             {
2102                               if (!new_arg)
2103                                 new_arg = g_malloc (arg_length + 1);
2104                               new_arg[arg_index++] = arg[j];
2105                             }
2106                         }
2107                       if (new_arg)
2108                         new_arg[arg_index] = '\0';
2109                       add_pending_null (context, &((*argv)[i]), new_arg);
2110                       i = new_i;
2111                     }
2112                   else if (parsed)
2113                     {
2114                       add_pending_null (context, &((*argv)[i]), NULL);
2115                       i = new_i;
2116                     }
2117                 }
2118
2119               if (!parsed)
2120                 has_unknown = TRUE;
2121
2122               if (!parsed && !context->ignore_unknown)
2123                 {
2124                   g_set_error (error,
2125                                G_OPTION_ERROR, G_OPTION_ERROR_UNKNOWN_OPTION,
2126                                    _("Unknown option %s"), (*argv)[i]);
2127                   goto fail;
2128                 }
2129             }
2130           else
2131             {
2132               if (context->strict_posix)
2133                 stop_parsing = TRUE;
2134
2135               /* Collect remaining args */
2136               if (context->main_group &&
2137                   !parse_remaining_arg (context, context->main_group, &i,
2138                                         argc, argv, error, &parsed))
2139                 goto fail;
2140
2141               if (!parsed && (has_unknown || (*argv)[i][0] == '-'))
2142                 separator_pos = 0;
2143             }
2144         }
2145
2146       if (separator_pos > 0)
2147         add_pending_null (context, &((*argv)[separator_pos]), NULL);
2148
2149     }
2150
2151   /* Call post-parse hooks */
2152   list = context->groups;
2153   while (list)
2154     {
2155       GOptionGroup *group = list->data;
2156
2157       if (group->post_parse_func)
2158         {
2159           if (!(* group->post_parse_func) (context, group,
2160                                            group->user_data, error))
2161             goto fail;
2162         }
2163
2164       list = list->next;
2165     }
2166
2167   if (context->main_group && context->main_group->post_parse_func)
2168     {
2169       if (!(* context->main_group->post_parse_func) (context, context->main_group,
2170                                                      context->main_group->user_data, error))
2171         goto fail;
2172     }
2173
2174   if (argc && argv)
2175     {
2176       free_pending_nulls (context, TRUE);
2177
2178       for (i = 1; i < *argc; i++)
2179         {
2180           for (k = i; k < *argc; k++)
2181             if ((*argv)[k] != NULL)
2182               break;
2183
2184           if (k > i)
2185             {
2186               k -= i;
2187               for (j = i + k; j < *argc; j++)
2188                 {
2189                   (*argv)[j-k] = (*argv)[j];
2190                   (*argv)[j] = NULL;
2191                 }
2192               *argc -= k;
2193             }
2194         }
2195     }
2196
2197   return TRUE;
2198
2199  fail:
2200
2201   /* Call error hooks */
2202   list = context->groups;
2203   while (list)
2204     {
2205       GOptionGroup *group = list->data;
2206
2207       if (group->error_func)
2208         (* group->error_func) (context, group,
2209                                group->user_data, error);
2210
2211       list = list->next;
2212     }
2213
2214   if (context->main_group && context->main_group->error_func)
2215     (* context->main_group->error_func) (context, context->main_group,
2216                                          context->main_group->user_data, error);
2217
2218   free_changes_list (context, TRUE);
2219   free_pending_nulls (context, FALSE);
2220
2221   return FALSE;
2222 }
2223
2224 /**
2225  * g_option_group_new:
2226  * @name: the name for the option group, this is used to provide
2227  *   help for the options in this group with `--help-`@name
2228  * @description: a description for this group to be shown in
2229  *   `--help`. This string is translated using the translation
2230  *   domain or translation function of the group
2231  * @help_description: a description for the `--help-`@name option.
2232  *   This string is translated using the translation domain or translation function
2233  *   of the group
2234  * @user_data: (allow-none): user data that will be passed to the pre- and post-parse hooks,
2235  *   the error hook and to callbacks of %G_OPTION_ARG_CALLBACK options, or %NULL
2236  * @destroy: (allow-none): a function that will be called to free @user_data, or %NULL
2237  *
2238  * Creates a new #GOptionGroup.
2239  *
2240  * Returns: a newly created option group. It should be added
2241  *   to a #GOptionContext or freed with g_option_group_unref().
2242  *
2243  * Since: 2.6
2244  **/
2245 GOptionGroup *
2246 g_option_group_new (const gchar    *name,
2247                     const gchar    *description,
2248                     const gchar    *help_description,
2249                     gpointer        user_data,
2250                     GDestroyNotify  destroy)
2251
2252 {
2253   GOptionGroup *group;
2254
2255   group = g_new0 (GOptionGroup, 1);
2256   group->ref_count = 1;
2257   group->name = g_strdup (name);
2258   group->description = g_strdup (description);
2259   group->help_description = g_strdup (help_description);
2260   group->user_data = user_data;
2261   group->destroy_notify = destroy;
2262
2263   return group;
2264 }
2265
2266
2267 /**
2268  * g_option_group_free:
2269  * @group: a #GOptionGroup
2270  *
2271  * Frees a #GOptionGroup. Note that you must not free groups
2272  * which have been added to a #GOptionContext.
2273  *
2274  * Since: 2.6
2275  *
2276  * Deprecated: 2.44: Use g_option_group_unref() instead.
2277  */
2278 void
2279 g_option_group_free (GOptionGroup *group)
2280 {
2281   g_option_group_unref (group);
2282 }
2283
2284 /**
2285  * g_option_group_ref:
2286  * @group: a #GOptionGroup
2287  *
2288  * Increments the reference count of @group by one.
2289  *
2290  * Returns: a #GoptionGroup
2291  *
2292  * Since: 2.44
2293  */
2294 GOptionGroup *
2295 g_option_group_ref (GOptionGroup *group)
2296 {
2297   g_return_val_if_fail (group != NULL, NULL);
2298
2299   group->ref_count++;
2300
2301   return group;
2302 }
2303
2304 /**
2305  * g_option_group_unref:
2306  * @group: a #GOptionGroup
2307  *
2308  * Decrements the reference count of @group by one.
2309  * If the reference count drops to 0, the @group will be freed.
2310  * and all memory allocated by the @group is released.
2311  *
2312  * Since: 2.44
2313  */
2314 void
2315 g_option_group_unref (GOptionGroup *group)
2316 {
2317   g_return_if_fail (group != NULL);
2318
2319   if (--group->ref_count == 0)
2320     {
2321       g_free (group->name);
2322       g_free (group->description);
2323       g_free (group->help_description);
2324
2325       g_free (group->entries);
2326
2327       if (group->destroy_notify)
2328         (* group->destroy_notify) (group->user_data);
2329
2330       if (group->translate_notify)
2331         (* group->translate_notify) (group->translate_data);
2332
2333       g_free (group);
2334     }
2335 }
2336
2337 /**
2338  * g_option_group_add_entries:
2339  * @group: a #GOptionGroup
2340  * @entries: a %NULL-terminated array of #GOptionEntrys
2341  *
2342  * Adds the options specified in @entries to @group.
2343  *
2344  * Since: 2.6
2345  **/
2346 void
2347 g_option_group_add_entries (GOptionGroup       *group,
2348                             const GOptionEntry *entries)
2349 {
2350   gint i, n_entries;
2351
2352   g_return_if_fail (entries != NULL);
2353
2354   for (n_entries = 0; entries[n_entries].long_name != NULL; n_entries++) ;
2355
2356   group->entries = g_renew (GOptionEntry, group->entries, group->n_entries + n_entries);
2357
2358   memcpy (group->entries + group->n_entries, entries, sizeof (GOptionEntry) * n_entries);
2359
2360   for (i = group->n_entries; i < group->n_entries + n_entries; i++)
2361     {
2362       gchar c = group->entries[i].short_name;
2363
2364       if (c == '-' || (c != 0 && !g_ascii_isprint (c)))
2365         {
2366           g_warning (G_STRLOC ": ignoring invalid short option '%c' (%d) in entry %s:%s",
2367               c, c, group->name, group->entries[i].long_name);
2368           group->entries[i].short_name = '\0';
2369         }
2370
2371       if (group->entries[i].arg != G_OPTION_ARG_NONE &&
2372           (group->entries[i].flags & G_OPTION_FLAG_REVERSE) != 0)
2373         {
2374           g_warning (G_STRLOC ": ignoring reverse flag on option of arg-type %d in entry %s:%s",
2375               group->entries[i].arg, group->name, group->entries[i].long_name);
2376
2377           group->entries[i].flags &= ~G_OPTION_FLAG_REVERSE;
2378         }
2379
2380       if (group->entries[i].arg != G_OPTION_ARG_CALLBACK &&
2381           (group->entries[i].flags & (G_OPTION_FLAG_NO_ARG|G_OPTION_FLAG_OPTIONAL_ARG|G_OPTION_FLAG_FILENAME)) != 0)
2382         {
2383           g_warning (G_STRLOC ": ignoring no-arg, optional-arg or filename flags (%d) on option of arg-type %d in entry %s:%s",
2384               group->entries[i].flags, group->entries[i].arg, group->name, group->entries[i].long_name);
2385
2386           group->entries[i].flags &= ~(G_OPTION_FLAG_NO_ARG|G_OPTION_FLAG_OPTIONAL_ARG|G_OPTION_FLAG_FILENAME);
2387         }
2388     }
2389
2390   group->n_entries += n_entries;
2391 }
2392
2393 /**
2394  * g_option_group_set_parse_hooks:
2395  * @group: a #GOptionGroup
2396  * @pre_parse_func: (allow-none): a function to call before parsing, or %NULL
2397  * @post_parse_func: (allow-none): a function to call after parsing, or %NULL
2398  *
2399  * Associates two functions with @group which will be called
2400  * from g_option_context_parse() before the first option is parsed
2401  * and after the last option has been parsed, respectively.
2402  *
2403  * Note that the user data to be passed to @pre_parse_func and
2404  * @post_parse_func can be specified when constructing the group
2405  * with g_option_group_new().
2406  *
2407  * Since: 2.6
2408  **/
2409 void
2410 g_option_group_set_parse_hooks (GOptionGroup     *group,
2411                                 GOptionParseFunc  pre_parse_func,
2412                                 GOptionParseFunc  post_parse_func)
2413 {
2414   g_return_if_fail (group != NULL);
2415
2416   group->pre_parse_func = pre_parse_func;
2417   group->post_parse_func = post_parse_func;
2418 }
2419
2420 /**
2421  * g_option_group_set_error_hook:
2422  * @group: a #GOptionGroup
2423  * @error_func: a function to call when an error occurs
2424  *
2425  * Associates a function with @group which will be called
2426  * from g_option_context_parse() when an error occurs.
2427  *
2428  * Note that the user data to be passed to @error_func can be
2429  * specified when constructing the group with g_option_group_new().
2430  *
2431  * Since: 2.6
2432  **/
2433 void
2434 g_option_group_set_error_hook (GOptionGroup     *group,
2435                                GOptionErrorFunc  error_func)
2436 {
2437   g_return_if_fail (group != NULL);
2438
2439   group->error_func = error_func;
2440 }
2441
2442
2443 /**
2444  * g_option_group_set_translate_func:
2445  * @group: a #GOptionGroup
2446  * @func: (allow-none): the #GTranslateFunc, or %NULL
2447  * @data: (allow-none): user data to pass to @func, or %NULL
2448  * @destroy_notify: (allow-none): a function which gets called to free @data, or %NULL
2449  *
2450  * Sets the function which is used to translate user-visible strings,
2451  * for `--help` output. Different groups can use different
2452  * #GTranslateFuncs. If @func is %NULL, strings are not translated.
2453  *
2454  * If you are using gettext(), you only need to set the translation
2455  * domain, see g_option_group_set_translation_domain().
2456  *
2457  * Since: 2.6
2458  **/
2459 void
2460 g_option_group_set_translate_func (GOptionGroup   *group,
2461                                    GTranslateFunc  func,
2462                                    gpointer        data,
2463                                    GDestroyNotify  destroy_notify)
2464 {
2465   g_return_if_fail (group != NULL);
2466
2467   if (group->translate_notify)
2468     group->translate_notify (group->translate_data);
2469
2470   group->translate_func = func;
2471   group->translate_data = data;
2472   group->translate_notify = destroy_notify;
2473 }
2474
2475 static const gchar *
2476 dgettext_swapped (const gchar *msgid,
2477                   const gchar *domainname)
2478 {
2479   return g_dgettext (domainname, msgid);
2480 }
2481
2482 /**
2483  * g_option_group_set_translation_domain:
2484  * @group: a #GOptionGroup
2485  * @domain: the domain to use
2486  *
2487  * A convenience function to use gettext() for translating
2488  * user-visible strings.
2489  *
2490  * Since: 2.6
2491  **/
2492 void
2493 g_option_group_set_translation_domain (GOptionGroup *group,
2494                                        const gchar  *domain)
2495 {
2496   g_return_if_fail (group != NULL);
2497
2498   g_option_group_set_translate_func (group,
2499                                      (GTranslateFunc)dgettext_swapped,
2500                                      g_strdup (domain),
2501                                      g_free);
2502 }
2503
2504 /**
2505  * g_option_context_set_translate_func:
2506  * @context: a #GOptionContext
2507  * @func: (allow-none): the #GTranslateFunc, or %NULL
2508  * @data: (allow-none): user data to pass to @func, or %NULL
2509  * @destroy_notify: (allow-none): a function which gets called to free @data, or %NULL
2510  *
2511  * Sets the function which is used to translate the contexts
2512  * user-visible strings, for `--help` output. If @func is %NULL,
2513  * strings are not translated.
2514  *
2515  * Note that option groups have their own translation functions,
2516  * this function only affects the @parameter_string (see g_option_context_new()),
2517  * the summary (see g_option_context_set_summary()) and the description
2518  * (see g_option_context_set_description()).
2519  *
2520  * If you are using gettext(), you only need to set the translation
2521  * domain, see g_option_context_set_translation_domain().
2522  *
2523  * Since: 2.12
2524  **/
2525 void
2526 g_option_context_set_translate_func (GOptionContext *context,
2527                                      GTranslateFunc func,
2528                                      gpointer       data,
2529                                      GDestroyNotify destroy_notify)
2530 {
2531   g_return_if_fail (context != NULL);
2532
2533   if (context->translate_notify)
2534     context->translate_notify (context->translate_data);
2535
2536   context->translate_func = func;
2537   context->translate_data = data;
2538   context->translate_notify = destroy_notify;
2539 }
2540
2541 /**
2542  * g_option_context_set_translation_domain:
2543  * @context: a #GOptionContext
2544  * @domain: the domain to use
2545  *
2546  * A convenience function to use gettext() for translating
2547  * user-visible strings.
2548  *
2549  * Since: 2.12
2550  **/
2551 void
2552 g_option_context_set_translation_domain (GOptionContext *context,
2553                                          const gchar     *domain)
2554 {
2555   g_return_if_fail (context != NULL);
2556
2557   g_option_context_set_translate_func (context,
2558                                        (GTranslateFunc)dgettext_swapped,
2559                                        g_strdup (domain),
2560                                        g_free);
2561 }
2562
2563 /**
2564  * g_option_context_set_summary:
2565  * @context: a #GOptionContext
2566  * @summary: (allow-none): a string to be shown in `--help` output
2567  *  before the list of options, or %NULL
2568  *
2569  * Adds a string to be displayed in `--help` output before the list
2570  * of options. This is typically a summary of the program functionality.
2571  *
2572  * Note that the summary is translated (see
2573  * g_option_context_set_translate_func() and
2574  * g_option_context_set_translation_domain()).
2575  *
2576  * Since: 2.12
2577  */
2578 void
2579 g_option_context_set_summary (GOptionContext *context,
2580                               const gchar    *summary)
2581 {
2582   g_return_if_fail (context != NULL);
2583
2584   g_free (context->summary);
2585   context->summary = g_strdup (summary);
2586 }
2587
2588
2589 /**
2590  * g_option_context_get_summary:
2591  * @context: a #GOptionContext
2592  *
2593  * Returns the summary. See g_option_context_set_summary().
2594  *
2595  * Returns: the summary
2596  *
2597  * Since: 2.12
2598  */
2599 const gchar *
2600 g_option_context_get_summary (GOptionContext *context)
2601 {
2602   g_return_val_if_fail (context != NULL, NULL);
2603
2604   return context->summary;
2605 }
2606
2607 /**
2608  * g_option_context_set_description:
2609  * @context: a #GOptionContext
2610  * @description: (allow-none): a string to be shown in `--help` output
2611  *   after the list of options, or %NULL
2612  *
2613  * Adds a string to be displayed in `--help` output after the list
2614  * of options. This text often includes a bug reporting address.
2615  *
2616  * Note that the summary is translated (see
2617  * g_option_context_set_translate_func()).
2618  *
2619  * Since: 2.12
2620  */
2621 void
2622 g_option_context_set_description (GOptionContext *context,
2623                                   const gchar    *description)
2624 {
2625   g_return_if_fail (context != NULL);
2626
2627   g_free (context->description);
2628   context->description = g_strdup (description);
2629 }
2630
2631
2632 /**
2633  * g_option_context_get_description:
2634  * @context: a #GOptionContext
2635  *
2636  * Returns the description. See g_option_context_set_description().
2637  *
2638  * Returns: the description
2639  *
2640  * Since: 2.12
2641  */
2642 const gchar *
2643 g_option_context_get_description (GOptionContext *context)
2644 {
2645   g_return_val_if_fail (context != NULL, NULL);
2646
2647   return context->description;
2648 }
2649
2650 /**
2651  * g_option_context_parse_strv:
2652  * @context: a #GOptionContext
2653  * @arguments: (inout) (array null-terminated=1): a pointer to the
2654  *    command line arguments (which must be in UTF-8 on Windows)
2655  * @error: a return location for errors
2656  *
2657  * Parses the command line arguments.
2658  *
2659  * This function is similar to g_option_context_parse() except that it
2660  * respects the normal memory rules when dealing with a strv instead of
2661  * assuming that the passed-in array is the argv of the main function.
2662  *
2663  * In particular, strings that are removed from the arguments list will
2664  * be freed using g_free().
2665  *
2666  * On Windows, the strings are expected to be in UTF-8.  This is in
2667  * contrast to g_option_context_parse() which expects them to be in the
2668  * system codepage, which is how they are passed as @argv to main().
2669  * See g_win32_get_command_line() for a solution.
2670  *
2671  * This function is useful if you are trying to use #GOptionContext with
2672  * #GApplication.
2673  *
2674  * Returns: %TRUE if the parsing was successful,
2675  *          %FALSE if an error occurred
2676  *
2677  * Since: 2.40
2678  **/
2679 gboolean
2680 g_option_context_parse_strv (GOptionContext   *context,
2681                              gchar          ***arguments,
2682                              GError          **error)
2683 {
2684   gboolean success;
2685   gint argc;
2686
2687   context->strv_mode = TRUE;
2688   argc = g_strv_length (*arguments);
2689   success = g_option_context_parse (context, &argc, arguments, error);
2690   context->strv_mode = FALSE;
2691
2692   return success;
2693 }