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
107
108
109
110
111
112
113
|
#include "cgit.h"
#include "config.h"
#define MAX_INCLUDE_NESTING 8
static int next_char(FILE *f)
{
int c = fgetc(f);
if (c == '\r') {
c = fgetc(f);
if (c != '\n') {
ungetc(c, f);
c = '\r';
}
}
return c;
}
static void skip_line(FILE *f)
{
int c;
while ((c = next_char(f)) && c != '\n' && c != EOF)
;
}
static int next_content_char(FILE *f)
{
int c = next_char(f);
for (;;) {
if (c == EOF)
return EOF;
if (c == '#' || c == ';')
skip_line(f);
else if (!isspace(c))
return c;
c = next_char(f);
}
}
static int read_entry(FILE *f, struct strbuf *name, struct strbuf *value)
{
int c;
strbuf_reset(value);
for (;;) {
c = next_content_char(f);
if (c == EOF)
return 0;
strbuf_reset(name);
while (c != '=' && c != '\n' && c != EOF) {
strbuf_addch(name, c);
c = next_char(f);
}
if (c == EOF)
return 0;
if (c != '=')
continue;
c = next_char(f);
while (c != '\n' && c != EOF) {
strbuf_addch(value, c);
c = next_char(f);
}
return 1;
}
}
int config_file_parse(const char *filename, config_file_value_fn fn)
{
static int nesting;
struct strbuf name = STRBUF_INIT;
struct strbuf value = STRBUF_INIT;
FILE *f;
if (nesting > MAX_INCLUDE_NESTING)
return -1;
if (!(f = fopen(filename, "r")))
return -1;
nesting++;
while (read_entry(f, &name, &value))
fn(name.buf, value.buf);
nesting--;
fclose(f);
strbuf_release(&name);
strbuf_release(&value);
return 0;
}
|