diff options
Diffstat (limited to 'options.c')
-rw-r--r-- | options.c | 95 |
1 files changed, 95 insertions, 0 deletions
diff --git a/options.c b/options.c new file mode 100644 index 0000000..2619602 --- /dev/null +++ b/options.c @@ -0,0 +1,95 @@ +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include "options.h" + + +struct options parse_options(int argc, char **argv) { + size_t filters_cap = 32, filters_len = 0; + struct filter_rule *filters = malloc(filters_cap * sizeof(struct filter_rule)); + + size_t cachetags_cap = 32, cachetags_len = 0; + char **cachetags = malloc(cachetags_cap * sizeof(char*)); + + char *rootpath = NULL; + + int print_depth = 1; + + bool debug = false; + + for (int i = 1; i < argc; i++) { + if (argv[i][0] != '-') { + if (rootpath) { + fprintf(stderr, "Multiple root paths given\n"); + exit(1); + } + rootpath = strdup(argv[i]); + + } else if (strcmp(argv[i], "--exclude") == 0) { + if (i + 1 >= argc) { + fprintf(stderr, "'--exclude' takes an argument\n"); + exit(1); + } + + if (filters_len >= filters_cap) { + filters_cap *= 2; + filters = realloc(filters, filters_cap * sizeof(struct filter_rule)); + } + struct filter_rule rule = parse_exclude_rule(argv[i+1]); + filters[filters_len++] = rule; + + i++; + + } else if (strcmp(argv[i], "--exclude-if-present") == 0) { + if (i + 1 >= argc) { + fprintf(stderr, "'--exclude-if-present' takes an argument\n"); + exit(1); + } + + if (cachetags_len >= cachetags_cap) { + cachetags_cap *= 2; + cachetags = realloc(cachetags, cachetags_cap * sizeof(char*)); + } + cachetags[cachetags_len++] = strdup(argv[i+1]); + + i++; + + } else if (strcmp(argv[i], "-d") == 0) { + if (i + 1 >= argc) { + fprintf(stderr, "'-d' takes an argument\n"); + exit(1); + } + + char *endp; + print_depth = strtol(argv[i+1], &endp, 10); + if (!*argv[i+1] || *endp) { + fprintf(stderr, "Invalid argument to '-d': '%s'\n", argv[i+1]); + exit(1); + } + + i++; + + } else if (strcmp(argv[i], "--debug") == 0) { + debug = true; + + } else { + fprintf(stderr, "Unrecognised argument: '%s'\n", argv[i]); + exit(1); + } + } + + if (rootpath == NULL) { + fprintf(stderr, "No root path provided\n"); + exit(1); + } + + return (struct options){ + .nfilters = filters_len, + .filters = filters, + .ncachetags = cachetags_len, + .cachetags = cachetags, + .rootpath = rootpath, + .print_depth = print_depth, + .debug = debug, + }; +} |