glib/: fully remove galias hacks
[platform/upstream/glib.git] / glib / goption.c
index c1e6068..ff762e8 100644 (file)
  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  * Boston, MA 02111-1307, USA.
  */
+/**
+ * SECTION:option
+ * @Short_description: parses commandline options
+ * @Title: Commandline option parser
+ * 
+ * The GOption commandline parser is intended to be a simpler replacement for the
+ * popt library. It supports short and long commandline options, as shown in the 
+ * following example:
+ * 
+ * <literal>testtreemodel -r 1 --max-size 20 --rand --display=:1.0 -vb -- file1 file2</literal>
+ * 
+ * The example demonstrates a number of features of the GOption commandline parser
+ * <itemizedlist><listitem><para>
+ *   Options can be single letters, prefixed by a single dash. Multiple
+ *   short options can be grouped behind a single dash.
+ * </para></listitem><listitem><para>
+ *   Long options are prefixed by two consecutive dashes.
+ * </para></listitem><listitem><para>
+ *   Options can have an extra argument, which can be a number, a string or a 
+ *   filename. For long options, the extra argument can be appended with an 
+ *   equals sign after the option name.
+ * </para></listitem><listitem><para>
+ *   Non-option arguments are returned to the application as rest arguments.
+ * </para></listitem><listitem><para>
+ *   An argument consisting solely of two dashes turns off further parsing, 
+ *   any remaining arguments (even those starting with a dash) are returned 
+ *   to the application as rest arguments.
+ * </para></listitem></itemizedlist>
+ * 
+ * Another important feature of GOption is that it can automatically generate 
+ * nicely formatted help output. Unless it is explicitly turned off with 
+ * g_option_context_set_help_enabled(), GOption will recognize the 
+ * <option>--help</option>, <option>-?</option>, <option>--help-all</option>
+ * and <option>--help-</option><replaceable>groupname</replaceable> options 
+ * (where <replaceable>groupname</replaceable> is the name of a #GOptionGroup) 
+ * and write a text similar to the one shown in the following example to stdout.
+ * 
+ * <informalexample><screen>
+ * Usage:
+ *   testtreemodel [OPTION...] - test tree model performance
+ *  
+ * Help Options:
+ *   -h, --help               Show help options
+ *   --help-all               Show all help options
+ *   --help-gtk               Show GTK+ Options
+ *  
+ * Application Options:
+ *   -r, --repeats=N          Average over N repetitions
+ *   -m, --max-size=M         Test up to 2^M items
+ *   --display=DISPLAY        X display to use
+ *   -v, --verbose            Be verbose
+ *   -b, --beep               Beep when done   
+ *   --rand                   Randomize the data
+ * </screen></informalexample>
+ * 
+ * GOption groups options in #GOptionGroup<!-- -->s, which makes it easy to
+ * incorporate options from multiple sources. The intended use for this is
+ * to let applications collect option groups from the libraries it uses,
+ * add them to their #GOptionContext, and parse all options by a single call
+ * to g_option_context_parse(). See gtk_get_option_group() for an example.
+ *
+ * If an option is declared to be of type string or filename, GOption takes
+ * care of converting it to the right encoding; strings are returned in UTF-8,
+ * filenames are returned in the GLib filename encoding. Note that this only
+ * works if setlocale() has been called before g_option_context_parse().
+ * 
+ * Here is a complete example of setting up GOption to parse the example
+ * commandline above and produce the example help output.
+ * 
+ * <informalexample><programlisting>
+ * static gint repeats = 2;
+ * static gint max_size = 8;
+ * static gboolean verbose = FALSE;
+ * static gboolean beep = FALSE;
+ * static gboolean rand = FALSE;
+ * 
+ * static GOptionEntry entries[] = 
+ * {
+ *   { "repeats", 'r', 0, G_OPTION_ARG_INT, &repeats, "Average over N repetitions", "N" },
+ *   { "max-size", 'm', 0, G_OPTION_ARG_INT, &max_size, "Test up to 2^M items", "M" },
+ *   { "verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose, "Be verbose", NULL },
+ *   { "beep", 'b', 0, G_OPTION_ARG_NONE, &beep, "Beep when done", NULL },
+ *   { "rand", 0, 0, G_OPTION_ARG_NONE, &rand, "Randomize the data", NULL },
+ *   { NULL }
+ * };
+ * 
+ * int 
+ * main (int argc, char *argv[])
+ * {
+ *   GError *error = NULL;
+ *   GOptionContext *context;
+ * 
+ *   context = g_option_context_new ("- test tree model performance");
+ *   g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
+ *   g_option_context_add_group (context, gtk_get_option_group (TRUE));
+ *   if (!g_option_context_parse (context, &argc, &argv, &error))
+ *     {
+ *       g_print ("option parsing failed: %s\n", error->message);
+ *       exit (1);
+ *     }
+ * 
+ *   // ...
+ * 
+ * }
+ * </programlisting></informalexample>
+ */
 
 #include "config.h"
 
 #include "glibintl.h"
 #include "gprintf.h"
 
-#include "galias.h"
 
 #include <string.h>
 #include <stdlib.h>
@@ -236,6 +341,9 @@ g_option_context_new (const gchar *parameter_string)
  * Frees context and all the groups which have been 
  * added to it.
  *
+ * Please note that parsed arguments need to be freed separately (see
+ * #GOptionEntry).
+ *
  * Since: 2.6
  */
 void g_option_context_free (GOptionContext *context) 
@@ -269,7 +377,8 @@ void g_option_context_free (GOptionContext *context)
  *
  * Enables or disables automatic generation of <option>--help</option> 
  * output. By default, g_option_context_parse() recognizes
- * <option>--help</option>, <option>-?</option>, <option>--help-all</option>
+ * <option>--help</option>, <option>-h</option>,
+ * <option>-?</option>, <option>--help-all</option>
  * and <option>--help-</option><replaceable>groupname</replaceable> and creates
  * suitable output to stdout. 
  *
@@ -520,6 +629,77 @@ print_entry (GOptionGroup       *group,
   g_string_free (str, TRUE);  
 }
 
+static gboolean
+group_has_visible_entries (GOptionContext *context,
+                           GOptionGroup *group,
+                           gboolean      main_entries)
+{
+  GOptionFlags reject_filter = G_OPTION_FLAG_HIDDEN;
+  GOptionEntry *entry;
+  gint i, l;
+  gboolean main_group = group == context->main_group;
+
+  if (!main_entries)
+    reject_filter |= G_OPTION_FLAG_IN_MAIN;
+
+  for (i = 0, l = (group ? group->n_entries : 0); i < l; i++)
+    {
+      entry = &group->entries[i];
+
+      if (main_entries && !main_group && !(entry->flags & G_OPTION_FLAG_IN_MAIN))
+        continue;
+      if (!(entry->flags & reject_filter))
+        return TRUE;
+    }
+
+  return FALSE;
+}
+
+static gboolean
+group_list_has_visible_entires (GOptionContext *context,
+                                GList          *group_list,
+                                gboolean       main_entries)
+{
+  while (group_list)
+    {
+      if (group_has_visible_entries (context, group_list->data, main_entries))
+        return TRUE;
+
+      group_list = group_list->next;
+    }
+
+  return FALSE;
+}
+
+static gboolean
+context_has_h_entry (GOptionContext *context)
+{
+  gsize i;
+  GList *list;
+
+  if (context->main_group)
+    {
+      for (i = 0; i < context->main_group->n_entries; i++)
+        {
+          if (context->main_group->entries[i].short_name == 'h')
+            return TRUE;
+        }
+    }
+
+  for (list = context->groups; list != NULL; list = g_list_next (list))
+    {
+     GOptionGroup *group;
+
+      group = (GOptionGroup*)list->data;
+      for (i = 0; i < group->n_entries; i++)
+        {
+          if (group->entries[i].short_name == 'h')
+            return TRUE;
+        }
+    }
+  return FALSE;
+}
+
 /**
  * g_option_context_get_help: 
  * @context: a #GOptionContext
@@ -551,6 +731,7 @@ g_option_context_get_help (GOptionContext *context,
   gboolean seen[256];
   const gchar *rest_description;
   GString *string;
+  guchar token;
 
   string = g_string_sized_new (1024);
 
@@ -614,13 +795,13 @@ g_option_context_get_help (GOptionContext *context,
   list = context->groups;
   while (list != NULL)
     {
-      GOptionGroup *group = list->data;
-      for (i = 0; i < group->n_entries; i++)
+      GOptionGroup *g = list->data;
+      for (i = 0; i < g->n_entries; i++)
        {
-         entry = &group->entries[i];
+         entry = &g->entries[i];
          if (g_hash_table_lookup (shadow_map, entry->long_name) && 
              !(entry->flags & G_OPTION_FLAG_NOALIAS))
-           entry->long_name = g_strdup_printf ("%s-%s", group->name, entry->long_name);
+           entry->long_name = g_strdup_printf ("%s-%s", g->name, entry->long_name);
          else  
            g_hash_table_insert (shadow_map, (gpointer)entry->long_name, entry);
 
@@ -653,14 +834,14 @@ g_option_context_get_help (GOptionContext *context,
 
   while (list != NULL)
     {
-      GOptionGroup *group = list->data;
+      GOptionGroup *g = list->data;
       
       /* First, we check the --help-<groupname> options */
-      len = _g_utf8_strwidth ("--help-", -1) + _g_utf8_strwidth (group->name, -1);
+      len = _g_utf8_strwidth ("--help-", -1) + _g_utf8_strwidth (g->name, -1);
       max_length = MAX (max_length, len);
 
       /* Then we go through the entries */
-      len = calculate_max_length (group);
+      len = calculate_max_length (g);
       max_length = MAX (max_length, len);
       
       list = list->next;
@@ -672,9 +853,11 @@ g_option_context_get_help (GOptionContext *context,
   if (!group)
     {
       list = context->groups;
-      
+
+      token = context_has_h_entry (context) ? '?' : 'h';
+
       g_string_append_printf (string, "%s\n  -%c, --%-*s %s\n", 
-                             _("Help Options:"), '?', max_length - 4, "help", 
+                             _("Help Options:"), token, max_length - 4, "help", 
                              _("Show help options"));
       
       /* We only want --help-all when there are groups */
@@ -685,11 +868,12 @@ g_option_context_get_help (GOptionContext *context,
       
       while (list)
        {
-         GOptionGroup *group = list->data;
-         
-         g_string_append_printf (string, "  --help-%-*s %s\n", 
-                                  max_length - 5, group->name, 
-                                 TRANSLATE (group, group->help_description));
+         GOptionGroup *g = list->data;
+
+         if (group_has_visible_entries (context, g, FALSE))
+           g_string_append_printf (string, "  --help-%-*s %s\n",
+                                   max_length - 5, g->name,
+                                   TRANSLATE (g, g->help_description));
          
          list = list->next;
        }
@@ -700,12 +884,15 @@ g_option_context_get_help (GOptionContext *context,
   if (group)
     {
       /* Print a certain group */
-      
-      g_string_append (string, TRANSLATE (group, group->description));
-      g_string_append (string, "\n");
-      for (i = 0; i < group->n_entries; i++)
-       print_entry (group, max_length, &group->entries[i], string);
-      g_string_append (string, "\n");
+
+      if (group_has_visible_entries (context, group, FALSE))
+        {
+          g_string_append (string, TRANSLATE (group, group->description));
+          g_string_append (string, "\n");
+          for (i = 0; i < group->n_entries; i++)
+            print_entry (group, max_length, &group->entries[i], string);
+          g_string_append (string, "\n");
+        }
     }
   else if (!main_help)
     {
@@ -715,21 +902,27 @@ g_option_context_get_help (GOptionContext *context,
 
       while (list)
        {
-         GOptionGroup *group = list->data;
+         GOptionGroup *g = list->data;
 
-         g_string_append (string, group->description);
-          g_string_append (string, "\n");
-         for (i = 0; i < group->n_entries; i++)
-           if (!(group->entries[i].flags & G_OPTION_FLAG_IN_MAIN))
-             print_entry (group, max_length, &group->entries[i], string);
+         if (group_has_visible_entries (context, g, FALSE))
+           {
+             g_string_append (string, g->description);
+             g_string_append (string, "\n");
+             for (i = 0; i < g->n_entries; i++)
+               if (!(g->entries[i].flags & G_OPTION_FLAG_IN_MAIN))
+                 print_entry (g, max_length, &g->entries[i], string);
          
-         g_string_append (string, "\n");
+             g_string_append (string, "\n");
+           }
+
          list = list->next;
        }
     }
   
   /* Print application options if --help or --help-all has been specified */
-  if (main_help || !group)
+  if ((main_help || !group) &&
+      (group_has_visible_entries (context, context->main_group, TRUE) ||
+       group_list_has_visible_entires (context, context->groups, TRUE)))
     {
       list = context->groups;
 
@@ -742,12 +935,12 @@ g_option_context_get_help (GOptionContext *context,
 
       while (list != NULL)
        {
-         GOptionGroup *group = list->data;
+         GOptionGroup *g = list->data;
 
          /* Print main entries from other groups */
-         for (i = 0; i < group->n_entries; i++)
-           if (group->entries[i].flags & G_OPTION_FLAG_IN_MAIN)
-             print_entry (group, max_length, &group->entries[i], string);
+         for (i = 0; i < g->n_entries; i++)
+           if (g->entries[i].flags & G_OPTION_FLAG_IN_MAIN)
+             print_entry (g, max_length, &g->entries[i], string);
          
          list = list->next;
        }
@@ -764,6 +957,7 @@ g_option_context_get_help (GOptionContext *context,
   return g_string_free (string, FALSE);
 }
 
+G_GNUC_NORETURN
 static void
 print_help (GOptionContext *context,
            gboolean        main_help,
@@ -772,7 +966,7 @@ print_help (GOptionContext *context,
   gchar *help;
 
   help = g_option_context_get_help (context, main_help, group);
-  g_printf (help);
+  g_print ("%s", help);
   g_free (help);
 
   exit (0);  
@@ -1097,6 +1291,11 @@ parse_arg (GOptionContext *context,
 
        retval = (* (GOptionArgFunc) entry->arg_data) (option_name, data, group->user_data, error);
        
+       if (!retval && error != NULL && *error == NULL)
+         g_set_error (error, 
+                      G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
+                      _("Error parsing option %s"), option_name);
+
        g_free (data);
        
        return retval;
@@ -1147,8 +1346,8 @@ parse_arg (GOptionContext *context,
 static gboolean
 parse_short_option (GOptionContext *context,
                    GOptionGroup   *group,
-                   gint            index,
-                   gint           *new_index,
+                   gint            idx,
+                   gint           *new_idx,
                    gchar           arg,
                    gint           *argc,
                    gchar        ***argv,
@@ -1170,7 +1369,7 @@ parse_short_option (GOptionContext *context,
            value = NULL;
          else
            {
-             if (*new_index > index)
+             if (*new_idx > idx)
                {
                  g_set_error (error, 
                               G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
@@ -1179,27 +1378,27 @@ parse_short_option (GOptionContext *context,
                  return FALSE;
                }
 
-             if (index < *argc - 1)
+             if (idx < *argc - 1)
                {
                  if (!OPTIONAL_ARG (&group->entries[j]))       
                    {    
-                     value = (*argv)[index + 1];
-                     add_pending_null (context, &((*argv)[index + 1]), NULL);
-                     *new_index = index+1;
+                     value = (*argv)[idx + 1];
+                     add_pending_null (context, &((*argv)[idx + 1]), NULL);
+                     *new_idx = idx + 1;
                    }
                  else
                    {
-                      if ((*argv)[index + 1][0] == '-') 
+                      if ((*argv)[idx + 1][0] == '-') 
                        value = NULL;
                      else
                        {
-                         value = (*argv)[index + 1];
-                         add_pending_null (context, &((*argv)[index + 1]), NULL);
-                         *new_index = index + 1;
+                         value = (*argv)[idx + 1];
+                         add_pending_null (context, &((*argv)[idx + 1]), NULL);
+                         *new_idx = idx + 1;
                        }
                    }
                }
-             else if (index >= *argc - 1 && OPTIONAL_ARG (&group->entries[j]))
+             else if (idx >= *argc - 1 && OPTIONAL_ARG (&group->entries[j]))
                value = NULL;
              else
                {
@@ -1229,7 +1428,7 @@ parse_short_option (GOptionContext *context,
 static gboolean
 parse_long_option (GOptionContext *context,
                   GOptionGroup   *group,
-                  gint           *index,
+                  gint           *idx,
                   gchar          *arg,
                   gboolean        aliased,
                   gint           *argc,
@@ -1241,7 +1440,7 @@ parse_long_option (GOptionContext *context,
 
   for (j = 0; j < group->n_entries; j++)
     {
-      if (*index >= *argc)
+      if (*idx >= *argc)
        return TRUE;
 
       if (aliased && (group->entries[j].flags & G_OPTION_FLAG_NOALIAS))
@@ -1251,14 +1450,17 @@ parse_long_option (GOptionContext *context,
          strcmp (arg, group->entries[j].long_name) == 0)
        {
          gchar *option_name;
+         gboolean retval;
 
          option_name = g_strconcat ("--", group->entries[j].long_name, NULL);
-         parse_arg (context, group, &group->entries[j],
-                    NULL, option_name, error);
+         retval = parse_arg (context, group, &group->entries[j],
+                             NULL, option_name, error);
          g_free(option_name);
          
-         add_pending_null (context, &((*argv)[*index]), NULL);
+         add_pending_null (context, &((*argv)[*idx]), NULL);
          *parsed = TRUE;
+
+         return retval;
        }
       else
        {
@@ -1270,22 +1472,22 @@ parse_long_option (GOptionContext *context,
              gchar *value = NULL;
              gchar *option_name;
 
-             add_pending_null (context, &((*argv)[*index]), NULL);
+             add_pending_null (context, &((*argv)[*idx]), NULL);
              option_name = g_strconcat ("--", group->entries[j].long_name, NULL);
 
              if (arg[len] == '=')
                value = arg + len + 1;
-             else if (*index < *argc - 1) 
+             else if (*idx < *argc - 1) 
                {
                  if (!(group->entries[j].flags & G_OPTION_FLAG_OPTIONAL_ARG))  
                    {    
-                     value = (*argv)[*index + 1];
-                     add_pending_null (context, &((*argv)[*index + 1]), NULL);
-                     (*index)++;
+                     value = (*argv)[*idx + 1];
+                     add_pending_null (context, &((*argv)[*idx + 1]), NULL);
+                     (*idx)++;
                    }
                  else
                    {
-                      if ((*argv)[*index + 1][0] == '-') 
+                      if ((*argv)[*idx + 1][0] == '-') 
                        {
                          gboolean retval;
                          retval = parse_arg (context, group, &group->entries[j],
@@ -1296,13 +1498,13 @@ parse_long_option (GOptionContext *context,
                        }
                      else
                        {
-                         value = (*argv)[*index + 1];
-                         add_pending_null (context, &((*argv)[*index + 1]), NULL);
-                         (*index)++;
+                         value = (*argv)[*idx + 1];
+                         add_pending_null (context, &((*argv)[*idx + 1]), NULL);
+                         (*idx)++;
                        }
                    }
                }
-             else if (*index >= *argc - 1 &&
+             else if (*idx >= *argc - 1 &&
                       group->entries[j].flags & G_OPTION_FLAG_OPTIONAL_ARG)
                {
                    gboolean retval;
@@ -1340,7 +1542,7 @@ parse_long_option (GOptionContext *context,
 static gboolean
 parse_remaining_arg (GOptionContext *context,
                     GOptionGroup   *group,
-                    gint           *index,
+                    gint           *idx,
                     gint           *argc,
                     gchar        ***argv,
                     GError        **error,
@@ -1350,7 +1552,7 @@ parse_remaining_arg (GOptionContext *context,
 
   for (j = 0; j < group->n_entries; j++)
     {
-      if (*index >= *argc)
+      if (*idx >= *argc)
        return TRUE;
 
       if (group->entries[j].long_name[0])
@@ -1360,9 +1562,9 @@ parse_remaining_arg (GOptionContext *context,
                             group->entries[j].arg == G_OPTION_ARG_STRING_ARRAY ||
                            group->entries[j].arg == G_OPTION_ARG_FILENAME_ARRAY, FALSE);
       
-      add_pending_null (context, &((*argv)[*index]), NULL);
+      add_pending_null (context, &((*argv)[*idx]), NULL);
       
-      if (!parse_arg (context, group, &group->entries[j], (*argv)[*index], "", error))
+      if (!parse_arg (context, group, &group->entries[j], (*argv)[*idx], "", error))
        return FALSE;
       
       *parsed = TRUE;
@@ -1568,8 +1770,6 @@ g_option_context_parse (GOptionContext   *context,
                        print_help (context, FALSE, NULL);                    
                      else if (strncmp (arg, "help-", 5) == 0)
                        {
-                         GList *list;
-                         
                          list = context->groups;
                          
                          while (list)
@@ -1640,17 +1840,19 @@ g_option_context_parse (GOptionContext   *context,
                }
              else
                { /* short option */
-                 gint j, new_i = i, arg_length;
+                 gint new_i = i, arg_length;
                  gboolean *nulled_out = NULL;
+                  gboolean has_h_entry = context_has_h_entry (context);
                  arg = (*argv)[i] + 1;
                   arg_length = strlen (arg);
                   nulled_out = g_newa (gboolean, arg_length);
                   memset (nulled_out, 0, arg_length * sizeof (gboolean));
                  for (j = 0; j < arg_length; j++)
                    {
-                     if (context->help_enabled && arg[j] == '?')
-                       print_help (context, TRUE, NULL);
-                     parsed = FALSE;
+                     if (context->help_enabled && (arg[j] == '?' ||
+                        (arg[j] == 'h' && !has_h_entry)))
+                        print_help (context, TRUE, NULL);
+                      parsed = FALSE;
                      if (context->main_group &&
                          !parse_short_option (context, context->main_group,
                                               i, &new_i, arg[j],
@@ -1953,9 +2155,8 @@ g_option_group_set_parse_hooks (GOptionGroup     *group,
  * Associates a function with @group which will be called 
  * from g_option_context_parse() when an error occurs.
  *
- * Note that the user data to be passed to @pre_parse_func and
- * @post_parse_func can be specified when constructing the group
- * with g_option_group_new().
+ * Note that the user data to be passed to @error_func can be
+ * specified when constructing the group with g_option_group_new().
  *
  * Since: 2.6
  **/
@@ -2002,11 +2203,11 @@ g_option_group_set_translate_func (GOptionGroup   *group,
   group->translate_notify = destroy_notify;
 }
 
-static gchar *
+static const gchar *
 dgettext_swapped (const gchar *msgid, 
                  const gchar *domainname)
 {
-  return dgettext (domainname, msgid);
+  return g_dgettext (domainname, msgid);
 }
 
 /**
@@ -2048,7 +2249,7 @@ g_option_group_set_translation_domain (GOptionGroup *group,
  * (see g_option_context_set_description()).
  *
  * If you are using gettext(), you only need to set the translation
- * domain, see g_context_group_set_translation_domain().
+ * domain, see g_option_context_set_translation_domain().
  *
  * Since: 2.12
  **/
@@ -2101,7 +2302,8 @@ g_option_context_set_translation_domain (GOptionContext *context,
  * program functionality. 
  *
  * Note that the summary is translated (see 
- * g_option_context_set_translate_func(), g_option_context_set_translation_domain()).
+ * g_option_context_set_translate_func() and
+ * g_option_context_set_translation_domain()).
  *
  * Since: 2.12
  */
@@ -2177,7 +2379,3 @@ g_option_context_get_description (GOptionContext *context)
 
   return context->description;
 }
-
-
-#define __G_OPTION_C__
-#include "galiasdef.c"