Imported Upstream version 2.61.1
[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 (entries != NULL);
659
660   if (!context->main_group)
661     context->main_group = g_option_group_new (NULL, NULL, NULL, NULL, NULL);
662
663   g_option_group_add_entries (context->main_group, entries);
664   g_option_group_set_translation_domain (context->main_group, translation_domain);
665 }
666
667 static gint
668 calculate_max_length (GOptionGroup *group,
669                       GHashTable   *aliases)
670 {
671   GOptionEntry *entry;
672   gsize i, len, max_length;
673   const gchar *long_name;
674
675   max_length = 0;
676
677   for (i = 0; i < group->n_entries; i++)
678     {
679       entry = &group->entries[i];
680
681       if (entry->flags & G_OPTION_FLAG_HIDDEN)
682         continue;
683
684       long_name = g_hash_table_lookup (aliases, &entry->long_name);
685       if (!long_name)
686         long_name = entry->long_name;
687       len = _g_utf8_strwidth (long_name);
688
689       if (entry->short_name)
690         len += 4;
691
692       if (!NO_ARG (entry) && entry->arg_description)
693         len += 1 + _g_utf8_strwidth (TRANSLATE (group, entry->arg_description));
694
695       max_length = MAX (max_length, len);
696     }
697
698   return max_length;
699 }
700
701 static void
702 print_entry (GOptionGroup       *group,
703              gint                max_length,
704              const GOptionEntry *entry,
705              GString            *string,
706              GHashTable         *aliases)
707 {
708   GString *str;
709   const gchar *long_name;
710
711   if (entry->flags & G_OPTION_FLAG_HIDDEN)
712     return;
713
714   if (entry->long_name[0] == 0)
715     return;
716
717   long_name = g_hash_table_lookup (aliases, &entry->long_name);
718   if (!long_name)
719     long_name = entry->long_name;
720
721   str = g_string_new (NULL);
722
723   if (entry->short_name)
724     g_string_append_printf (str, "  -%c, --%s", entry->short_name, long_name);
725   else
726     g_string_append_printf (str, "  --%s", long_name);
727
728   if (entry->arg_description)
729     g_string_append_printf (str, "=%s", TRANSLATE (group, entry->arg_description));
730
731   g_string_append_printf (string, "%s%*s %s\n", str->str,
732                           (int) (max_length + 4 - _g_utf8_strwidth (str->str)), "",
733                           entry->description ? TRANSLATE (group, entry->description) : "");
734   g_string_free (str, TRUE);
735 }
736
737 static gboolean
738 group_has_visible_entries (GOptionContext *context,
739                            GOptionGroup *group,
740                            gboolean      main_entries)
741 {
742   GOptionFlags reject_filter = G_OPTION_FLAG_HIDDEN;
743   GOptionEntry *entry;
744   gint i, l;
745   gboolean main_group = group == context->main_group;
746
747   if (!main_entries)
748     reject_filter |= G_OPTION_FLAG_IN_MAIN;
749
750   for (i = 0, l = (group ? group->n_entries : 0); i < l; i++)
751     {
752       entry = &group->entries[i];
753
754       if (main_entries && !main_group && !(entry->flags & G_OPTION_FLAG_IN_MAIN))
755         continue;
756       if (entry->long_name[0] == 0) /* ignore rest entry */
757         continue;
758       if (!(entry->flags & reject_filter))
759         return TRUE;
760     }
761
762   return FALSE;
763 }
764
765 static gboolean
766 group_list_has_visible_entries (GOptionContext *context,
767                                 GList          *group_list,
768                                 gboolean       main_entries)
769 {
770   while (group_list)
771     {
772       if (group_has_visible_entries (context, group_list->data, main_entries))
773         return TRUE;
774
775       group_list = group_list->next;
776     }
777
778   return FALSE;
779 }
780
781 static gboolean
782 context_has_h_entry (GOptionContext *context)
783 {
784   gsize i;
785   GList *list;
786
787   if (context->main_group)
788     {
789       for (i = 0; i < context->main_group->n_entries; i++)
790         {
791           if (context->main_group->entries[i].short_name == 'h')
792             return TRUE;
793         }
794     }
795
796   for (list = context->groups; list != NULL; list = g_list_next (list))
797     {
798      GOptionGroup *group;
799
800       group = (GOptionGroup*)list->data;
801       for (i = 0; i < group->n_entries; i++)
802         {
803           if (group->entries[i].short_name == 'h')
804             return TRUE;
805         }
806     }
807   return FALSE;
808 }
809
810 /**
811  * g_option_context_get_help:
812  * @context: a #GOptionContext
813  * @main_help: if %TRUE, only include the main group
814  * @group: (nullable): the #GOptionGroup to create help for, or %NULL
815  *
816  * Returns a formatted, translated help text for the given context.
817  * To obtain the text produced by `--help`, call
818  * `g_option_context_get_help (context, TRUE, NULL)`.
819  * To obtain the text produced by `--help-all`, call
820  * `g_option_context_get_help (context, FALSE, NULL)`.
821  * To obtain the help text for an option group, call
822  * `g_option_context_get_help (context, FALSE, group)`.
823  *
824  * Returns: A newly allocated string containing the help text
825  *
826  * Since: 2.14
827  */
828 gchar *
829 g_option_context_get_help (GOptionContext *context,
830                            gboolean        main_help,
831                            GOptionGroup   *group)
832 {
833   GList *list;
834   gint max_length = 0, len;
835   gsize i;
836   GOptionEntry *entry;
837   GHashTable *shadow_map;
838   GHashTable *aliases;
839   gboolean seen[256];
840   const gchar *rest_description;
841   GString *string;
842   guchar token;
843
844   string = g_string_sized_new (1024);
845
846   rest_description = NULL;
847   if (context->main_group)
848     {
849
850       for (i = 0; i < context->main_group->n_entries; i++)
851         {
852           entry = &context->main_group->entries[i];
853           if (entry->long_name[0] == 0)
854             {
855               rest_description = TRANSLATE (context->main_group, entry->arg_description);
856               break;
857             }
858         }
859     }
860
861   g_string_append_printf (string, "%s\n  %s", _("Usage:"), g_get_prgname ());
862   if (context->help_enabled ||
863       (context->main_group && context->main_group->n_entries > 0) ||
864       context->groups != NULL)
865     g_string_append_printf (string, " %s", _("[OPTION…]"));
866
867   if (rest_description)
868     {
869       g_string_append (string, " ");
870       g_string_append (string, rest_description);
871     }
872
873   if (context->parameter_string)
874     {
875       g_string_append (string, " ");
876       g_string_append (string, TRANSLATE (context, context->parameter_string));
877     }
878
879   g_string_append (string, "\n\n");
880
881   if (context->summary)
882     {
883       g_string_append (string, TRANSLATE (context, context->summary));
884       g_string_append (string, "\n\n");
885     }
886
887   memset (seen, 0, sizeof (gboolean) * 256);
888   shadow_map = g_hash_table_new (g_str_hash, g_str_equal);
889   aliases = g_hash_table_new_full (NULL, NULL, NULL, g_free);
890
891   if (context->main_group)
892     {
893       for (i = 0; i < context->main_group->n_entries; i++)
894         {
895           entry = &context->main_group->entries[i];
896           g_hash_table_insert (shadow_map,
897                                (gpointer)entry->long_name,
898                                entry);
899
900           if (seen[(guchar)entry->short_name])
901             entry->short_name = 0;
902           else
903             seen[(guchar)entry->short_name] = TRUE;
904         }
905     }
906
907   list = context->groups;
908   while (list != NULL)
909     {
910       GOptionGroup *g = list->data;
911       for (i = 0; i < g->n_entries; i++)
912         {
913           entry = &g->entries[i];
914           if (g_hash_table_lookup (shadow_map, entry->long_name) &&
915               !(entry->flags & G_OPTION_FLAG_NOALIAS))
916             {
917               g_hash_table_insert (aliases, &entry->long_name,
918                                    g_strdup_printf ("%s-%s", g->name, entry->long_name));
919             }
920           else
921             g_hash_table_insert (shadow_map, (gpointer)entry->long_name, entry);
922
923           if (seen[(guchar)entry->short_name] &&
924               !(entry->flags & G_OPTION_FLAG_NOALIAS))
925             entry->short_name = 0;
926           else
927             seen[(guchar)entry->short_name] = TRUE;
928         }
929       list = list->next;
930     }
931
932   g_hash_table_destroy (shadow_map);
933
934   list = context->groups;
935
936   if (context->help_enabled)
937     {
938       max_length = _g_utf8_strwidth ("-?, --help");
939
940       if (list)
941         {
942           len = _g_utf8_strwidth ("--help-all");
943           max_length = MAX (max_length, len);
944         }
945     }
946
947   if (context->main_group)
948     {
949       len = calculate_max_length (context->main_group, aliases);
950       max_length = MAX (max_length, len);
951     }
952
953   while (list != NULL)
954     {
955       GOptionGroup *g = list->data;
956
957       if (context->help_enabled)
958         {
959           /* First, we check the --help-<groupname> options */
960           len = _g_utf8_strwidth ("--help-") + _g_utf8_strwidth (g->name);
961           max_length = MAX (max_length, len);
962         }
963
964       /* Then we go through the entries */
965       len = calculate_max_length (g, aliases);
966       max_length = MAX (max_length, len);
967
968       list = list->next;
969     }
970
971   /* Add a bit of padding */
972   max_length += 4;
973
974   if (!group && context->help_enabled)
975     {
976       list = context->groups;
977
978       token = context_has_h_entry (context) ? '?' : 'h';
979
980       g_string_append_printf (string, "%s\n  -%c, --%-*s %s\n",
981                               _("Help Options:"), token, max_length - 4, "help",
982                               _("Show help options"));
983
984       /* We only want --help-all when there are groups */
985       if (list)
986         g_string_append_printf (string, "  --%-*s %s\n",
987                                 max_length, "help-all",
988                                 _("Show all help options"));
989
990       while (list)
991         {
992           GOptionGroup *g = list->data;
993
994           if (group_has_visible_entries (context, g, FALSE))
995             g_string_append_printf (string, "  --help-%-*s %s\n",
996                                     max_length - 5, g->name,
997                                     TRANSLATE (g, g->help_description));
998
999           list = list->next;
1000         }
1001
1002       g_string_append (string, "\n");
1003     }
1004
1005   if (group)
1006     {
1007       /* Print a certain group */
1008
1009       if (group_has_visible_entries (context, group, FALSE))
1010         {
1011           g_string_append (string, TRANSLATE (group, group->description));
1012           g_string_append (string, "\n");
1013           for (i = 0; i < group->n_entries; i++)
1014             print_entry (group, max_length, &group->entries[i], string, aliases);
1015           g_string_append (string, "\n");
1016         }
1017     }
1018   else if (!main_help)
1019     {
1020       /* Print all groups */
1021
1022       list = context->groups;
1023
1024       while (list)
1025         {
1026           GOptionGroup *g = list->data;
1027
1028           if (group_has_visible_entries (context, g, FALSE))
1029             {
1030               g_string_append (string, g->description);
1031               g_string_append (string, "\n");
1032               for (i = 0; i < g->n_entries; i++)
1033                 if (!(g->entries[i].flags & G_OPTION_FLAG_IN_MAIN))
1034                   print_entry (g, max_length, &g->entries[i], string, aliases);
1035
1036               g_string_append (string, "\n");
1037             }
1038
1039           list = list->next;
1040         }
1041     }
1042
1043   /* Print application options if --help or --help-all has been specified */
1044   if ((main_help || !group) &&
1045       (group_has_visible_entries (context, context->main_group, TRUE) ||
1046        group_list_has_visible_entries (context, context->groups, TRUE)))
1047     {
1048       list = context->groups;
1049
1050       if (context->help_enabled || list)
1051         g_string_append (string,  _("Application Options:"));
1052       else
1053         g_string_append (string, _("Options:"));
1054       g_string_append (string, "\n");
1055       if (context->main_group)
1056         for (i = 0; i < context->main_group->n_entries; i++)
1057           print_entry (context->main_group, max_length,
1058                        &context->main_group->entries[i], string, aliases);
1059
1060       while (list != NULL)
1061         {
1062           GOptionGroup *g = list->data;
1063
1064           /* Print main entries from other groups */
1065           for (i = 0; i < g->n_entries; i++)
1066             if (g->entries[i].flags & G_OPTION_FLAG_IN_MAIN)
1067               print_entry (g, max_length, &g->entries[i], string, aliases);
1068
1069           list = list->next;
1070         }
1071
1072       g_string_append (string, "\n");
1073     }
1074
1075   if (context->description)
1076     {
1077       g_string_append (string, TRANSLATE (context, context->description));
1078       g_string_append (string, "\n");
1079     }
1080
1081   g_hash_table_destroy (aliases);
1082
1083   return g_string_free (string, FALSE);
1084 }
1085
1086 G_GNUC_NORETURN
1087 static void
1088 print_help (GOptionContext *context,
1089             gboolean        main_help,
1090             GOptionGroup   *group)
1091 {
1092   gchar *help;
1093
1094   help = g_option_context_get_help (context, main_help, group);
1095   g_print ("%s", help);
1096   g_free (help);
1097
1098   exit (0);
1099 }
1100
1101 static gboolean
1102 parse_int (const gchar *arg_name,
1103            const gchar *arg,
1104            gint        *result,
1105            GError     **error)
1106 {
1107   gchar *end;
1108   glong tmp;
1109
1110   errno = 0;
1111   tmp = strtol (arg, &end, 0);
1112
1113   if (*arg == '\0' || *end != '\0')
1114     {
1115       g_set_error (error,
1116                    G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1117                    _("Cannot parse integer value “%s” for %s"),
1118                    arg, arg_name);
1119       return FALSE;
1120     }
1121
1122   *result = tmp;
1123   if (*result != tmp || errno == ERANGE)
1124     {
1125       g_set_error (error,
1126                    G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1127                    _("Integer value “%s” for %s out of range"),
1128                    arg, arg_name);
1129       return FALSE;
1130     }
1131
1132   return TRUE;
1133 }
1134
1135
1136 static gboolean
1137 parse_double (const gchar *arg_name,
1138            const gchar *arg,
1139            gdouble        *result,
1140            GError     **error)
1141 {
1142   gchar *end;
1143   gdouble tmp;
1144
1145   errno = 0;
1146   tmp = g_strtod (arg, &end);
1147
1148   if (*arg == '\0' || *end != '\0')
1149     {
1150       g_set_error (error,
1151                    G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1152                    _("Cannot parse double value “%s” for %s"),
1153                    arg, arg_name);
1154       return FALSE;
1155     }
1156   if (errno == ERANGE)
1157     {
1158       g_set_error (error,
1159                    G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1160                    _("Double value “%s” for %s out of range"),
1161                    arg, arg_name);
1162       return FALSE;
1163     }
1164
1165   *result = tmp;
1166
1167   return TRUE;
1168 }
1169
1170
1171 static gboolean
1172 parse_int64 (const gchar *arg_name,
1173              const gchar *arg,
1174              gint64      *result,
1175              GError     **error)
1176 {
1177   gchar *end;
1178   gint64 tmp;
1179
1180   errno = 0;
1181   tmp = g_ascii_strtoll (arg, &end, 0);
1182
1183   if (*arg == '\0' || *end != '\0')
1184     {
1185       g_set_error (error,
1186                    G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1187                    _("Cannot parse integer value “%s” for %s"),
1188                    arg, arg_name);
1189       return FALSE;
1190     }
1191   if (errno == ERANGE)
1192     {
1193       g_set_error (error,
1194                    G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1195                    _("Integer value “%s” for %s out of range"),
1196                    arg, arg_name);
1197       return FALSE;
1198     }
1199
1200   *result = tmp;
1201
1202   return TRUE;
1203 }
1204
1205
1206 static Change *
1207 get_change (GOptionContext *context,
1208             GOptionArg      arg_type,
1209             gpointer        arg_data)
1210 {
1211   GList *list;
1212   Change *change = NULL;
1213
1214   for (list = context->changes; list != NULL; list = list->next)
1215     {
1216       change = list->data;
1217
1218       if (change->arg_data == arg_data)
1219         goto found;
1220     }
1221
1222   change = g_new0 (Change, 1);
1223   change->arg_type = arg_type;
1224   change->arg_data = arg_data;
1225
1226   context->changes = g_list_prepend (context->changes, change);
1227
1228  found:
1229
1230   return change;
1231 }
1232
1233 static void
1234 add_pending_null (GOptionContext *context,
1235                   gchar         **ptr,
1236                   gchar          *value)
1237 {
1238   PendingNull *n;
1239
1240   n = g_new0 (PendingNull, 1);
1241   n->ptr = ptr;
1242   n->value = value;
1243
1244   context->pending_nulls = g_list_prepend (context->pending_nulls, n);
1245 }
1246
1247 static gboolean
1248 parse_arg (GOptionContext *context,
1249            GOptionGroup   *group,
1250            GOptionEntry   *entry,
1251            const gchar    *value,
1252            const gchar    *option_name,
1253            GError        **error)
1254
1255 {
1256   Change *change;
1257
1258   g_assert (value || OPTIONAL_ARG (entry) || NO_ARG (entry));
1259
1260   switch (entry->arg)
1261     {
1262     case G_OPTION_ARG_NONE:
1263       {
1264         (void) get_change (context, G_OPTION_ARG_NONE,
1265                            entry->arg_data);
1266
1267         *(gboolean *)entry->arg_data = !(entry->flags & G_OPTION_FLAG_REVERSE);
1268         break;
1269       }
1270     case G_OPTION_ARG_STRING:
1271       {
1272         gchar *data;
1273
1274 #ifdef G_OS_WIN32
1275         if (!context->strv_mode)
1276           data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1277         else
1278           data = g_strdup (value);
1279 #else
1280         data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1281 #endif
1282
1283         if (!data)
1284           return FALSE;
1285
1286         change = get_change (context, G_OPTION_ARG_STRING,
1287                              entry->arg_data);
1288
1289         if (!change->allocated.str)
1290           change->prev.str = *(gchar **)entry->arg_data;
1291         else
1292           g_free (change->allocated.str);
1293
1294         change->allocated.str = data;
1295
1296         *(gchar **)entry->arg_data = data;
1297         break;
1298       }
1299     case G_OPTION_ARG_STRING_ARRAY:
1300       {
1301         gchar *data;
1302
1303 #ifdef G_OS_WIN32
1304         if (!context->strv_mode)
1305           data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1306         else
1307           data = g_strdup (value);
1308 #else
1309         data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1310 #endif
1311
1312         if (!data)
1313           return FALSE;
1314
1315         change = get_change (context, G_OPTION_ARG_STRING_ARRAY,
1316                              entry->arg_data);
1317
1318         if (change->allocated.array.len == 0)
1319           {
1320             change->prev.array = *(gchar ***)entry->arg_data;
1321             change->allocated.array.data = g_new (gchar *, 2);
1322           }
1323         else
1324           change->allocated.array.data =
1325             g_renew (gchar *, change->allocated.array.data,
1326                      change->allocated.array.len + 2);
1327
1328         change->allocated.array.data[change->allocated.array.len] = data;
1329         change->allocated.array.data[change->allocated.array.len + 1] = NULL;
1330
1331         change->allocated.array.len ++;
1332
1333         *(gchar ***)entry->arg_data = change->allocated.array.data;
1334
1335         break;
1336       }
1337
1338     case G_OPTION_ARG_FILENAME:
1339       {
1340         gchar *data;
1341
1342 #ifdef G_OS_WIN32
1343         if (!context->strv_mode)
1344           data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1345         else
1346           data = g_strdup (value);
1347
1348         if (!data)
1349           return FALSE;
1350 #else
1351         data = g_strdup (value);
1352 #endif
1353         change = get_change (context, G_OPTION_ARG_FILENAME,
1354                              entry->arg_data);
1355
1356         if (!change->allocated.str)
1357           change->prev.str = *(gchar **)entry->arg_data;
1358         else
1359           g_free (change->allocated.str);
1360
1361         change->allocated.str = data;
1362
1363         *(gchar **)entry->arg_data = data;
1364         break;
1365       }
1366
1367     case G_OPTION_ARG_FILENAME_ARRAY:
1368       {
1369         gchar *data;
1370
1371 #ifdef G_OS_WIN32
1372         if (!context->strv_mode)
1373           data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1374         else
1375           data = g_strdup (value);
1376
1377         if (!data)
1378           return FALSE;
1379 #else
1380         data = g_strdup (value);
1381 #endif
1382         change = get_change (context, G_OPTION_ARG_STRING_ARRAY,
1383                              entry->arg_data);
1384
1385         if (change->allocated.array.len == 0)
1386           {
1387             change->prev.array = *(gchar ***)entry->arg_data;
1388             change->allocated.array.data = g_new (gchar *, 2);
1389           }
1390         else
1391           change->allocated.array.data =
1392             g_renew (gchar *, change->allocated.array.data,
1393                      change->allocated.array.len + 2);
1394
1395         change->allocated.array.data[change->allocated.array.len] = data;
1396         change->allocated.array.data[change->allocated.array.len + 1] = NULL;
1397
1398         change->allocated.array.len ++;
1399
1400         *(gchar ***)entry->arg_data = change->allocated.array.data;
1401
1402         break;
1403       }
1404
1405     case G_OPTION_ARG_INT:
1406       {
1407         gint data;
1408
1409         if (!parse_int (option_name, value,
1410                         &data,
1411                         error))
1412           return FALSE;
1413
1414         change = get_change (context, G_OPTION_ARG_INT,
1415                              entry->arg_data);
1416         change->prev.integer = *(gint *)entry->arg_data;
1417         *(gint *)entry->arg_data = data;
1418         break;
1419       }
1420     case G_OPTION_ARG_CALLBACK:
1421       {
1422         gchar *data;
1423         gboolean retval;
1424
1425         if (!value && entry->flags & G_OPTION_FLAG_OPTIONAL_ARG)
1426           data = NULL;
1427         else if (entry->flags & G_OPTION_FLAG_NO_ARG)
1428           data = NULL;
1429         else if (entry->flags & G_OPTION_FLAG_FILENAME)
1430           {
1431 #ifdef G_OS_WIN32
1432             if (!context->strv_mode)
1433               data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1434             else
1435               data = g_strdup (value);
1436 #else
1437             data = g_strdup (value);
1438 #endif
1439           }
1440         else
1441           data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1442
1443         if (!(entry->flags & (G_OPTION_FLAG_NO_ARG|G_OPTION_FLAG_OPTIONAL_ARG)) &&
1444             !data)
1445           return FALSE;
1446
1447         retval = (* (GOptionArgFunc) entry->arg_data) (option_name, data, group->user_data, error);
1448
1449         if (!retval && error != NULL && *error == NULL)
1450           g_set_error (error,
1451                        G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
1452                        _("Error parsing option %s"), option_name);
1453
1454         g_free (data);
1455
1456         return retval;
1457
1458         break;
1459       }
1460     case G_OPTION_ARG_DOUBLE:
1461       {
1462         gdouble data;
1463
1464         if (!parse_double (option_name, value,
1465                         &data,
1466                         error))
1467           {
1468             return FALSE;
1469           }
1470
1471         change = get_change (context, G_OPTION_ARG_DOUBLE,
1472                              entry->arg_data);
1473         change->prev.dbl = *(gdouble *)entry->arg_data;
1474         *(gdouble *)entry->arg_data = data;
1475         break;
1476       }
1477     case G_OPTION_ARG_INT64:
1478       {
1479         gint64 data;
1480
1481         if (!parse_int64 (option_name, value,
1482                          &data,
1483                          error))
1484           {
1485             return FALSE;
1486           }
1487
1488         change = get_change (context, G_OPTION_ARG_INT64,
1489                              entry->arg_data);
1490         change->prev.int64 = *(gint64 *)entry->arg_data;
1491         *(gint64 *)entry->arg_data = data;
1492         break;
1493       }
1494     default:
1495       g_assert_not_reached ();
1496     }
1497
1498   return TRUE;
1499 }
1500
1501 static gboolean
1502 parse_short_option (GOptionContext *context,
1503                     GOptionGroup   *group,
1504                     gint            idx,
1505                     gint           *new_idx,
1506                     gchar           arg,
1507                     gint           *argc,
1508                     gchar        ***argv,
1509                     GError        **error,
1510                     gboolean       *parsed)
1511 {
1512   gsize j;
1513
1514   for (j = 0; j < group->n_entries; j++)
1515     {
1516       if (arg == group->entries[j].short_name)
1517         {
1518           gchar *option_name;
1519           gchar *value = NULL;
1520
1521           option_name = g_strdup_printf ("-%c", group->entries[j].short_name);
1522
1523           if (NO_ARG (&group->entries[j]))
1524             value = NULL;
1525           else
1526             {
1527               if (*new_idx > idx)
1528                 {
1529                   g_set_error (error,
1530                                G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
1531                                _("Error parsing option %s"), option_name);
1532                   g_free (option_name);
1533                   return FALSE;
1534                 }
1535
1536               if (idx < *argc - 1)
1537                 {
1538                   if (!OPTIONAL_ARG (&group->entries[j]))
1539                     {
1540                       value = (*argv)[idx + 1];
1541                       add_pending_null (context, &((*argv)[idx + 1]), NULL);
1542                       *new_idx = idx + 1;
1543                     }
1544                   else
1545                     {
1546                       if ((*argv)[idx + 1][0] == '-')
1547                         value = NULL;
1548                       else
1549                         {
1550                           value = (*argv)[idx + 1];
1551                           add_pending_null (context, &((*argv)[idx + 1]), NULL);
1552                           *new_idx = idx + 1;
1553                         }
1554                     }
1555                 }
1556               else if (idx >= *argc - 1 && OPTIONAL_ARG (&group->entries[j]))
1557                 value = NULL;
1558               else
1559                 {
1560                   g_set_error (error,
1561                                G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1562                                _("Missing argument for %s"), option_name);
1563                   g_free (option_name);
1564                   return FALSE;
1565                 }
1566             }
1567
1568           if (!parse_arg (context, group, &group->entries[j],
1569                           value, option_name, error))
1570             {
1571               g_free (option_name);
1572               return FALSE;
1573             }
1574
1575           g_free (option_name);
1576           *parsed = TRUE;
1577         }
1578     }
1579
1580   return TRUE;
1581 }
1582
1583 static gboolean
1584 parse_long_option (GOptionContext *context,
1585                    GOptionGroup   *group,
1586                    gint           *idx,
1587                    gchar          *arg,
1588                    gboolean        aliased,
1589                    gint           *argc,
1590                    gchar        ***argv,
1591                    GError        **error,
1592                    gboolean       *parsed)
1593 {
1594   gsize j;
1595
1596   for (j = 0; j < group->n_entries; j++)
1597     {
1598       if (*idx >= *argc)
1599         return TRUE;
1600
1601       if (aliased && (group->entries[j].flags & G_OPTION_FLAG_NOALIAS))
1602         continue;
1603
1604       if (NO_ARG (&group->entries[j]) &&
1605           strcmp (arg, group->entries[j].long_name) == 0)
1606         {
1607           gchar *option_name;
1608           gboolean retval;
1609
1610           option_name = g_strconcat ("--", group->entries[j].long_name, NULL);
1611           retval = parse_arg (context, group, &group->entries[j],
1612                               NULL, option_name, error);
1613           g_free (option_name);
1614
1615           add_pending_null (context, &((*argv)[*idx]), NULL);
1616           *parsed = TRUE;
1617
1618           return retval;
1619         }
1620       else
1621         {
1622           gint len = strlen (group->entries[j].long_name);
1623
1624           if (strncmp (arg, group->entries[j].long_name, len) == 0 &&
1625               (arg[len] == '=' || arg[len] == 0))
1626             {
1627               gchar *value = NULL;
1628               gchar *option_name;
1629
1630               add_pending_null (context, &((*argv)[*idx]), NULL);
1631               option_name = g_strconcat ("--", group->entries[j].long_name, NULL);
1632
1633               if (arg[len] == '=')
1634                 value = arg + len + 1;
1635               else if (*idx < *argc - 1)
1636                 {
1637                   if (!OPTIONAL_ARG (&group->entries[j]))
1638                     {
1639                       value = (*argv)[*idx + 1];
1640                       add_pending_null (context, &((*argv)[*idx + 1]), NULL);
1641                       (*idx)++;
1642                     }
1643                   else
1644                     {
1645                       if ((*argv)[*idx + 1][0] == '-')
1646                         {
1647                           gboolean retval;
1648                           retval = parse_arg (context, group, &group->entries[j],
1649                                               NULL, option_name, error);
1650                           *parsed = TRUE;
1651                           g_free (option_name);
1652                           return retval;
1653                         }
1654                       else
1655                         {
1656                           value = (*argv)[*idx + 1];
1657                           add_pending_null (context, &((*argv)[*idx + 1]), NULL);
1658                           (*idx)++;
1659                         }
1660                     }
1661                 }
1662               else if (*idx >= *argc - 1 && OPTIONAL_ARG (&group->entries[j]))
1663                 {
1664                     gboolean retval;
1665                     retval = parse_arg (context, group, &group->entries[j],
1666                                         NULL, option_name, error);
1667                     *parsed = TRUE;
1668                     g_free (option_name);
1669                     return retval;
1670                 }
1671               else
1672                 {
1673                   g_set_error (error,
1674                                G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1675                                _("Missing argument for %s"), option_name);
1676                   g_free (option_name);
1677                   return FALSE;
1678                 }
1679
1680               if (!parse_arg (context, group, &group->entries[j],
1681                               value, option_name, error))
1682                 {
1683                   g_free (option_name);
1684                   return FALSE;
1685                 }
1686
1687               g_free (option_name);
1688               *parsed = TRUE;
1689             }
1690         }
1691     }
1692
1693   return TRUE;
1694 }
1695
1696 static gboolean
1697 parse_remaining_arg (GOptionContext *context,
1698                      GOptionGroup   *group,
1699                      gint           *idx,
1700                      gint           *argc,
1701                      gchar        ***argv,
1702                      GError        **error,
1703                      gboolean       *parsed)
1704 {
1705   gsize j;
1706
1707   for (j = 0; j < group->n_entries; j++)
1708     {
1709       if (*idx >= *argc)
1710         return TRUE;
1711
1712       if (group->entries[j].long_name[0])
1713         continue;
1714
1715       g_return_val_if_fail (group->entries[j].arg == G_OPTION_ARG_CALLBACK ||
1716                             group->entries[j].arg == G_OPTION_ARG_STRING_ARRAY ||
1717                             group->entries[j].arg == G_OPTION_ARG_FILENAME_ARRAY, FALSE);
1718
1719       add_pending_null (context, &((*argv)[*idx]), NULL);
1720
1721       if (!parse_arg (context, group, &group->entries[j], (*argv)[*idx], "", error))
1722         return FALSE;
1723
1724       *parsed = TRUE;
1725       return TRUE;
1726     }
1727
1728   return TRUE;
1729 }
1730
1731 static void
1732 free_changes_list (GOptionContext *context,
1733                    gboolean        revert)
1734 {
1735   GList *list;
1736
1737   for (list = context->changes; list != NULL; list = list->next)
1738     {
1739       Change *change = list->data;
1740
1741       if (revert)
1742         {
1743           switch (change->arg_type)
1744             {
1745             case G_OPTION_ARG_NONE:
1746               *(gboolean *)change->arg_data = change->prev.bool;
1747               break;
1748             case G_OPTION_ARG_INT:
1749               *(gint *)change->arg_data = change->prev.integer;
1750               break;
1751             case G_OPTION_ARG_STRING:
1752             case G_OPTION_ARG_FILENAME:
1753               g_free (change->allocated.str);
1754               *(gchar **)change->arg_data = change->prev.str;
1755               break;
1756             case G_OPTION_ARG_STRING_ARRAY:
1757             case G_OPTION_ARG_FILENAME_ARRAY:
1758               g_strfreev (change->allocated.array.data);
1759               *(gchar ***)change->arg_data = change->prev.array;
1760               break;
1761             case G_OPTION_ARG_DOUBLE:
1762               *(gdouble *)change->arg_data = change->prev.dbl;
1763               break;
1764             case G_OPTION_ARG_INT64:
1765               *(gint64 *)change->arg_data = change->prev.int64;
1766               break;
1767             default:
1768               g_assert_not_reached ();
1769             }
1770         }
1771
1772       g_free (change);
1773     }
1774
1775   g_list_free (context->changes);
1776   context->changes = NULL;
1777 }
1778
1779 static void
1780 free_pending_nulls (GOptionContext *context,
1781                     gboolean        perform_nulls)
1782 {
1783   GList *list;
1784
1785   for (list = context->pending_nulls; list != NULL; list = list->next)
1786     {
1787       PendingNull *n = list->data;
1788
1789       if (perform_nulls)
1790         {
1791           if (n->value)
1792             {
1793               /* Copy back the short options */
1794               *(n->ptr)[0] = '-';
1795               strcpy (*n->ptr + 1, n->value);
1796             }
1797           else
1798             {
1799               if (context->strv_mode)
1800                 g_free (*n->ptr);
1801
1802               *n->ptr = NULL;
1803             }
1804         }
1805
1806       g_free (n->value);
1807       g_free (n);
1808     }
1809
1810   g_list_free (context->pending_nulls);
1811   context->pending_nulls = NULL;
1812 }
1813
1814 /* Use a platform-specific mechanism to look up the first argument to
1815  * the current process. 
1816  * Note if you implement this for other platforms, also add it to
1817  * tests/option-argv0.c
1818  */
1819 static char *
1820 platform_get_argv0 (void)
1821 {
1822 #ifdef HAVE_PROC_SELF_CMDLINE
1823   char *cmdline;
1824   char *base_arg0;
1825   gsize len;
1826
1827   if (!g_file_get_contents ("/proc/self/cmdline",
1828                             &cmdline,
1829                             &len,
1830                             NULL))
1831     return NULL;
1832   /* Sanity check for a NUL terminator. */
1833   if (!memchr (cmdline, 0, len))
1834     return NULL;
1835   /* We could just return cmdline, but I think it's better
1836    * to hold on to a smaller malloc block; the arguments
1837    * could be large.
1838    */
1839   base_arg0 = g_path_get_basename (cmdline);
1840   g_free (cmdline);
1841   return base_arg0;
1842 #elif defined __OpenBSD__
1843   char **cmdline;
1844   char *base_arg0;
1845   gsize len;
1846
1847   int mib[] = { CTL_KERN, KERN_PROC_ARGS, getpid(), KERN_PROC_ARGV };
1848
1849   if (sysctl (mib, G_N_ELEMENTS (mib), NULL, &len, NULL, 0) == -1)
1850       return NULL;
1851
1852   cmdline = g_malloc0 (len);
1853
1854   if (sysctl (mib, G_N_ELEMENTS (mib), cmdline, &len, NULL, 0) == -1)
1855     {
1856       g_free (cmdline);
1857       return NULL;
1858     }
1859
1860   /* We could just return cmdline, but I think it's better
1861    * to hold on to a smaller malloc block; the arguments
1862    * could be large.
1863    */
1864   base_arg0 = g_path_get_basename (*cmdline);
1865   g_free (cmdline);
1866   return base_arg0;
1867 #elif defined G_OS_WIN32
1868   const wchar_t *cmdline;
1869   wchar_t **wargv;
1870   int wargc;
1871   gchar *utf8_buf = NULL;
1872   char *base_arg0 = NULL;
1873
1874   /* Pretend it's const, since we're not allowed to free it */
1875   cmdline = (const wchar_t *) GetCommandLineW ();
1876   if (G_UNLIKELY (cmdline == NULL))
1877     return NULL;
1878
1879   /* Skip leading whitespace. CommandLineToArgvW() is documented
1880    * to behave weirdly with that. The character codes below
1881    * correspond to the *only* unicode characters that are
1882    * considered to be spaces by CommandLineToArgvW(). The rest
1883    * (such as 0xa0 - NO-BREAK SPACE) are treated as
1884    * normal characters.
1885    */
1886   while (cmdline[0] == 0x09 ||
1887          cmdline[0] == 0x0a ||
1888          cmdline[0] == 0x0c ||
1889          cmdline[0] == 0x0d ||
1890          cmdline[0] == 0x20)
1891     cmdline++;
1892
1893   wargv = CommandLineToArgvW (cmdline, &wargc);
1894   if (G_UNLIKELY (wargv == NULL))
1895     return NULL;
1896
1897   if (wargc > 0)
1898     utf8_buf = g_utf16_to_utf8 (wargv[0], -1, NULL, NULL, NULL);
1899
1900   LocalFree (wargv);
1901
1902   if (G_UNLIKELY (utf8_buf == NULL))
1903     return NULL;
1904
1905   /* We could just return cmdline, but I think it's better
1906    * to hold on to a smaller malloc block; the arguments
1907    * could be large.
1908    */
1909   base_arg0 = g_path_get_basename (utf8_buf);
1910   g_free (utf8_buf);
1911   return base_arg0;
1912 #endif
1913
1914   return NULL;
1915 }
1916
1917 /**
1918  * g_option_context_parse:
1919  * @context: a #GOptionContext
1920  * @argc: (inout) (optional): a pointer to the number of command line arguments
1921  * @argv: (inout) (array length=argc) (optional): a pointer to the array of command line arguments
1922  * @error: a return location for errors
1923  *
1924  * Parses the command line arguments, recognizing options
1925  * which have been added to @context. A side-effect of
1926  * calling this function is that g_set_prgname() will be
1927  * called.
1928  *
1929  * If the parsing is successful, any parsed arguments are
1930  * removed from the array and @argc and @argv are updated
1931  * accordingly. A '--' option is stripped from @argv
1932  * unless there are unparsed options before and after it,
1933  * or some of the options after it start with '-'. In case
1934  * of an error, @argc and @argv are left unmodified.
1935  *
1936  * If automatic `--help` support is enabled
1937  * (see g_option_context_set_help_enabled()), and the
1938  * @argv array contains one of the recognized help options,
1939  * this function will produce help output to stdout and
1940  * call `exit (0)`.
1941  *
1942  * Note that function depends on the [current locale][setlocale] for
1943  * automatic character set conversion of string and filename
1944  * arguments.
1945  *
1946  * Returns: %TRUE if the parsing was successful,
1947  *               %FALSE if an error occurred
1948  *
1949  * Since: 2.6
1950  **/
1951 gboolean
1952 g_option_context_parse (GOptionContext   *context,
1953                         gint             *argc,
1954                         gchar          ***argv,
1955                         GError          **error)
1956 {
1957   gint i, j, k;
1958   GList *list;
1959
1960   /* Set program name */
1961   if (!g_get_prgname())
1962     {
1963       gchar *prgname;
1964
1965       if (argc && argv && *argc)
1966         prgname = g_path_get_basename ((*argv)[0]);
1967       else
1968         prgname = platform_get_argv0 ();
1969
1970       if (prgname)
1971         g_set_prgname (prgname);
1972       else
1973         g_set_prgname ("<unknown>");
1974
1975       g_free (prgname);
1976     }
1977
1978   /* Call pre-parse hooks */
1979   list = context->groups;
1980   while (list)
1981     {
1982       GOptionGroup *group = list->data;
1983
1984       if (group->pre_parse_func)
1985         {
1986           if (!(* group->pre_parse_func) (context, group,
1987                                           group->user_data, error))
1988             goto fail;
1989         }
1990
1991       list = list->next;
1992     }
1993
1994   if (context->main_group && context->main_group->pre_parse_func)
1995     {
1996       if (!(* context->main_group->pre_parse_func) (context, context->main_group,
1997                                                     context->main_group->user_data, error))
1998         goto fail;
1999     }
2000
2001   if (argc && argv)
2002     {
2003       gboolean stop_parsing = FALSE;
2004       gboolean has_unknown = FALSE;
2005       gint separator_pos = 0;
2006
2007       for (i = 1; i < *argc; i++)
2008         {
2009           gchar *arg, *dash;
2010           gboolean parsed = FALSE;
2011
2012           if ((*argv)[i][0] == '-' && (*argv)[i][1] != '\0' && !stop_parsing)
2013             {
2014               if ((*argv)[i][1] == '-')
2015                 {
2016                   /* -- option */
2017
2018                   arg = (*argv)[i] + 2;
2019
2020                   /* '--' terminates list of arguments */
2021                   if (*arg == 0)
2022                     {
2023                       separator_pos = i;
2024                       stop_parsing = TRUE;
2025                       continue;
2026                     }
2027
2028                   /* Handle help options */
2029                   if (context->help_enabled)
2030                     {
2031                       if (strcmp (arg, "help") == 0)
2032                         print_help (context, TRUE, NULL);
2033                       else if (strcmp (arg, "help-all") == 0)
2034                         print_help (context, FALSE, NULL);
2035                       else if (strncmp (arg, "help-", 5) == 0)
2036                         {
2037                           list = context->groups;
2038
2039                           while (list)
2040                             {
2041                               GOptionGroup *group = list->data;
2042
2043                               if (strcmp (arg + 5, group->name) == 0)
2044                                 print_help (context, FALSE, group);
2045
2046                               list = list->next;
2047                             }
2048                         }
2049                     }
2050
2051                   if (context->main_group &&
2052                       !parse_long_option (context, context->main_group, &i, arg,
2053                                           FALSE, argc, argv, error, &parsed))
2054                     goto fail;
2055
2056                   if (parsed)
2057                     continue;
2058
2059                   /* Try the groups */
2060                   list = context->groups;
2061                   while (list)
2062                     {
2063                       GOptionGroup *group = list->data;
2064
2065                       if (!parse_long_option (context, group, &i, arg,
2066                                               FALSE, argc, argv, error, &parsed))
2067                         goto fail;
2068
2069                       if (parsed)
2070                         break;
2071
2072                       list = list->next;
2073                     }
2074
2075                   if (parsed)
2076                     continue;
2077
2078                   /* Now look for --<group>-<option> */
2079                   dash = strchr (arg, '-');
2080                   if (dash && arg < dash)
2081                     {
2082                       /* Try the groups */
2083                       list = context->groups;
2084                       while (list)
2085                         {
2086                           GOptionGroup *group = list->data;
2087
2088                           if (strncmp (group->name, arg, dash - arg) == 0)
2089                             {
2090                               if (!parse_long_option (context, group, &i, dash + 1,
2091                                                       TRUE, argc, argv, error, &parsed))
2092                                 goto fail;
2093
2094                               if (parsed)
2095                                 break;
2096                             }
2097
2098                           list = list->next;
2099                         }
2100                     }
2101
2102                   if (context->ignore_unknown)
2103                     continue;
2104                 }
2105               else
2106                 { /* short option */
2107                   gint new_i = i, arg_length;
2108                   gboolean *nulled_out = NULL;
2109                   gboolean has_h_entry = context_has_h_entry (context);
2110                   arg = (*argv)[i] + 1;
2111                   arg_length = strlen (arg);
2112                   nulled_out = g_newa (gboolean, arg_length);
2113                   memset (nulled_out, 0, arg_length * sizeof (gboolean));
2114                   for (j = 0; j < arg_length; j++)
2115                     {
2116                       if (context->help_enabled && (arg[j] == '?' ||
2117                         (arg[j] == 'h' && !has_h_entry)))
2118                         print_help (context, TRUE, NULL);
2119                       parsed = FALSE;
2120                       if (context->main_group &&
2121                           !parse_short_option (context, context->main_group,
2122                                                i, &new_i, arg[j],
2123                                                argc, argv, error, &parsed))
2124                         goto fail;
2125                       if (!parsed)
2126                         {
2127                           /* Try the groups */
2128                           list = context->groups;
2129                           while (list)
2130                             {
2131                               GOptionGroup *group = list->data;
2132                               if (!parse_short_option (context, group, i, &new_i, arg[j],
2133                                                        argc, argv, error, &parsed))
2134                                 goto fail;
2135                               if (parsed)
2136                                 break;
2137                               list = list->next;
2138                             }
2139                         }
2140
2141                       if (context->ignore_unknown && parsed)
2142                         nulled_out[j] = TRUE;
2143                       else if (context->ignore_unknown)
2144                         continue;
2145                       else if (!parsed)
2146                         break;
2147                       /* !context->ignore_unknown && parsed */
2148                     }
2149                   if (context->ignore_unknown)
2150                     {
2151                       gchar *new_arg = NULL;
2152                       gint arg_index = 0;
2153                       for (j = 0; j < arg_length; j++)
2154                         {
2155                           if (!nulled_out[j])
2156                             {
2157                               if (!new_arg)
2158                                 new_arg = g_malloc (arg_length + 1);
2159                               new_arg[arg_index++] = arg[j];
2160                             }
2161                         }
2162                       if (new_arg)
2163                         new_arg[arg_index] = '\0';
2164                       add_pending_null (context, &((*argv)[i]), new_arg);
2165                       i = new_i;
2166                     }
2167                   else if (parsed)
2168                     {
2169                       add_pending_null (context, &((*argv)[i]), NULL);
2170                       i = new_i;
2171                     }
2172                 }
2173
2174               if (!parsed)
2175                 has_unknown = TRUE;
2176
2177               if (!parsed && !context->ignore_unknown)
2178                 {
2179                   g_set_error (error,
2180                                G_OPTION_ERROR, G_OPTION_ERROR_UNKNOWN_OPTION,
2181                                    _("Unknown option %s"), (*argv)[i]);
2182                   goto fail;
2183                 }
2184             }
2185           else
2186             {
2187               if (context->strict_posix)
2188                 stop_parsing = TRUE;
2189
2190               /* Collect remaining args */
2191               if (context->main_group &&
2192                   !parse_remaining_arg (context, context->main_group, &i,
2193                                         argc, argv, error, &parsed))
2194                 goto fail;
2195
2196               if (!parsed && (has_unknown || (*argv)[i][0] == '-'))
2197                 separator_pos = 0;
2198             }
2199         }
2200
2201       if (separator_pos > 0)
2202         add_pending_null (context, &((*argv)[separator_pos]), NULL);
2203
2204     }
2205
2206   /* Call post-parse hooks */
2207   list = context->groups;
2208   while (list)
2209     {
2210       GOptionGroup *group = list->data;
2211
2212       if (group->post_parse_func)
2213         {
2214           if (!(* group->post_parse_func) (context, group,
2215                                            group->user_data, error))
2216             goto fail;
2217         }
2218
2219       list = list->next;
2220     }
2221
2222   if (context->main_group && context->main_group->post_parse_func)
2223     {
2224       if (!(* context->main_group->post_parse_func) (context, context->main_group,
2225                                                      context->main_group->user_data, error))
2226         goto fail;
2227     }
2228
2229   if (argc && argv)
2230     {
2231       free_pending_nulls (context, TRUE);
2232
2233       for (i = 1; i < *argc; i++)
2234         {
2235           for (k = i; k < *argc; k++)
2236             if ((*argv)[k] != NULL)
2237               break;
2238
2239           if (k > i)
2240             {
2241               k -= i;
2242               for (j = i + k; j < *argc; j++)
2243                 {
2244                   (*argv)[j-k] = (*argv)[j];
2245                   (*argv)[j] = NULL;
2246                 }
2247               *argc -= k;
2248             }
2249         }
2250     }
2251
2252   return TRUE;
2253
2254  fail:
2255
2256   /* Call error hooks */
2257   list = context->groups;
2258   while (list)
2259     {
2260       GOptionGroup *group = list->data;
2261
2262       if (group->error_func)
2263         (* group->error_func) (context, group,
2264                                group->user_data, error);
2265
2266       list = list->next;
2267     }
2268
2269   if (context->main_group && context->main_group->error_func)
2270     (* context->main_group->error_func) (context, context->main_group,
2271                                          context->main_group->user_data, error);
2272
2273   free_changes_list (context, TRUE);
2274   free_pending_nulls (context, FALSE);
2275
2276   return FALSE;
2277 }
2278
2279 /**
2280  * g_option_group_new:
2281  * @name: the name for the option group, this is used to provide
2282  *   help for the options in this group with `--help-`@name
2283  * @description: a description for this group to be shown in
2284  *   `--help`. This string is translated using the translation
2285  *   domain or translation function of the group
2286  * @help_description: a description for the `--help-`@name option.
2287  *   This string is translated using the translation domain or translation function
2288  *   of the group
2289  * @user_data: (nullable): user data that will be passed to the pre- and post-parse hooks,
2290  *   the error hook and to callbacks of %G_OPTION_ARG_CALLBACK options, or %NULL
2291  * @destroy: (nullable): a function that will be called to free @user_data, or %NULL
2292  *
2293  * Creates a new #GOptionGroup.
2294  *
2295  * Returns: a newly created option group. It should be added
2296  *   to a #GOptionContext or freed with g_option_group_unref().
2297  *
2298  * Since: 2.6
2299  **/
2300 GOptionGroup *
2301 g_option_group_new (const gchar    *name,
2302                     const gchar    *description,
2303                     const gchar    *help_description,
2304                     gpointer        user_data,
2305                     GDestroyNotify  destroy)
2306
2307 {
2308   GOptionGroup *group;
2309
2310   group = g_new0 (GOptionGroup, 1);
2311   group->ref_count = 1;
2312   group->name = g_strdup (name);
2313   group->description = g_strdup (description);
2314   group->help_description = g_strdup (help_description);
2315   group->user_data = user_data;
2316   group->destroy_notify = destroy;
2317
2318   return group;
2319 }
2320
2321
2322 /**
2323  * g_option_group_free:
2324  * @group: a #GOptionGroup
2325  *
2326  * Frees a #GOptionGroup. Note that you must not free groups
2327  * which have been added to a #GOptionContext.
2328  *
2329  * Since: 2.6
2330  *
2331  * Deprecated: 2.44: Use g_option_group_unref() instead.
2332  */
2333 void
2334 g_option_group_free (GOptionGroup *group)
2335 {
2336   g_option_group_unref (group);
2337 }
2338
2339 /**
2340  * g_option_group_ref:
2341  * @group: a #GOptionGroup
2342  *
2343  * Increments the reference count of @group by one.
2344  *
2345  * Returns: a #GOptionGroup
2346  *
2347  * Since: 2.44
2348  */
2349 GOptionGroup *
2350 g_option_group_ref (GOptionGroup *group)
2351 {
2352   g_return_val_if_fail (group != NULL, NULL);
2353
2354   group->ref_count++;
2355
2356   return group;
2357 }
2358
2359 /**
2360  * g_option_group_unref:
2361  * @group: a #GOptionGroup
2362  *
2363  * Decrements the reference count of @group by one.
2364  * If the reference count drops to 0, the @group will be freed.
2365  * and all memory allocated by the @group is released.
2366  *
2367  * Since: 2.44
2368  */
2369 void
2370 g_option_group_unref (GOptionGroup *group)
2371 {
2372   g_return_if_fail (group != NULL);
2373
2374   if (--group->ref_count == 0)
2375     {
2376       g_free (group->name);
2377       g_free (group->description);
2378       g_free (group->help_description);
2379
2380       g_free (group->entries);
2381
2382       if (group->destroy_notify)
2383         (* group->destroy_notify) (group->user_data);
2384
2385       if (group->translate_notify)
2386         (* group->translate_notify) (group->translate_data);
2387
2388       g_free (group);
2389     }
2390 }
2391
2392 /**
2393  * g_option_group_add_entries:
2394  * @group: a #GOptionGroup
2395  * @entries: a %NULL-terminated array of #GOptionEntrys
2396  *
2397  * Adds the options specified in @entries to @group.
2398  *
2399  * Since: 2.6
2400  **/
2401 void
2402 g_option_group_add_entries (GOptionGroup       *group,
2403                             const GOptionEntry *entries)
2404 {
2405   gsize i, n_entries;
2406
2407   g_return_if_fail (entries != NULL);
2408
2409   for (n_entries = 0; entries[n_entries].long_name != NULL; n_entries++) ;
2410
2411   group->entries = g_renew (GOptionEntry, group->entries, group->n_entries + n_entries);
2412
2413   /* group->entries could be NULL in the trivial case where we add no
2414    * entries to no entries */
2415   if (n_entries != 0)
2416     memcpy (group->entries + group->n_entries, entries, sizeof (GOptionEntry) * n_entries);
2417
2418   for (i = group->n_entries; i < group->n_entries + n_entries; i++)
2419     {
2420       gchar c = group->entries[i].short_name;
2421
2422       if (c == '-' || (c != 0 && !g_ascii_isprint (c)))
2423         {
2424           g_warning (G_STRLOC ": ignoring invalid short option '%c' (%d) in entry %s:%s",
2425               c, c, group->name, group->entries[i].long_name);
2426           group->entries[i].short_name = '\0';
2427         }
2428
2429       if (group->entries[i].arg != G_OPTION_ARG_NONE &&
2430           (group->entries[i].flags & G_OPTION_FLAG_REVERSE) != 0)
2431         {
2432           g_warning (G_STRLOC ": ignoring reverse flag on option of arg-type %d in entry %s:%s",
2433               group->entries[i].arg, group->name, group->entries[i].long_name);
2434
2435           group->entries[i].flags &= ~G_OPTION_FLAG_REVERSE;
2436         }
2437
2438       if (group->entries[i].arg != G_OPTION_ARG_CALLBACK &&
2439           (group->entries[i].flags & (G_OPTION_FLAG_NO_ARG|G_OPTION_FLAG_OPTIONAL_ARG|G_OPTION_FLAG_FILENAME)) != 0)
2440         {
2441           g_warning (G_STRLOC ": ignoring no-arg, optional-arg or filename flags (%d) on option of arg-type %d in entry %s:%s",
2442               group->entries[i].flags, group->entries[i].arg, group->name, group->entries[i].long_name);
2443
2444           group->entries[i].flags &= ~(G_OPTION_FLAG_NO_ARG|G_OPTION_FLAG_OPTIONAL_ARG|G_OPTION_FLAG_FILENAME);
2445         }
2446     }
2447
2448   group->n_entries += n_entries;
2449 }
2450
2451 /**
2452  * g_option_group_set_parse_hooks:
2453  * @group: a #GOptionGroup
2454  * @pre_parse_func: (nullable): a function to call before parsing, or %NULL
2455  * @post_parse_func: (nullable): a function to call after parsing, or %NULL
2456  *
2457  * Associates two functions with @group which will be called
2458  * from g_option_context_parse() before the first option is parsed
2459  * and after the last option has been parsed, respectively.
2460  *
2461  * Note that the user data to be passed to @pre_parse_func and
2462  * @post_parse_func can be specified when constructing the group
2463  * with g_option_group_new().
2464  *
2465  * Since: 2.6
2466  **/
2467 void
2468 g_option_group_set_parse_hooks (GOptionGroup     *group,
2469                                 GOptionParseFunc  pre_parse_func,
2470                                 GOptionParseFunc  post_parse_func)
2471 {
2472   g_return_if_fail (group != NULL);
2473
2474   group->pre_parse_func = pre_parse_func;
2475   group->post_parse_func = post_parse_func;
2476 }
2477
2478 /**
2479  * g_option_group_set_error_hook:
2480  * @group: a #GOptionGroup
2481  * @error_func: a function to call when an error occurs
2482  *
2483  * Associates a function with @group which will be called
2484  * from g_option_context_parse() when an error occurs.
2485  *
2486  * Note that the user data to be passed to @error_func can be
2487  * specified when constructing the group with g_option_group_new().
2488  *
2489  * Since: 2.6
2490  **/
2491 void
2492 g_option_group_set_error_hook (GOptionGroup     *group,
2493                                GOptionErrorFunc  error_func)
2494 {
2495   g_return_if_fail (group != NULL);
2496
2497   group->error_func = error_func;
2498 }
2499
2500
2501 /**
2502  * g_option_group_set_translate_func:
2503  * @group: a #GOptionGroup
2504  * @func: (nullable): the #GTranslateFunc, or %NULL
2505  * @data: (nullable): user data to pass to @func, or %NULL
2506  * @destroy_notify: (nullable): a function which gets called to free @data, or %NULL
2507  *
2508  * Sets the function which is used to translate user-visible strings,
2509  * for `--help` output. Different groups can use different
2510  * #GTranslateFuncs. If @func is %NULL, strings are not translated.
2511  *
2512  * If you are using gettext(), you only need to set the translation
2513  * domain, see g_option_group_set_translation_domain().
2514  *
2515  * Since: 2.6
2516  **/
2517 void
2518 g_option_group_set_translate_func (GOptionGroup   *group,
2519                                    GTranslateFunc  func,
2520                                    gpointer        data,
2521                                    GDestroyNotify  destroy_notify)
2522 {
2523   g_return_if_fail (group != NULL);
2524
2525   if (group->translate_notify)
2526     group->translate_notify (group->translate_data);
2527
2528   group->translate_func = func;
2529   group->translate_data = data;
2530   group->translate_notify = destroy_notify;
2531 }
2532
2533 static const gchar *
2534 dgettext_swapped (const gchar *msgid,
2535                   const gchar *domainname)
2536 {
2537   return g_dgettext (domainname, msgid);
2538 }
2539
2540 /**
2541  * g_option_group_set_translation_domain:
2542  * @group: a #GOptionGroup
2543  * @domain: the domain to use
2544  *
2545  * A convenience function to use gettext() for translating
2546  * user-visible strings.
2547  *
2548  * Since: 2.6
2549  **/
2550 void
2551 g_option_group_set_translation_domain (GOptionGroup *group,
2552                                        const gchar  *domain)
2553 {
2554   g_return_if_fail (group != NULL);
2555
2556   g_option_group_set_translate_func (group,
2557                                      (GTranslateFunc)dgettext_swapped,
2558                                      g_strdup (domain),
2559                                      g_free);
2560 }
2561
2562 /**
2563  * g_option_context_set_translate_func:
2564  * @context: a #GOptionContext
2565  * @func: (nullable): the #GTranslateFunc, or %NULL
2566  * @data: (nullable): user data to pass to @func, or %NULL
2567  * @destroy_notify: (nullable): a function which gets called to free @data, or %NULL
2568  *
2569  * Sets the function which is used to translate the contexts
2570  * user-visible strings, for `--help` output. If @func is %NULL,
2571  * strings are not translated.
2572  *
2573  * Note that option groups have their own translation functions,
2574  * this function only affects the @parameter_string (see g_option_context_new()),
2575  * the summary (see g_option_context_set_summary()) and the description
2576  * (see g_option_context_set_description()).
2577  *
2578  * If you are using gettext(), you only need to set the translation
2579  * domain, see g_option_context_set_translation_domain().
2580  *
2581  * Since: 2.12
2582  **/
2583 void
2584 g_option_context_set_translate_func (GOptionContext *context,
2585                                      GTranslateFunc func,
2586                                      gpointer       data,
2587                                      GDestroyNotify destroy_notify)
2588 {
2589   g_return_if_fail (context != NULL);
2590
2591   if (context->translate_notify)
2592     context->translate_notify (context->translate_data);
2593
2594   context->translate_func = func;
2595   context->translate_data = data;
2596   context->translate_notify = destroy_notify;
2597 }
2598
2599 /**
2600  * g_option_context_set_translation_domain:
2601  * @context: a #GOptionContext
2602  * @domain: the domain to use
2603  *
2604  * A convenience function to use gettext() for translating
2605  * user-visible strings.
2606  *
2607  * Since: 2.12
2608  **/
2609 void
2610 g_option_context_set_translation_domain (GOptionContext *context,
2611                                          const gchar     *domain)
2612 {
2613   g_return_if_fail (context != NULL);
2614
2615   g_option_context_set_translate_func (context,
2616                                        (GTranslateFunc)dgettext_swapped,
2617                                        g_strdup (domain),
2618                                        g_free);
2619 }
2620
2621 /**
2622  * g_option_context_set_summary:
2623  * @context: a #GOptionContext
2624  * @summary: (nullable): a string to be shown in `--help` output
2625  *  before the list of options, or %NULL
2626  *
2627  * Adds a string to be displayed in `--help` output before the list
2628  * of options. This is typically a summary of the program functionality.
2629  *
2630  * Note that the summary is translated (see
2631  * g_option_context_set_translate_func() and
2632  * g_option_context_set_translation_domain()).
2633  *
2634  * Since: 2.12
2635  */
2636 void
2637 g_option_context_set_summary (GOptionContext *context,
2638                               const gchar    *summary)
2639 {
2640   g_return_if_fail (context != NULL);
2641
2642   g_free (context->summary);
2643   context->summary = g_strdup (summary);
2644 }
2645
2646
2647 /**
2648  * g_option_context_get_summary:
2649  * @context: a #GOptionContext
2650  *
2651  * Returns the summary. See g_option_context_set_summary().
2652  *
2653  * Returns: the summary
2654  *
2655  * Since: 2.12
2656  */
2657 const gchar *
2658 g_option_context_get_summary (GOptionContext *context)
2659 {
2660   g_return_val_if_fail (context != NULL, NULL);
2661
2662   return context->summary;
2663 }
2664
2665 /**
2666  * g_option_context_set_description:
2667  * @context: a #GOptionContext
2668  * @description: (nullable): a string to be shown in `--help` output
2669  *   after the list of options, or %NULL
2670  *
2671  * Adds a string to be displayed in `--help` output after the list
2672  * of options. This text often includes a bug reporting address.
2673  *
2674  * Note that the summary is translated (see
2675  * g_option_context_set_translate_func()).
2676  *
2677  * Since: 2.12
2678  */
2679 void
2680 g_option_context_set_description (GOptionContext *context,
2681                                   const gchar    *description)
2682 {
2683   g_return_if_fail (context != NULL);
2684
2685   g_free (context->description);
2686   context->description = g_strdup (description);
2687 }
2688
2689
2690 /**
2691  * g_option_context_get_description:
2692  * @context: a #GOptionContext
2693  *
2694  * Returns the description. See g_option_context_set_description().
2695  *
2696  * Returns: the description
2697  *
2698  * Since: 2.12
2699  */
2700 const gchar *
2701 g_option_context_get_description (GOptionContext *context)
2702 {
2703   g_return_val_if_fail (context != NULL, NULL);
2704
2705   return context->description;
2706 }
2707
2708 /**
2709  * g_option_context_parse_strv:
2710  * @context: a #GOptionContext
2711  * @arguments: (inout) (array zero-terminated=1): a pointer to the
2712  *    command line arguments (which must be in UTF-8 on Windows)
2713  * @error: a return location for errors
2714  *
2715  * Parses the command line arguments.
2716  *
2717  * This function is similar to g_option_context_parse() except that it
2718  * respects the normal memory rules when dealing with a strv instead of
2719  * assuming that the passed-in array is the argv of the main function.
2720  *
2721  * In particular, strings that are removed from the arguments list will
2722  * be freed using g_free().
2723  *
2724  * On Windows, the strings are expected to be in UTF-8.  This is in
2725  * contrast to g_option_context_parse() which expects them to be in the
2726  * system codepage, which is how they are passed as @argv to main().
2727  * See g_win32_get_command_line() for a solution.
2728  *
2729  * This function is useful if you are trying to use #GOptionContext with
2730  * #GApplication.
2731  *
2732  * Returns: %TRUE if the parsing was successful,
2733  *          %FALSE if an error occurred
2734  *
2735  * Since: 2.40
2736  **/
2737 gboolean
2738 g_option_context_parse_strv (GOptionContext   *context,
2739                              gchar          ***arguments,
2740                              GError          **error)
2741 {
2742   gboolean success;
2743   gint argc;
2744
2745   context->strv_mode = TRUE;
2746   argc = g_strv_length (*arguments);
2747   success = g_option_context_parse (context, &argc, arguments, error);
2748   context->strv_mode = FALSE;
2749
2750   return success;
2751 }