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