Coverage Report

Created: 2025-08-28 06:24

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