Set errno to 0 before calling strtol. (#306388, Morten Welinder)
[platform/upstream/glib.git] / glib / goption.c
1 /* goption.c - Option parser
2  *
3  *  Copyright (C) 1999, 2003 Red Hat Software
4  *  Copyright (C) 2004       Anders Carlsson <andersca@gnome.org>
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Library General Public License for more details.
15  *
16  * You should have received a copy of the GNU Library General Public
17  * License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19  * Boston, MA 02111-1307, USA.
20  */
21
22 #include "config.h"
23
24 #include "goption.h"
25 #include "glib.h"
26 #include "gi18n.h"
27
28 #include "galias.h"
29
30 #include <string.h>
31 #include <stdlib.h>
32 #include <errno.h>
33
34 #define TRANSLATE(group, str) (((group)->translate_func ? (* (group)->translate_func) ((str), (group)->translate_data) : (str)))
35
36 typedef struct 
37 {
38   GOptionArg arg_type;
39   gpointer arg_data;  
40   union 
41   {
42     gboolean bool;
43     gint integer;
44     gchar *str;
45     gchar **array;
46   } prev;
47   union 
48   {
49     gchar *str;
50     struct 
51     {
52       gint len;
53       gchar **data;
54     } array;
55   } allocated;
56 } Change;
57
58 typedef struct
59 {
60   gchar **ptr;
61   gchar *value;
62 } PendingNull;
63
64 struct _GOptionContext
65 {
66   GList *groups;
67
68   gchar *parameter_string;
69
70   gboolean help_enabled;
71   gboolean ignore_unknown;
72   
73   GOptionGroup *main_group;
74
75   /* We keep a list of change so we can revert them */
76   GList *changes;
77   
78   /* We also keep track of all argv elements that should be NULLed or
79    * modified.
80    */
81   GList *pending_nulls;
82 };
83
84 struct _GOptionGroup
85 {
86   gchar *name;
87   gchar *description;
88   gchar *help_description;
89
90   GDestroyNotify  destroy_notify;
91   gpointer        user_data;
92
93   GTranslateFunc  translate_func;
94   GDestroyNotify  translate_notify;
95   gpointer        translate_data;
96
97   GOptionEntry *entries;
98   gint         n_entries;
99
100   GOptionParseFunc pre_parse_func;
101   GOptionParseFunc post_parse_func;
102   GOptionErrorFunc error_func;
103 };
104
105 static void free_changes_list (GOptionContext *context,
106                                gboolean        revert);
107 static void free_pending_nulls (GOptionContext *context,
108                                 gboolean        perform_nulls);
109
110 GQuark
111 g_option_error_quark (void)
112 {
113   static GQuark q = 0;
114   
115   if (q == 0)
116     q = g_quark_from_static_string ("g-option-context-error-quark");
117
118   return q;
119 }
120
121 /**
122  * g_option_context_new:
123  * @parameter_string: a string which is displayed in
124  *    the first line of <option>--help</option> output, after 
125  *    <literal><replaceable>programname</replaceable> [OPTION...]</literal>
126  *
127  * Creates a new option context. 
128  *
129  * Returns: a newly created #GOptionContext, which must be
130  *    freed with g_option_context_free() after use.
131  *
132  * Since: 2.6
133  */
134 GOptionContext *
135 g_option_context_new (const gchar *parameter_string)
136
137 {
138   GOptionContext *context;
139
140   context = g_new0 (GOptionContext, 1);
141
142   context->parameter_string = g_strdup (parameter_string);
143   context->help_enabled = TRUE;
144   context->ignore_unknown = FALSE;
145
146   return context;
147 }
148
149 /**
150  * g_option_context_free:
151  * @context: a #GOptionContext 
152  *
153  * Frees context and all the groups which have been 
154  * added to it.
155  *
156  * Since: 2.6
157  */
158 void g_option_context_free (GOptionContext *context) 
159 {
160   g_return_if_fail (context != NULL);
161
162   g_list_foreach (context->groups, (GFunc)g_option_group_free, NULL);
163   g_list_free (context->groups);
164
165   if (context->main_group) 
166     g_option_group_free (context->main_group);
167
168   free_changes_list (context, FALSE);
169   free_pending_nulls (context, FALSE);
170   
171   g_free (context->parameter_string);
172   
173   g_free (context);
174 }
175
176
177 /**
178  * g_option_context_set_help_enabled:
179  * @context: a #GOptionContext
180  * @help_enabled: %TRUE to enable <option>--help</option>, %FALSE to disable it
181  *
182  * Enables or disables automatic generation of <option>--help</option> 
183  * output. By default, g_option_context_parse() recognizes
184  * <option>--help</option>, <option>-?</option>, <option>--help-all</option>
185  * and <option>--help-</option><replaceable>groupname</replaceable> and creates
186  * suitable output to stdout. 
187  *
188  * Since: 2.6
189  */
190 void g_option_context_set_help_enabled (GOptionContext *context,
191                                         gboolean        help_enabled)
192
193 {
194   g_return_if_fail (context != NULL);
195
196   context->help_enabled = help_enabled;
197 }
198
199 /**
200  * g_option_context_get_help_enabled:
201  * @context: a #GOptionContext
202  * 
203  * Returns whether automatic <option>--help</option> generation
204  * is turned on for @context. See g_option_context_set_help_enabled().
205  * 
206  * Returns: %TRUE if automatic help generation is turned on.
207  *
208  * Since: 2.6
209  */
210 gboolean 
211 g_option_context_get_help_enabled (GOptionContext *context) 
212 {
213   g_return_val_if_fail (context != NULL, FALSE);
214   
215   return context->help_enabled;
216 }
217
218 /**
219  * g_option_context_set_ignore_unknown_options:
220  * @context: a #GOptionContext
221  * @ignore_unknown: %TRUE to ignore unknown options, %FALSE to produce
222  *    an error when unknown options are met
223  * 
224  * Sets whether to ignore unknown options or not. If an argument is 
225  * ignored, it is left in the @argv array after parsing. By default, 
226  * g_option_context_parse() treats unknown options as error.
227  * 
228  * This setting does not affect non-option arguments (i.e. arguments 
229  * which don't start with a dash). But note that GOption cannot reliably
230  * determine whether a non-option belongs to a preceding unknown option.
231  *
232  * Since: 2.6
233  **/
234 void
235 g_option_context_set_ignore_unknown_options (GOptionContext *context,
236                                              gboolean        ignore_unknown)
237 {
238   g_return_if_fail (context != NULL);
239
240   context->ignore_unknown = ignore_unknown;
241 }
242
243 /**
244  * g_option_context_get_ignore_unknown_options:
245  * @context: a #GOptionContext
246  * 
247  * Returns whether unknown options are ignored or not. See
248  * g_option_context_set_ignore_unknown_options().
249  * 
250  * Returns: %TRUE if unknown options are ignored.
251  * 
252  * Since: 2.6
253  **/
254 gboolean
255 g_option_context_get_ignore_unknown_options (GOptionContext *context)
256 {
257   g_return_val_if_fail (context != NULL, FALSE);
258
259   return context->ignore_unknown;
260 }
261
262 /**
263  * g_option_context_add_group:
264  * @context: a #GOptionContext
265  * @group: the group to add
266  * 
267  * Adds a #GOptionGroup to the @context, so that parsing with @context
268  * will recognize the options in the group. Note that the group will
269  * be freed together with the context when g_option_context_free() is
270  * called, so you must not free the group yourself after adding it
271  * to a context.
272  *
273  * Since: 2.6
274  **/
275 void
276 g_option_context_add_group (GOptionContext *context,
277                             GOptionGroup   *group)
278 {
279   GList *list;
280
281   g_return_if_fail (context != NULL);
282   g_return_if_fail (group != NULL);
283   g_return_if_fail (group->name != NULL);
284   g_return_if_fail (group->description != NULL);
285   g_return_if_fail (group->help_description != NULL);
286
287   for (list = context->groups; list; list = list->next)
288     {
289       GOptionGroup *g = (GOptionGroup *)list->data;
290
291       if ((group->name == NULL && g->name == NULL) ||
292           (group->name && g->name && strcmp (group->name, g->name) == 0))
293         g_warning ("A group named \"%s\" is already part of this GOptionContext", 
294                    group->name);
295     }
296
297   context->groups = g_list_append (context->groups, group);
298 }
299
300 /**
301  * g_option_context_set_main_group:
302  * @context: a #GOptionContext
303  * @group: the group to set as main group
304  * 
305  * Sets a #GOptionGroup as main group of the @context. 
306  * This has the same effect as calling g_option_context_add_group(), 
307  * the only difference is that the options in the main group are 
308  * treated differently when generating <option>--help</option> output.
309  *
310  * Since: 2.6
311  **/
312 void
313 g_option_context_set_main_group (GOptionContext *context,
314                                  GOptionGroup   *group)
315 {
316   g_return_if_fail (context != NULL);
317   g_return_if_fail (group != NULL);
318
319   if (context->main_group)
320     {
321       g_warning ("This GOptionContext already has a main group");
322
323       return;
324     }
325   
326   context->main_group = group;
327 }
328
329 /**
330  * g_option_context_get_main_group:
331  * @context: a #GOptionContext
332  * 
333  * Returns a pointer to the main group of @context.
334  * 
335  * Return value: the main group of @context, or %NULL if @context doesn't
336  *  have a main group. Note that group belongs to @context and should
337  *  not be modified or freed.
338  *
339  * Since: 2.6
340  **/
341 GOptionGroup *
342 g_option_context_get_main_group (GOptionContext *context)
343 {
344   g_return_val_if_fail (context != NULL, NULL);
345
346   return context->main_group;
347 }
348
349 /**
350  * g_option_context_add_main_entries:
351  * @context: a #GOptionContext
352  * @entries: a %NULL-terminated array of #GOptionEntry<!-- -->s
353  * @translation_domain: a translation domain to use for translating
354  *    the <option>--help</option> output for the options in @entries
355  *    with gettext(), or %NULL
356  * 
357  * A convenience function which creates a main group if it doesn't 
358  * exist, adds the @entries to it and sets the translation domain.
359  * 
360  * Since: 2.6
361  **/
362 void
363 g_option_context_add_main_entries (GOptionContext      *context,
364                                    const GOptionEntry  *entries,
365                                    const gchar         *translation_domain)
366 {
367   g_return_if_fail (entries != NULL);
368
369   if (!context->main_group)
370     context->main_group = g_option_group_new (NULL, NULL, NULL, NULL, NULL);
371   
372   g_option_group_add_entries (context->main_group, entries);
373   g_option_group_set_translation_domain (context->main_group, translation_domain);
374 }
375
376 static gint
377 calculate_max_length (GOptionGroup *group)
378 {
379   GOptionEntry *entry;
380   gint i, len, max_length;
381
382   max_length = 0;
383
384   for (i = 0; i < group->n_entries; i++)
385     {
386       entry = &group->entries[i];
387
388       if (entry->flags & G_OPTION_FLAG_HIDDEN)
389         continue;
390
391       len = g_utf8_strlen (entry->long_name, -1);
392       
393       if (entry->short_name)
394         len += 4;
395       
396       if (entry->arg != G_OPTION_ARG_NONE && entry->arg_description)
397         len += 1 + g_utf8_strlen (TRANSLATE (group, entry->arg_description), -1);
398       
399       max_length = MAX (max_length, len);
400     }
401
402   return max_length;
403 }
404
405 static void
406 print_entry (GOptionGroup       *group,
407              gint                max_length,
408              const GOptionEntry *entry)
409 {
410   GString *str;
411
412   if (entry->flags & G_OPTION_FLAG_HIDDEN)
413     return;
414
415   if (entry->long_name[0] == 0)
416     return;
417
418   str = g_string_new (NULL);
419   
420   if (entry->short_name)
421     g_string_append_printf (str, "  -%c, --%s", entry->short_name, entry->long_name);
422   else
423     g_string_append_printf (str, "  --%s", entry->long_name);
424   
425   if (entry->arg_description)
426     g_string_append_printf (str, "=%s", TRANSLATE (group, entry->arg_description));
427   
428   g_print ("%-*s %s\n", max_length + 4, str->str,
429            entry->description ? TRANSLATE (group, entry->description) : "");
430   g_string_free (str, TRUE);  
431 }
432
433 static void
434 print_help (GOptionContext *context,
435             gboolean        main_help,
436             GOptionGroup   *group) 
437 {
438   GList *list;
439   gint max_length, len;
440   gint i;
441   GOptionEntry *entry;
442   GHashTable *shadow_map;
443   gboolean seen[256];
444   const gchar *rest_description;
445   
446   rest_description = NULL;
447   if (context->main_group)
448     {
449       for (i = 0; i < context->main_group->n_entries; i++)
450         {
451           entry = &context->main_group->entries[i];
452           if (entry->long_name[0] == 0)
453             {
454               rest_description = entry->arg_description;
455               break;
456             }
457         }
458     }
459   
460   g_print ("%s\n  %s %s%s%s%s%s\n\n", 
461            _("Usage:"), g_get_prgname(), _("[OPTION...]"),
462            rest_description ? " " : "",
463            rest_description ? rest_description : "",
464            context->parameter_string ? " " : "",
465            context->parameter_string ? context->parameter_string : "");
466
467   memset (seen, 0, sizeof (gboolean) * 256);
468   shadow_map = g_hash_table_new (g_str_hash, g_str_equal);
469
470   if (context->main_group)
471     {
472       for (i = 0; i < context->main_group->n_entries; i++)
473         {
474           entry = &context->main_group->entries[i];
475           g_hash_table_insert (shadow_map, 
476                                (gpointer)entry->long_name, 
477                                entry);
478           
479           if (seen[(guchar)entry->short_name])
480             entry->short_name = 0;
481           else
482             seen[(guchar)entry->short_name] = TRUE;
483         }
484     }
485
486   list = context->groups;
487   while (list != NULL)
488     {
489       GOptionGroup *group = list->data;
490       for (i = 0; i < group->n_entries; i++)
491         {
492           entry = &group->entries[i];
493           if (g_hash_table_lookup (shadow_map, entry->long_name))
494             entry->long_name = g_strdup_printf ("%s-%s", group->name, entry->long_name);
495           else  
496             g_hash_table_insert (shadow_map, (gpointer)entry->long_name, entry);
497
498           if (seen[(guchar)entry->short_name])
499             entry->short_name = 0;
500           else
501             seen[(guchar)entry->short_name] = TRUE;
502         }
503       list = list->next;
504     }
505
506   g_hash_table_destroy (shadow_map);
507
508   list = context->groups;
509
510   max_length = g_utf8_strlen ("-?, --help", -1);
511
512   if (list)
513     {
514       len = g_utf8_strlen ("--help-all", -1);
515       max_length = MAX (max_length, len);
516     }
517
518   if (context->main_group)
519     {
520       len = calculate_max_length (context->main_group);
521       max_length = MAX (max_length, len);
522     }
523
524   while (list != NULL)
525     {
526       GOptionGroup *group = list->data;
527       
528       /* First, we check the --help-<groupname> options */
529       len = g_utf8_strlen ("--help-", -1) + g_utf8_strlen (group->name, -1);
530       max_length = MAX (max_length, len);
531
532       /* Then we go through the entries */
533       len = calculate_max_length (group);
534       max_length = MAX (max_length, len);
535       
536       list = list->next;
537     }
538
539   /* Add a bit of padding */
540   max_length += 4;
541
542   if (!group)
543     {
544       list = context->groups;
545       
546       g_print ("%s\n  -%c, --%-*s %s\n", 
547                _("Help Options:"), '?', max_length - 4, "help", 
548                _("Show help options"));
549       
550       /* We only want --help-all when there are groups */
551       if (list)
552         g_print ("  --%-*s %s\n", max_length, "help-all", 
553                  _("Show all help options"));
554       
555       while (list)
556         {
557           GOptionGroup *group = list->data;
558           
559           g_print ("  --help-%-*s %s\n", max_length - 5, group->name, 
560                    TRANSLATE (group, group->help_description));
561           
562           list = list->next;
563         }
564
565       g_print ("\n");
566     }
567
568   if (group)
569     {
570       /* Print a certain group */
571       
572       g_print ("%s\n", TRANSLATE (group, group->description));
573       for (i = 0; i < group->n_entries; i++)
574         print_entry (group, max_length, &group->entries[i]);
575       g_print ("\n");
576     }
577   else if (!main_help)
578     {
579       /* Print all groups */
580
581       list = context->groups;
582
583       while (list)
584         {
585           GOptionGroup *group = list->data;
586
587           g_print ("%s\n", group->description);
588
589           for (i = 0; i < group->n_entries; i++)
590             if (!(group->entries[i].flags & G_OPTION_FLAG_IN_MAIN))
591               print_entry (group, max_length, &group->entries[i]);
592           
593           g_print ("\n");
594           list = list->next;
595         }
596     }
597   
598   /* Print application options if --help or --help-all has been specified */
599   if (main_help || !group)
600     {
601       list = context->groups;
602
603       g_print ("%s\n", _("Application Options:"));
604
605       if (context->main_group)
606         for (i = 0; i < context->main_group->n_entries; i++) 
607           print_entry (context->main_group, max_length, 
608                        &context->main_group->entries[i]);
609
610       while (list != NULL)
611         {
612           GOptionGroup *group = list->data;
613
614           /* Print main entries from other groups */
615           for (i = 0; i < group->n_entries; i++)
616             if (group->entries[i].flags & G_OPTION_FLAG_IN_MAIN)
617               print_entry (group, max_length, &group->entries[i]);
618           
619           list = list->next;
620         }
621
622       g_print ("\n");
623     }
624   
625   exit (0);
626 }
627
628 static gboolean
629 parse_int (const gchar *arg_name,
630            const gchar *arg,
631            gint        *result,
632            GError     **error)
633 {
634   gchar *end;
635   glong tmp;
636
637   errno = 0;
638   tmp = strtol (arg, &end, 0);
639   
640   if (*arg == '\0' || *end != '\0')
641     {
642       g_set_error (error,
643                    G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
644                    _("Cannot parse integer value '%s' for %s"),
645                    arg, arg_name);
646       return FALSE;
647     }
648
649   *result = tmp;
650   if (*result != tmp || errno == ERANGE)
651     {
652       g_set_error (error,
653                    G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
654                    _("Integer value '%s' for %s out of range"),
655                    arg, arg_name);
656       return FALSE;
657     }
658
659   return TRUE;
660 }
661
662 static Change *
663 get_change (GOptionContext *context,
664             GOptionArg      arg_type,
665             gpointer        arg_data)
666 {
667   GList *list;
668   Change *change = NULL;
669   
670   for (list = context->changes; list != NULL; list = list->next)
671     {
672       change = list->data;
673
674       if (change->arg_data == arg_data)
675         goto found;
676     }
677
678   change = g_new0 (Change, 1);
679   change->arg_type = arg_type;
680   change->arg_data = arg_data;
681   
682   context->changes = g_list_prepend (context->changes, change);
683   
684  found:
685
686   return change;
687 }
688
689 static void
690 add_pending_null (GOptionContext *context,
691                   gchar         **ptr,
692                   gchar          *value)
693 {
694   PendingNull *n;
695
696   n = g_new0 (PendingNull, 1);
697   n->ptr = ptr;
698   n->value = value;
699
700   context->pending_nulls = g_list_prepend (context->pending_nulls, n);
701 }
702                   
703 static gboolean
704 parse_arg (GOptionContext *context,
705            GOptionGroup   *group,
706            GOptionEntry   *entry,
707            const gchar    *value,
708            const gchar    *option_name,
709            GError        **error)
710      
711 {
712   Change *change;
713   
714   switch (entry->arg)
715     {
716     case G_OPTION_ARG_NONE:
717       {
718         change = get_change (context, G_OPTION_ARG_NONE,
719                              entry->arg_data);
720
721         *(gboolean *)entry->arg_data = !(entry->flags & G_OPTION_FLAG_REVERSE);
722         break;
723       }      
724     case G_OPTION_ARG_STRING:
725       {
726         gchar *data;
727
728         data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
729
730         if (!data)
731           return FALSE;
732
733         change = get_change (context, G_OPTION_ARG_STRING,
734                              entry->arg_data);
735         g_free (change->allocated.str);
736         
737         change->prev.str = *(gchar **)entry->arg_data;
738         change->allocated.str = data;
739         
740         *(gchar **)entry->arg_data = data;
741         break;
742       }
743     case G_OPTION_ARG_STRING_ARRAY:
744       {
745         gchar *data;
746         
747         data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
748
749         if (!data)
750           return FALSE;
751
752         change = get_change (context, G_OPTION_ARG_STRING_ARRAY,
753                              entry->arg_data);
754
755         if (change->allocated.array.len == 0)
756           {
757             change->prev.array = entry->arg_data;
758             change->allocated.array.data = g_new (gchar *, 2);
759           }
760         else
761           change->allocated.array.data =
762             g_renew (gchar *, change->allocated.array.data,
763                      change->allocated.array.len + 2);
764
765         change->allocated.array.data[change->allocated.array.len] = data;
766         change->allocated.array.data[change->allocated.array.len + 1] = NULL;
767
768         change->allocated.array.len ++;
769
770         *(gchar ***)entry->arg_data = change->allocated.array.data;
771
772         break;
773       }
774       
775     case G_OPTION_ARG_FILENAME:
776       {
777         gchar *data;
778
779 #ifdef G_OS_WIN32
780         data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
781         
782         if (!data)
783           return FALSE;
784 #else
785         data = g_strdup (value);
786 #endif
787         change = get_change (context, G_OPTION_ARG_FILENAME,
788                              entry->arg_data);
789         g_free (change->allocated.str);
790         
791         change->prev.str = *(gchar **)entry->arg_data;
792         change->allocated.str = data;
793
794         *(gchar **)entry->arg_data = data;
795         break;
796       }
797
798     case G_OPTION_ARG_FILENAME_ARRAY:
799       {
800         gchar *data;
801         
802 #ifdef G_OS_WIN32
803         data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
804         
805         if (!data)
806           return FALSE;
807 #else
808         data = g_strdup (value);
809 #endif
810         change = get_change (context, G_OPTION_ARG_STRING_ARRAY,
811                              entry->arg_data);
812
813         if (change->allocated.array.len == 0)
814           {
815             change->prev.array = entry->arg_data;
816             change->allocated.array.data = g_new (gchar *, 2);
817           }
818         else
819           change->allocated.array.data =
820             g_renew (gchar *, change->allocated.array.data,
821                      change->allocated.array.len + 2);
822
823         change->allocated.array.data[change->allocated.array.len] = data;
824         change->allocated.array.data[change->allocated.array.len + 1] = NULL;
825
826         change->allocated.array.len ++;
827
828         *(gchar ***)entry->arg_data = change->allocated.array.data;
829
830         break;
831       }
832       
833     case G_OPTION_ARG_INT:
834       {
835         gint data;
836
837         if (!parse_int (option_name, value,
838                         &data,
839                         error))
840           return FALSE;
841
842         change = get_change (context, G_OPTION_ARG_INT,
843                              entry->arg_data);
844         change->prev.integer = *(gint *)entry->arg_data;
845         *(gint *)entry->arg_data = data;
846         break;
847       }
848     case G_OPTION_ARG_CALLBACK:
849       {
850         gchar *tmp;
851         gboolean retval;
852         
853         tmp = g_locale_to_utf8 (value, -1, NULL, NULL, error);
854
855         if (!value)
856           return FALSE;
857
858         retval = (* (GOptionArgFunc) entry->arg_data) (option_name, tmp, group->user_data, error);
859         
860         g_free (tmp);
861         
862         return retval;
863         
864         break;
865       }
866     default:
867       g_assert_not_reached ();
868     }
869
870   return TRUE;
871 }
872
873 static gboolean
874 parse_short_option (GOptionContext *context,
875                     GOptionGroup   *group,
876                     gint            index,
877                     gint           *new_index,
878                     gchar           arg,
879                     gint           *argc,
880                     gchar        ***argv,
881                     GError        **error,
882                     gboolean       *parsed)
883 {
884   gint j;
885     
886   for (j = 0; j < group->n_entries; j++)
887     {
888       if (arg == group->entries[j].short_name)
889         {
890           if (group->entries[j].arg == G_OPTION_ARG_NONE)
891             {
892               parse_arg (context, group, &group->entries[j],
893                          NULL, NULL, error);
894               *parsed = TRUE;
895             }
896           else
897             {
898               gchar *value = NULL;
899               gchar *option_name;
900               
901               if (*new_index > index)
902                 {
903                   g_warning ("FIXME: figure out the correct error here");
904
905                   return FALSE;
906                 }
907
908               option_name = g_strdup_printf ("-%c", group->entries[j].short_name);
909               
910               if (index < *argc - 1)
911                 {
912                   value = (*argv)[index + 1];
913                   add_pending_null (context, &((*argv)[index + 1]), NULL);
914                   *new_index = index + 1;
915                 }
916               else
917                 {
918                   g_set_error (error, 
919                                G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
920                                _("Missing argument for %s"), option_name);
921                   g_free (option_name);
922                   return FALSE;
923                 }
924               
925               if (!parse_arg (context, group, &group->entries[j], value, option_name, error))
926                 {
927                   g_free (option_name);
928                   return FALSE;
929                 }
930
931               g_free (option_name);
932               *parsed = TRUE;
933             }
934         }
935     }
936
937   return TRUE;
938 }
939
940 static gboolean
941 parse_long_option (GOptionContext *context,
942                    GOptionGroup   *group,
943                    gint           *index,
944                    gchar          *arg,
945                    gint           *argc,
946                    gchar        ***argv,
947                    GError        **error,
948                    gboolean       *parsed)
949 {
950   gint j;
951
952   for (j = 0; j < group->n_entries; j++)
953     {
954       if (*index >= *argc)
955         return TRUE;
956
957       if (group->entries[j].arg == G_OPTION_ARG_NONE &&
958           strcmp (arg, group->entries[j].long_name) == 0)
959         {
960           parse_arg (context, group, &group->entries[j],
961                      NULL, NULL, error);
962           
963           add_pending_null (context, &((*argv)[*index]), NULL);
964           *parsed = TRUE;
965         }
966       else
967         {
968           gint len = strlen (group->entries[j].long_name);
969           
970           if (strncmp (arg, group->entries[j].long_name, len) == 0 &&
971               (arg[len] == '=' || arg[len] == 0))
972             {
973               gchar *value = NULL;
974               gchar *option_name;
975
976               add_pending_null (context, &((*argv)[*index]), NULL);
977               option_name = g_strconcat ("--", group->entries[j].long_name, NULL);
978
979               if (arg[len] == '=')
980                 value = arg + len + 1;
981               else if (*index < *argc - 1)
982                 {
983                   value = (*argv)[*index + 1];
984                   add_pending_null (context, &((*argv)[*index + 1]), NULL);
985                   (*index)++;
986                 }
987               else
988                 {
989                   g_set_error (error, 
990                                G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
991                                _("Missing argument for %s"), option_name);
992                   g_free (option_name);
993                   return FALSE;
994                 }
995
996               if (!parse_arg (context, group, &group->entries[j], value, option_name, error))
997                 {
998                   g_free (option_name);
999                   return FALSE;
1000                 }
1001
1002               g_free (option_name);
1003               *parsed = TRUE;
1004             }
1005         }
1006     }
1007   
1008   return TRUE;
1009 }
1010
1011 static gboolean
1012 parse_remaining_arg (GOptionContext *context,
1013                      GOptionGroup   *group,
1014                      gint           *index,
1015                      gint           *argc,
1016                      gchar        ***argv,
1017                      GError        **error,
1018                      gboolean       *parsed)
1019 {
1020   gint j;
1021
1022   for (j = 0; j < group->n_entries; j++)
1023     {
1024       if (*index >= *argc)
1025         return TRUE;
1026
1027       if (group->entries[j].long_name[0])
1028         continue;
1029
1030       g_return_val_if_fail (group->entries[j].arg == G_OPTION_ARG_STRING_ARRAY ||
1031                             group->entries[j].arg == G_OPTION_ARG_FILENAME_ARRAY, FALSE);
1032       
1033       add_pending_null (context, &((*argv)[*index]), NULL);
1034       
1035       if (!parse_arg (context, group, &group->entries[j], (*argv)[*index], "", error))
1036         return FALSE;
1037       
1038       *parsed = TRUE;
1039       return TRUE;
1040     }
1041
1042   return TRUE;
1043 }
1044
1045 static void
1046 free_changes_list (GOptionContext *context,
1047                    gboolean        revert)
1048 {
1049   GList *list;
1050
1051   for (list = context->changes; list != NULL; list = list->next)
1052     {
1053       Change *change = list->data;
1054
1055       if (revert)
1056         {
1057           switch (change->arg_type)
1058             {
1059             case G_OPTION_ARG_NONE:
1060               *(gboolean *)change->arg_data = change->prev.bool;
1061               break;
1062             case G_OPTION_ARG_INT:
1063               *(gint *)change->arg_data = change->prev.integer;
1064               break;
1065             case G_OPTION_ARG_STRING:
1066             case G_OPTION_ARG_FILENAME:
1067               g_free (change->allocated.str);
1068               *(gchar **)change->arg_data = change->prev.str;
1069               break;
1070             case G_OPTION_ARG_STRING_ARRAY:
1071             case G_OPTION_ARG_FILENAME_ARRAY:
1072               g_strfreev (change->allocated.array.data);
1073               *(gchar ***)change->arg_data = change->prev.array;
1074               break;
1075             default:
1076               g_assert_not_reached ();
1077             }
1078         }
1079       
1080       g_free (change);
1081     }
1082
1083   g_list_free (context->changes);
1084   context->changes = NULL;
1085 }
1086
1087 static void
1088 free_pending_nulls (GOptionContext *context,
1089                     gboolean        perform_nulls)
1090 {
1091   GList *list;
1092
1093   for (list = context->pending_nulls; list != NULL; list = list->next)
1094     {
1095       PendingNull *n = list->data;
1096
1097       if (perform_nulls)
1098         {
1099           if (n->value)
1100             {
1101               /* Copy back the short options */
1102               *(n->ptr)[0] = '-';             
1103               strcpy (*n->ptr + 1, n->value);
1104             }
1105           else
1106             *n->ptr = NULL;
1107         }
1108       
1109       g_free (n->value);
1110       g_free (n);
1111     }
1112
1113   g_list_free (context->pending_nulls);
1114   context->pending_nulls = NULL;
1115 }
1116
1117 /**
1118  * g_option_context_parse:
1119  * @context: a #GOptionContext
1120  * @argc: a pointer to the number of command line arguments.
1121  * @argv: a pointer to the array of command line arguments.
1122  * @error: a return location for errors 
1123  * 
1124  * Parses the command line arguments, recognizing options
1125  * which have been added to @context. A side-effect of 
1126  * calling this function is that g_set_prgname() will be
1127  * called.
1128  *
1129  * If the parsing is successful, any parsed arguments are
1130  * removed from the array and @argc and @argv are updated 
1131  * accordingly. A '--' option is stripped from @argv
1132  * unless there are unparsed options before and after it, 
1133  * or some of the options after it start with '-'. In case 
1134  * of an error, @argc and @argv are left unmodified. 
1135  *
1136  * If automatic <option>--help</option> support is enabled
1137  * (see g_option_context_set_help_enabled()), and the 
1138  * @argv array contains one of the recognized help options,
1139  * this function will produce help output to stdout and
1140  * call <literal>exit (0)</literal>.
1141  * 
1142  * Return value: %TRUE if the parsing was successful, 
1143  *               %FALSE if an error occurred
1144  *
1145  * Since: 2.6
1146  **/
1147 gboolean
1148 g_option_context_parse (GOptionContext   *context,
1149                         gint             *argc,
1150                         gchar          ***argv,
1151                         GError          **error)
1152 {
1153   gint i, j, k;
1154   GList *list;
1155
1156   /* Set program name */
1157   if (argc && argv && *argc)
1158     {
1159       gchar *prgname;
1160       
1161       prgname = g_path_get_basename ((*argv)[0]);
1162       g_set_prgname (prgname);
1163       g_free (prgname);
1164     }
1165   else
1166     {
1167       g_set_prgname ("<unknown>");
1168     }
1169   
1170   /* Call pre-parse hooks */
1171   list = context->groups;
1172   while (list)
1173     {
1174       GOptionGroup *group = list->data;
1175       
1176       if (group->pre_parse_func)
1177         {
1178           if (!(* group->pre_parse_func) (context, group,
1179                                           group->user_data, error))
1180             goto fail;
1181         }
1182       
1183       list = list->next;
1184     }
1185
1186   if (context->main_group && context->main_group->pre_parse_func)
1187     {
1188       if (!(* context->main_group->pre_parse_func) (context, context->main_group,
1189                                                     context->main_group->user_data, error))
1190         goto fail;
1191     }
1192
1193   if (argc && argv)
1194     {
1195       gboolean stop_parsing = FALSE;
1196       gboolean has_unknown = FALSE;
1197       gint separator_pos = 0;
1198
1199       for (i = 1; i < *argc; i++)
1200         {
1201           gchar *arg, *dash;
1202           gboolean parsed = FALSE;
1203
1204           if ((*argv)[i][0] == '-' && (*argv)[i][1] != '\0' && !stop_parsing)
1205             {
1206               if ((*argv)[i][1] == '-')
1207                 {
1208                   /* -- option */
1209
1210                   arg = (*argv)[i] + 2;
1211
1212                   /* '--' terminates list of arguments */
1213                   if (*arg == 0)
1214                     {
1215                       separator_pos = i;
1216                       stop_parsing = TRUE;
1217                       continue;
1218                     }
1219
1220                   /* Handle help options */
1221                   if (context->help_enabled)
1222                     {
1223                       if (strcmp (arg, "help") == 0)
1224                         print_help (context, TRUE, NULL);
1225                       else if (strcmp (arg, "help-all") == 0)
1226                         print_help (context, FALSE, NULL);                    
1227                       else if (strncmp (arg, "help-", 5) == 0)
1228                         {
1229                           GList *list;
1230                           
1231                           list = context->groups;
1232                           
1233                           while (list)
1234                             {
1235                               GOptionGroup *group = list->data;
1236                               
1237                               if (strcmp (arg + 5, group->name) == 0)
1238                                 print_help (context, FALSE, group);                                           
1239                               
1240                               list = list->next;
1241                             }
1242                         }
1243                     }
1244
1245                   if (context->main_group &&
1246                       !parse_long_option (context, context->main_group, &i, arg,
1247                                           argc, argv, error, &parsed))
1248                     goto fail;
1249
1250                   if (parsed)
1251                     continue;
1252                   
1253                   /* Try the groups */
1254                   list = context->groups;
1255                   while (list)
1256                     {
1257                       GOptionGroup *group = list->data;
1258                       
1259                       if (!parse_long_option (context, group, &i, arg,
1260                                               argc, argv, error, &parsed))
1261                         goto fail;
1262                       
1263                       if (parsed)
1264                         break;
1265                       
1266                       list = list->next;
1267                     }
1268                   
1269                   if (parsed)
1270                     continue;
1271
1272                   /* Now look for --<group>-<option> */
1273                   dash = strchr (arg, '-');
1274                   if (dash)
1275                     {
1276                       /* Try the groups */
1277                       list = context->groups;
1278                       while (list)
1279                         {
1280                           GOptionGroup *group = list->data;
1281                           
1282                           if (strncmp (group->name, arg, dash - arg) == 0)
1283                             {
1284                               if (!parse_long_option (context, group, &i, dash + 1,
1285                                                       argc, argv, error, &parsed))
1286                                 goto fail;
1287                               
1288                               if (parsed)
1289                                 break;
1290                             }
1291                           
1292                           list = list->next;
1293                         }
1294                     }
1295                   
1296                   if (context->ignore_unknown)
1297                     continue;
1298                 }
1299               else
1300                 {
1301                   /* short option */
1302
1303                   gint new_i, j;
1304                   gboolean *nulled_out = NULL;
1305                   
1306                   arg = (*argv)[i] + 1;
1307
1308                   new_i = i;
1309
1310                   if (context->ignore_unknown)
1311                     nulled_out = g_new0 (gboolean, strlen (arg));
1312                   
1313                   for (j = 0; j < strlen (arg); j++)
1314                     {
1315                       if (context->help_enabled && arg[j] == '?')
1316                         print_help (context, TRUE, NULL);
1317                       
1318                       parsed = FALSE;
1319                       
1320                       if (context->main_group &&
1321                           !parse_short_option (context, context->main_group,
1322                                                i, &new_i, arg[j],
1323                                                argc, argv, error, &parsed))
1324                         {
1325
1326                           g_free (nulled_out);
1327                           goto fail;
1328                         }
1329
1330                       if (!parsed)
1331                         {
1332                           /* Try the groups */
1333                           list = context->groups;
1334                           while (list)
1335                             {
1336                               GOptionGroup *group = list->data;
1337                               
1338                               if (!parse_short_option (context, group, i, &new_i, arg[j],
1339                                                        argc, argv, error, &parsed))
1340                                 goto fail;
1341                               
1342                               if (parsed)
1343                                 break;
1344                           
1345                               list = list->next;
1346                             }
1347                         }
1348
1349                       if (context->ignore_unknown)
1350                         {
1351                           if (parsed)
1352                             nulled_out[j] = TRUE;
1353                           else
1354                             continue;
1355                         }
1356
1357                       if (!parsed)
1358                         break;
1359                     }
1360
1361                   if (context->ignore_unknown)
1362                     {
1363                       gchar *new_arg = NULL; 
1364                       gint arg_index = 0;
1365                       
1366                       for (j = 0; j < strlen (arg); j++)
1367                         {
1368                           if (!nulled_out[j])
1369                             {
1370                               if (!new_arg)
1371                                 new_arg = g_malloc (strlen (arg) + 1);
1372                               new_arg[arg_index++] = arg[j];
1373                             }
1374                         }
1375                       if (new_arg)
1376                         new_arg[arg_index] = '\0';
1377                       
1378                       add_pending_null (context, &((*argv)[i]), new_arg);
1379                     }
1380                   else if (parsed)
1381                     {
1382                       add_pending_null (context, &((*argv)[i]), NULL);
1383                       i = new_i;
1384                     }
1385                 }
1386               
1387               if (!parsed)
1388                 has_unknown = TRUE;
1389
1390               if (!parsed && !context->ignore_unknown)
1391                 {
1392                   g_set_error (error,
1393                                G_OPTION_ERROR, G_OPTION_ERROR_UNKNOWN_OPTION,
1394                                    _("Unknown option %s"), (*argv)[i]);
1395                   goto fail;
1396                 }
1397             }
1398           else
1399             {
1400               /* Collect remaining args */
1401               if (context->main_group &&
1402                   !parse_remaining_arg (context, context->main_group, &i,
1403                                         argc, argv, error, &parsed))
1404                 goto fail;
1405               
1406               if (!parsed && (has_unknown || (*argv)[i][0] == '-'))
1407                 separator_pos = 0;
1408             }
1409         }
1410
1411       if (separator_pos > 0)
1412         add_pending_null (context, &((*argv)[separator_pos]), NULL);
1413         
1414     }
1415
1416   /* Call post-parse hooks */
1417   list = context->groups;
1418   while (list)
1419     {
1420       GOptionGroup *group = list->data;
1421       
1422       if (group->post_parse_func)
1423         {
1424           if (!(* group->post_parse_func) (context, group,
1425                                            group->user_data, error))
1426             goto fail;
1427         }
1428       
1429       list = list->next;
1430     }
1431   
1432   if (context->main_group && context->main_group->post_parse_func)
1433     {
1434       if (!(* context->main_group->post_parse_func) (context, context->main_group,
1435                                                      context->main_group->user_data, error))
1436         goto fail;
1437     }
1438   
1439   if (argc && argv)
1440     {
1441       free_pending_nulls (context, TRUE);
1442       
1443       for (i = 1; i < *argc; i++)
1444         {
1445           for (k = i; k < *argc; k++)
1446             if ((*argv)[k] != NULL)
1447               break;
1448           
1449           if (k > i)
1450             {
1451               k -= i;
1452               for (j = i + k; j < *argc; j++)
1453                 {
1454                   (*argv)[j-k] = (*argv)[j];
1455                   (*argv)[j] = NULL;
1456                 }
1457               *argc -= k;
1458             }
1459         }      
1460     }
1461
1462   return TRUE;
1463
1464  fail:
1465   
1466   /* Call error hooks */
1467   list = context->groups;
1468   while (list)
1469     {
1470       GOptionGroup *group = list->data;
1471       
1472       if (group->error_func)
1473         (* group->error_func) (context, group,
1474                                group->user_data, error);
1475       
1476       list = list->next;
1477     }
1478
1479   if (context->main_group && context->main_group->error_func)
1480     (* context->main_group->error_func) (context, context->main_group,
1481                                          context->main_group->user_data, error);
1482   
1483   free_changes_list (context, TRUE);
1484   free_pending_nulls (context, FALSE);
1485
1486   return FALSE;
1487 }
1488                                    
1489 /**
1490  * g_option_group_new:
1491  * @name: the name for the option group, this is used to provide
1492  *   help for the options in this group with <option>--help-</option>@name
1493  * @description: a description for this group to be shown in 
1494  *   <option>--help</option>. This string is translated using the translation
1495  *   domain or translation function of the group
1496  * @help_description: a description for the <option>--help-</option>@name option.
1497  *   This string is translated using the translation domain or translation function
1498  *   of the group
1499  * @user_data: user data that will be passed to the pre- and post-parse hooks,
1500  *   the error hook and to callbacks of %G_OPTION_ARG_CALLBACK options, or %NULL
1501  * @destroy: a function that will be called to free @user_data, or %NULL
1502  * 
1503  * Creates a new #GOptionGroup.
1504  * 
1505  * Return value: a newly created option group. It should be added 
1506  *   to a #GOptionContext or freed with g_option_group_free().
1507  *
1508  * Since: 2.6
1509  **/
1510 GOptionGroup *
1511 g_option_group_new (const gchar    *name,
1512                     const gchar    *description,
1513                     const gchar    *help_description,
1514                     gpointer        user_data,
1515                     GDestroyNotify  destroy)
1516
1517 {
1518   GOptionGroup *group;
1519
1520   group = g_new0 (GOptionGroup, 1);
1521   group->name = g_strdup (name);
1522   group->description = g_strdup (description);
1523   group->help_description = g_strdup (help_description);
1524   group->user_data = user_data;
1525   group->destroy_notify = destroy;
1526   
1527   return group;
1528 }
1529
1530
1531 /**
1532  * g_option_group_free:
1533  * @group: a #GOptionGroup
1534  * 
1535  * Frees a #GOptionGroup. Note that you must <emphasis>not</emphasis>
1536  * free groups which have been added to a #GOptionContext.
1537  *
1538  * Since: 2.6
1539  **/
1540 void
1541 g_option_group_free (GOptionGroup *group)
1542 {
1543   g_return_if_fail (group != NULL);
1544
1545   g_free (group->name);
1546   g_free (group->description);
1547   g_free (group->help_description);
1548
1549   g_free (group->entries);
1550   
1551   if (group->destroy_notify)
1552     (* group->destroy_notify) (group->user_data);
1553
1554   if (group->translate_notify)
1555     (* group->translate_notify) (group->translate_data);
1556   
1557   g_free (group);
1558 }
1559
1560
1561 /**
1562  * g_option_group_add_entries:
1563  * @group: a #GOptionGroup
1564  * @entries: a %NULL-terminated array of #GOptionEntry<!-- -->s
1565  * 
1566  * Adds the options specified in @entries to @group.
1567  *
1568  * Since: 2.6
1569  **/
1570 void
1571 g_option_group_add_entries (GOptionGroup       *group,
1572                             const GOptionEntry *entries)
1573 {
1574   gint n_entries;
1575   
1576   g_return_if_fail (entries != NULL);
1577
1578   for (n_entries = 0; entries[n_entries].long_name != NULL; n_entries++);
1579
1580   group->entries = g_renew (GOptionEntry, group->entries, group->n_entries + n_entries);
1581
1582   memcpy (group->entries + group->n_entries, entries, sizeof (GOptionEntry) * n_entries);
1583
1584   group->n_entries += n_entries;
1585 }
1586
1587 /**
1588  * g_option_group_set_parse_hooks:
1589  * @group: a #GOptionGroup
1590  * @pre_parse_func: a function to call before parsing, or %NULL
1591  * @post_parse_func: a function to call after parsing, or %NULL
1592  * 
1593  * Associates two functions with @group which will be called 
1594  * from g_option_context_parse() before the first option is parsed
1595  * and after the last option has been parsed, respectively.
1596  *
1597  * Note that the user data to be passed to @pre_parse_func and
1598  * @post_parse_func can be specified when constructing the group
1599  * with g_option_group_new().
1600  *
1601  * Since: 2.6
1602  **/
1603 void
1604 g_option_group_set_parse_hooks (GOptionGroup     *group,
1605                                 GOptionParseFunc  pre_parse_func,
1606                                 GOptionParseFunc  post_parse_func)
1607 {
1608   g_return_if_fail (group != NULL);
1609
1610   group->pre_parse_func = pre_parse_func;
1611   group->post_parse_func = post_parse_func;  
1612 }
1613
1614 /**
1615  * g_option_group_set_error_hook:
1616  * @group: a #GOptionGroup
1617  * @error_func: a function to call when an error occurs
1618  * 
1619  * Associates a function with @group which will be called 
1620  * from g_option_context_parse() when an error occurs.
1621  *
1622  * Note that the user data to be passed to @pre_parse_func and
1623  * @post_parse_func can be specified when constructing the group
1624  * with g_option_group_new().
1625  *
1626  * Since: 2.6
1627  **/
1628 void
1629 g_option_group_set_error_hook (GOptionGroup     *group,
1630                                GOptionErrorFunc  error_func)
1631 {
1632   g_return_if_fail (group != NULL);
1633
1634   group->error_func = error_func;  
1635 }
1636
1637
1638 /**
1639  * g_option_group_set_translate_func:
1640  * @group: a #GOptionGroup
1641  * @func: the #GTranslateFunc, or %NULL 
1642  * @data: user data to pass to @func, or %NULL
1643  * @destroy_notify: a function which gets called to free @data, or %NULL
1644  * 
1645  * Sets the function which is used to translate user-visible
1646  * strings, for <option>--help</option> output. Different
1647  * groups can use different #GTranslateFunc<!-- -->s. If @func
1648  * is %NULL, strings are not translated.
1649  *
1650  * If you are using gettext(), you only need to set the translation
1651  * domain, see g_option_group_set_translation_domain().
1652  *
1653  * Since: 2.6
1654  **/
1655 void
1656 g_option_group_set_translate_func (GOptionGroup   *group,
1657                                    GTranslateFunc  func,
1658                                    gpointer        data,
1659                                    GDestroyNotify  destroy_notify)
1660 {
1661   g_return_if_fail (group != NULL);
1662   
1663   if (group->translate_notify)
1664     group->translate_notify (group->translate_data);
1665       
1666   group->translate_func = func;
1667   group->translate_data = data;
1668   group->translate_notify = destroy_notify;
1669 }
1670
1671 static gchar *
1672 dgettext_swapped (const gchar *msgid, 
1673                   const gchar *domainname)
1674 {
1675   return dgettext (domainname, msgid);
1676 }
1677
1678 /**
1679  * g_option_group_set_translation_domain:
1680  * @group: a #GOptionGroup
1681  * @domain: the domain to use
1682  * 
1683  * A convenience function to use gettext() for translating
1684  * user-visible strings. 
1685  * 
1686  * Since: 2.6
1687  **/
1688 void
1689 g_option_group_set_translation_domain (GOptionGroup *group,
1690                                        const gchar  *domain)
1691 {
1692   g_return_if_fail (group != NULL);
1693
1694   g_option_group_set_translate_func (group, 
1695                                      (GTranslateFunc)dgettext_swapped,
1696                                      g_strdup (domain),
1697                                      g_free);
1698
1699
1700 #define __G_OPTION_C__
1701 #include "galiasdef.c"