aboutsummaryrefslogtreecommitdiff
path: root/src/config.c
blob: ce2c7b06224b42626d4ff1de6facd9fb331fc39f (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
#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));

  ptr_wrapper_t *wrapper;

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

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

  while (buffer != NULL) {
    buffer = ltrim(buffer);

    wrapper = malloc(sizeof(ptr_wrapper_t));
    wrapper->ptr = strdup(key);
    list_add(keys, wrapper);

    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) {
        wrapper = malloc(sizeof(ptr_wrapper_t));
        wrapper->ptr = strdup(trim(value));
        list_add(l, wrapper);

        value = strsep(&raw_array, DELIM_ARRAY);
      }

      list_add(array_values, l);

      wrapper = malloc(sizeof(ptr_wrapper_t));
      wrapper->ptr = NULL;
      list_add(values, wrapper);
    } else {
      char *value = trim(strsep(&buffer, "\n"));

      wrapper = malloc(sizeof(ptr_wrapper_t));
      wrapper->ptr = NULL;
      list_add(array_values, wrapper);

      wrapper = malloc(sizeof(ptr_wrapper_t));
      wrapper->ptr = strdup(value);
      list_add(values, wrapper);
    }

    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;
}