summaryrefslogtreecommitdiff
path: root/lib/args.c
blob: 5311acf0c997ac341b1ef306dfb48572e805f734 (plain)
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#include "lslib.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifndef MAJOR
#define MAJOR 0
#endif

#ifndef MINOR
#define MINOR 0
#endif

#ifndef PATCH
#define PATCH 0
#endif

void check_arg (char* arg) {
    if (arg == NULL) {
        error("expected another argument after option");
    }
}

void global_help(void (*help)(void)) {
    printf("LazySphere v%d.%d.%d multi-call binary.\n\n", MAJOR, MINOR, PATCH);
    help();
    exit(EXIT_SUCCESS);
}

void parse_help(int argc, char** argv, void (*help)(void)) {
    int i;

    if (argc < 1) return;

    for (i = 0; i < argc; i++) {
        if (!prefix("-", argv[i]) || streql("-", argv[i])) break;
        if (help != NULL && streql("--help", argv[i])) global_help(help);
    }
}

int parse_args(int argc, char** argv, void (*help)(void), int (*short_arg)(char, char*), int (*long_arg)(char*, char*)) {
    int start, i, current;
    char* next_arg;

    if (argc < 1) return 0;

    start = 0;
    for (i = 0; i < argc; i++) {
        
        if (!prefix("-", argv[i]) || streql("-", argv[i])) break;
        if (help != NULL && streql("--help", argv[i])) global_help(help);

        if (i + 1 == argc) {
            next_arg = NULL;
        } else {
            next_arg = argv[i+1];
        }

        current = i;

        if (prefix("--", argv[i])) {
            int r;

            if (long_arg == NULL) {
                goto exit;
            }
            
            r = long_arg(argv[current], next_arg);
            
            if (r == ARG_USED) {
                i++;
                start++;
            } else if (r == ARG_IGNORE) {
                goto exit;
            } else if (r == ARG_INVALID) {
                error("invalid argument %s", argv[current]);
            
            }
        } else {
            size_t j;
            int r;

            if (short_arg == NULL) {
                goto exit;
            }

            for (j = 1; j < strlen(argv[current]); j++) {
                
                r = short_arg(argv[current][j], next_arg);
                
                if (r == ARG_USED) {
                    i++;
                    start++;
                } else if (r == ARG_IGNORE) {
                    goto exit;
                } else if (r == ARG_INVALID) {
                    error("invalid argument -%c", argv[current][j]);
                }
            }
        }

        start++;
    }

exit:

    return start;
}