summaryrefslogtreecommitdiff
path: root/src/grijp.c
blob: 0c406f43988c44990f121a198474249acc394da1 (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
#include <assert.h>
#include <errno.h>
#include <getopt.h>
#include <pwd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>

#include "util/debug.h"
#include "util/error.h"
#include "util/loop_args.h"
#include "util/versie.h"

#include "io/read_file.h"

char *gpats;

static void usage(FILE *f) {
  fprintf(f,
      "Gebruik: grijp [-hV] [PATRONEN] [BESTAND]...\n"
      "\n"
      "TODO\n"
      "\n"
      "  -h          Toon deze hulptekst\n"
      "  -V          Toon versienummer\n");
}

// Returns pointer to argument array containing patterns and then the file names
static char** parse_options(int argc, char **argv) {
  int opt;
  while ((opt = getopt(argc, argv, "hV")) != -1) {
    switch (opt) {
      case 'h':
        usage(stdout);
        exit(0);

      case 'V':
        drukkedoos_print_versie(stdout);
        exit(0);

      case '?':
        fprintf(stderr, "grijp: Ongeldige optie: -%c\n", optopt);
        usage(stderr);
        exit(1);
    }
  }

  return argv + optind;
}

static int process(char *fname, bool isstdin) {
  FILE *stream = isstdin ? stdin : fopen(fname, "rb");

  char **patterns;
  size_t npat = 0;
  {
    size_t cappat = 1 << 4;
    patterns = calloc(sizeof(char*), cappat);

    char *s = gpats;
    char *pat = NULL;
    while ((pat = strtok(s, "\n")) != NULL) {
      s = NULL;

      if (npat == cappat) {
        cappat *= 2;
        patterns = realloc(patterns, sizeof(char*)*cappat);
      }
      patterns[npat] = strdup(pat);
      npat++;
    }
  }

  char *line = NULL;
  size_t linen = 0;

  ssize_t nread = 0;
  while ((errno = 0, nread = getline(&line, &linen, stream)) != -1) {
    for (size_t i = 0; i < npat; i++) {
      char *pat = patterns[i];
      if (strstr(line, pat) == NULL) continue;
      printf("%s", line);
    }
  }
  free(line);

  for (size_t i = 0; i < npat; i++) free(patterns[i]);
  free(patterns);

  return 0;
}

int entry_grijp(int argc, char **argv) {
  char **args = parse_options(argc, argv);
  if (*args == NULL) {
    fprintf(stderr, "grijp: geen patroon gegeven\n");
    return 1;
  }

  gpats = *args;
  args++;
  return loop_args(args, process);
}