File: ini.c

package info (click to toggle)
i3blocks 1.5-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 548 kB
  • sloc: ansic: 2,439; makefile: 30; javascript: 29; sh: 19
file content (106 lines) | stat: -rw-r--r-- 2,328 bytes parent folder | download
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
/*
 * ini.c - generic INI parser
 * Copyright (C) 2017-2019  Vivien Didelot
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <ctype.h>
#include <string.h>

#include "ini.h"
#include "line.h"
#include "log.h"

struct ini {
	ini_sec_cb_t *sec_cb;
	ini_prop_cb_t *prop_cb;
	void *data;
};

static int ini_section(struct ini *ini, char *section)
{
	if (!ini->sec_cb)
		return 0;

	return ini->sec_cb(section, ini->data);
}

static int ini_property(struct ini *ini, char *key, char *value)
{
	if (!ini->prop_cb)
		return 0;

	return ini->prop_cb(key, value, ini->data);
}

static int ini_parse_line(char *line, size_t num, void *data)
{
	/* comment or empty line? */
	if (*line == '\0' || *line == '#')
		return 0;

	/* section? */
	if (*line == '[') {
		char *closing, *section;

		closing = strchr(line, ']');
		if (!closing) {
			error("malformated section \"%s\"", line);
			return -EINVAL;
		}

		if (*(closing + 1) != '\0') {
			error("trailing characters \"%s\"", closing);
			return -EINVAL;
		}

		section = line + 1;
		*closing = '\0';

		return ini_section(data, section);
	}

	/* property? */
	if (isalpha(*line) || *line == '_') {
		char *equals, *key, *value;

		equals = strchr(line, '=');
		if (!equals) {
			error("malformated property, should be a key=value pair");
			return -EINVAL;
		}

		*equals = '\0';
		key = line;
		value = equals + 1;

		return ini_property(data, key, value);
	}

	error("invalid INI syntax for line: \"%s\"", line);
	return -EINVAL;
}

int ini_read(int fd, size_t count, ini_sec_cb_t *sec_cb, ini_prop_cb_t *prop_cb,
	     void *data)
{
	struct ini ini = {
		.sec_cb = sec_cb,
		.prop_cb = prop_cb,
		.data = data,
	};

	return line_read(fd, count, ini_parse_line, &ini);
}