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

#include <config.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(list_t));

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

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

  while (buffer != NULL) {
    buffer = ltrim(buffer);
    list_add(keys, wrap_ptr(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_add(l, wrap_ptr(strdup(trim(value))));
        value = strsep(&raw_array, DELIM_ARRAY);
      }

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

      list_add(array_values, wrap_ptr(NULL));
      list_add(values, wrap_ptr(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;
}