config.c (1520B)
1 #include <stdlib.h> 2 #include <string.h> 3 #include "benhoyt/inih.h" 4 #include "rxi/log.h" 5 #include "infrastructure/config.h" 6 #include "common/resp.h" 7 8 resp_object *global_cfg = NULL; 9 resp_object *pending_cfg = NULL; 10 11 static const char *stored_config_path = NULL; 12 13 static int config_handler(void *user, const char *section, const char *name, const char *value, int lineno) { 14 (void)lineno; 15 resp_object *cfg = (resp_object *)user; 16 resp_object *sec = resp_map_get(cfg, section); 17 if (!sec || sec->type != RESPT_ARRAY) { 18 sec = resp_array_init(); 19 resp_map_set(cfg, section, sec); 20 sec = resp_map_get(cfg, section); 21 } 22 resp_array_append_bulk(sec, name); 23 resp_array_append_bulk(sec, value); 24 return 1; 25 } 26 27 void config_init(void) { 28 global_cfg = resp_array_init(); 29 config_load(global_cfg, config_get_path()); 30 } 31 32 int config_load(resp_object *cfg, const char *path) { 33 return ini_parse(path, config_handler, cfg); 34 } 35 36 void config_pending_init(void) { 37 pending_cfg = resp_array_init(); 38 } 39 40 void config_swap(void) { 41 resp_object *old = global_cfg; 42 global_cfg = pending_cfg; 43 pending_cfg = old; 44 if (old) resp_free(old); 45 } 46 47 int config_reload(void) { 48 config_pending_init(); 49 int r = config_load(pending_cfg, config_get_path()); 50 if (r < 0) return -1; 51 config_swap(); 52 return 0; 53 } 54 55 void config_set_path(const char *path) { 56 if (stored_config_path) free((void*)stored_config_path); 57 stored_config_path = path ? strdup(path) : NULL; 58 } 59 60 const char *config_get_path(void) { 61 return stored_config_path; 62 }