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