summaryrefslogtreecommitdiffstats
path: root/src/foodopts.c
blob: eff281ce1db037222c8f3b546366705a926ecc70 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <stdio.h>
#include <stdlib.h>
#include "foodopts.h"

static struct option *
to_getopt_longopts(const struct foodoption * src)
{
  int l = 0;
  while( src[l].name    != 0
      || src[l].has_arg != 0
      || src[l].flag    != 0
      || src[l].val     != 0) {
    l++;
  }

  struct option * dst = (struct option *)malloc(sizeof(struct option) * (l + 1));
  int i = 0;
  while( src[i].name    != 0
      || src[i].has_arg != 0
      || src[i].flag    != 0
      || src[i].val     != 0) {
    dst[i].name    = src[i].name;
    dst[i].has_arg = src[i].has_arg;
    dst[i].flag    = src[i].flag;
    dst[i].val     = src[i].val;
    i++;
  }
  dst[i].name    = 0;
  dst[i].has_arg = 0;
  dst[i].flag    = 0;
  dst[i].val     = 0;

  return dst;
}

int
get_foodopt(int argc, char *const argv[],
            const char *optstring,
            const struct foodoption *lopts,
            int *longindex)
{
  struct option * o = to_getopt_longopts(lopts);
  int rc = getopt_long(argc, argv, optstring, o, longindex);

  free(o);
  return rc;
}

const char *
get_argument(const char opt,
             const struct foodoption *lopts)
{
  int i = 0;
  while ((lopts[i].name)
         && (lopts[i].val)) {
    if (lopts[i].val == opt)
      return lopts[i].arg;
    i++;
  }
  return NULL;
}

void
foodopt_help(char * argv0,
             const struct foodoption *lopts)
{
  fprintf(stderr, "%s [OPTION ...] FILE ...\n", argv0);
  fprintf(stderr, "\nOPTIONS:\n");


  int i = 0;
  while ((lopts[i].name)
         && (lopts[i].val)) {
    if (lopts[i].category) {
      fprintf(stderr, "\n%s:\n", lopts[i].category);
    }
    fprintf(stderr, "-%c, --%s%s%s: %s\n",
            lopts[i].val,
            lopts[i].name,
            (lopts[i].has_arg == required_argument ||
             lopts[i].has_arg == optional_argument) ? " " : "",
            (lopts[i].has_arg == required_argument ||
             lopts[i].has_arg == optional_argument) ? lopts[i].arg : "",
            lopts[i].help);
    i++;
  }
}