aboutsummaryrefslogtreecommitdiff
path: root/src/config.c
blob: e634002e7e969adc848684fc17708483029a6d11 (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
#define _GNU_SOURCE

#include <config.h>
#include <filehandler.h>
#include <list.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <util.h>

config_t *
config_parse(char *content)
{
  list_t *keys = list_create(sizeof(ptr_wrapper_t));
  list_t *values = list_create(sizeof(ptr_wrapper_t));
  list_t *array_values = list_create(sizeof(ptr_wrapper_t));

  char *buffer = strdup(content);
  /* For free() */
  char *x = buffer;

  char *key = trim(strsep(&buffer, DELIM));

  while (buffer != NULL) {
    buffer = ltrim(buffer);
    list_wrap_and_add(keys, strdup(key));

    if (*buffer == '{') {
      buffer++;
      list_t *l = list_create(sizeof(ptr_wrapper_t));
      char *raw_array = strsep(&buffer, "}");

      char *value = strsep(&raw_array, DELIM_ARRAY);
      while (value != NULL) {
        list_wrap_and_add(l, strdup(trim(value)));
        value = strsep(&raw_array, DELIM_ARRAY);
      }

      list_wrap_and_add(array_values, l);
      list_wrap_and_add(values, NULL);
    } else {
      char *value = trim(strsep(&buffer, "\n"));

      list_wrap_and_add(array_values, NULL);
      list_wrap_and_add(values, strdup(value));
    }

    key = trim(strsep(&buffer, DELIM));
  }

  free(x);

  config_t *config = malloc(sizeof(config_t));
  config->keys = keys;
  config->values = values;
  config->array_values = array_values;
  return config;
}

void
config_delete(config_t *config)
{
  for (size_t i = 0; i < config->keys->size; i++) {
    ptr_wrapper_t *wrapper;

    wrapper = list_get(config->keys, i);
    if (wrapper->ptr != NULL)
      free(wrapper->ptr);

    wrapper = list_get(config->values, i);
    if (wrapper->ptr != NULL)
      free(wrapper->ptr);

    list_t *l = get_wrapped(list_get(config->array_values, i));
    if (l != NULL) {
      for (size_t y = 0; y < l->size; y++) {
        wrapper = list_get(l, y);
        free(wrapper->ptr);
      }
      list_delete(l);
    }
  }

  list_delete(config->keys);
  list_delete(config->values);
  list_delete(config->array_values);
  free(config);
}

config_t *
config_fetch_and_parse(char *path)
{
  FILE *f = fopen(path, "r");
  if (f == NULL) {
    printf("Could not open %s\n", path);
    return NULL;
  }

  size_t s = fsize(f);
  char *content = fcontent(f, s);
  fclose(f);

  config_t *config = config_parse(content);
  free(content);

  return config;
}