summaryrefslogtreecommitdiff
path: root/options.c
blob: 2619602323911bec6936bb04703fe43065810af7 (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
#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,
  };
}