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