1 /*
2 * Copyright (C) 2019-2020 Scoopta
3 * This file is part of Wofi
4 * Wofi is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
8
9 Wofi is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with Wofi. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18 #include <config.h>
19
20 #include <stdio.h>
21 #include <stdarg.h>
22 #include <string.h>
23 #include <stdlib.h>
24
25 #include <map.h>
26
config_put(struct map * map,char * line)27 void config_put(struct map* map, char* line) {
28 size_t line_size = strlen(line);
29 char* new_line = calloc(1, line_size + 1);
30 size_t new_line_count = 0;
31 for(size_t count = 0; count < line_size; ++count) {
32 if(line[count] == '\\') {
33 new_line[new_line_count++] = line[++count];
34 } else if(line[count] == '#') {
35 break;
36 } else {
37 new_line[new_line_count++] = line[count];
38 }
39 }
40 line = new_line;
41 char* equals = strchr(line, '=');
42 if(equals == NULL) {
43 free(line);
44 return;
45 }
46 *equals = 0;
47 char* key = equals - 1;
48 while(*key == ' ') {
49 --key;
50 }
51 *(key + 1) = 0;
52 char* value = equals + 1;
53 while(*value == ' ') {
54 ++value;
55 }
56 size_t len = strlen(value);
57 char* end = value + len - 1;
58 if(*end == '\n' || *end == ' ') {
59 *end = 0;
60 }
61 map_put(map, line, value);
62 free(line);
63 }
64
config_load(struct map * map,const char * config)65 void config_load(struct map* map, const char* config) {
66 FILE* file = fopen(config, "r");
67 char* line = NULL;
68 size_t size = 0;
69 while(getline(&line, &size, file) != -1) {
70 config_put(map, line);
71 }
72 free(line);
73 fclose(file);
74 }
75
config_get(struct map * config,const char * key,char * def_opt)76 char* config_get(struct map* config, const char* key, char* def_opt) {
77 char* opt = map_get(config, key);
78 if(opt == NULL) {
79 opt = def_opt;
80 }
81 return opt;
82 }
83
config_get_mnemonic(struct map * config,const char * key,char * def_opt,uint8_t num_choices,...)84 uint8_t config_get_mnemonic(struct map* config, const char* key, char* def_opt, uint8_t num_choices, ...) {
85 char* opt = config_get(config, key, def_opt);
86 va_list ap;
87 va_start(ap, num_choices);
88 uint8_t result = 0;
89 for(uint8_t i = 0; i < num_choices; i++) {
90 char* cmp_str = va_arg(ap, char*);
91 if(strcmp(opt, cmp_str) == 0) {
92 result = i;
93 break;
94 }
95 }
96 va_end(ap);
97 return result;
98 }
99